paleolimbot commented on code in PR #269:
URL: https://github.com/apache/sedona-db/pull/269#discussion_r2485196162


##########
rust/sedona-functions/src/st_dump.rs:
##########
@@ -0,0 +1,424 @@
+// 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, ListBuilder, StructBuilder, UInt32Builder},
+    ListArray,
+};
+use arrow_schema::{DataType, Field, Fields};
+use datafusion_common::error::Result;
+use datafusion_expr::{
+    scalar_doc_sections::DOC_SECTION_OTHER, ColumnarValue, Documentation, 
Volatility,
+};
+use geo_traits::{
+    GeometryCollectionTrait, GeometryTrait, GeometryType, 
MultiLineStringTrait, MultiPointTrait,
+    MultiPolygonTrait,
+};
+use sedona_common::sedona_internal_err;
+use sedona_expr::scalar_udf::{SedonaScalarKernel, SedonaScalarUDF};
+use sedona_geometry::wkb_factory::WKB_MIN_PROBABLE_BYTES;
+use sedona_schema::{
+    datatypes::{SedonaType, WKB_GEOMETRY},
+    matchers::ArgMatcher,
+};
+use std::sync::Arc;
+
+use crate::executor::WkbExecutor;
+
+/// ST_Dump() scalar UDF
+///
+/// Native implementation to get all the points of a geometry as MULTIPOINT
+pub fn st_dump_udf() -> SedonaScalarUDF {
+    SedonaScalarUDF::new(
+        "st_dump",
+        vec![Arc::new(STDump)],
+        Volatility::Immutable,
+        Some(st_dump_doc()),
+    )
+}
+
+fn st_dump_doc() -> Documentation {
+    Documentation::builder(
+        DOC_SECTION_OTHER,
+        "Extracts the components of a geometry.",
+        "ST_Dump (geom: Geometry)",
+    )
+    .with_argument("geom", "geometry: Input geometry")
+    .with_sql_example("SELECT ST_Dump(ST_GeomFromWKT('MULTIPOINT (0 1, 2 3, 4 
5)'))")
+    .build()
+}
+
+#[derive(Debug)]
+struct STDump;
+
+// This enum is solely for passing the subset of wkb geometry to 
STDumpStructBuilder.
+// Maybe we can pass the underlying raw WKB bytes directly, but this just 
works for now.
+enum SingleWkb<'a> {
+    Point(&'a wkb::reader::Point<'a>),
+    LineString(&'a wkb::reader::LineString<'a>),
+    Polygon(&'a wkb::reader::Polygon<'a>),
+}
+
+// A builder for a single struct of { path: [u32], geom: POINT | LINESTRING | 
POLYGON }
+struct STDumpStructBuilder<'a> {
+    struct_builder: &'a mut StructBuilder,
+}
+
+// A builder for a list of the structs
+struct STDumpBuilder {
+    builder: ListBuilder<StructBuilder>,
+}
+
+impl<'a> STDumpStructBuilder<'a> {
+    // This appends both path and geom at once.
+    fn append(
+        &mut self,
+        parent_path: &[u32],
+        cur_index: Option<u32>,
+        wkb: SingleWkb<'_>,
+    ) -> Result<()> {
+        let path_builder = self
+            .struct_builder
+            .field_builder::<ListBuilder<UInt32Builder>>(0)
+            .unwrap();
+
+        let path_array_builder = path_builder.values();
+        path_array_builder.append_slice(parent_path);
+        if let Some(cur_index) = cur_index {
+            path_array_builder.append_value(cur_index);
+        }
+        path_builder.append(true);
+
+        let geom_builder = self
+            .struct_builder
+            .field_builder::<BinaryBuilder>(1)
+            .unwrap();
+
+        let write_result = match wkb {
+            SingleWkb::Point(point) => {
+                wkb::writer::write_point(geom_builder, &point, 
&Default::default())
+            }
+            SingleWkb::LineString(line_string) => {
+                wkb::writer::write_line_string(geom_builder, &line_string, 
&Default::default())
+            }
+            SingleWkb::Polygon(polygon) => {
+                wkb::writer::write_polygon(geom_builder, &polygon, 
&Default::default())
+            }
+        };
+        if let Err(e) = write_result {
+            return sedona_internal_err!("Failed to write WKB: {e}");
+        }
+
+        geom_builder.append_value([]);
+
+        self.struct_builder.append(true);
+
+        Ok(())
+    }
+}
+
+impl STDumpBuilder {
+    fn new(num_iter: usize) -> Self {
+        let path_builder =
+            ListBuilder::with_capacity(UInt32Builder::with_capacity(num_iter), 
num_iter);
+        let geom_builder =
+            BinaryBuilder::with_capacity(num_iter, WKB_MIN_PROBABLE_BYTES * 
num_iter);
+        let struct_builder = StructBuilder::new(
+            geometry_dump_fields(),
+            vec![Box::new(path_builder), Box::new(geom_builder)],
+        );
+        let builder = ListBuilder::with_capacity(struct_builder, 
WKB_MIN_PROBABLE_BYTES * num_iter);
+
+        Self { builder }
+    }
+
+    fn append(&mut self, is_valid: bool) {
+        self.builder.append(is_valid);
+    }
+
+    fn append_null(&mut self) {
+        self.builder.append_null();
+    }
+
+    fn struct_builder<'a>(&'a mut self) -> STDumpStructBuilder<'a> {
+        STDumpStructBuilder {
+            struct_builder: self.builder.values(),
+        }
+    }
+
+    fn finish(&mut self) -> ListArray {
+        self.builder.finish()
+    }
+}
+
+impl SedonaScalarKernel for STDump {
+    fn return_type(&self, args: &[SedonaType]) -> Result<Option<SedonaType>> {
+        let matcher = ArgMatcher::new(vec![ArgMatcher::is_geometry()], 
geometry_dump_type());
+        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 = STDumpBuilder::new(executor.num_iterations());
+
+        executor.execute_wkb_void(|maybe_wkb| {
+            if let Some(wkb) = maybe_wkb {
+                let mut struct_builder = builder.struct_builder();
+
+                let mut cur_path: Vec<u32> = Vec::new();

Review Comment:
   It probably doesn't make much of a difference here but you could declare 
this outside the loop and reset the size to zero to reuse any previous heap 
allocation.



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