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


##########
c/sedona-geos/src/st_buffer.rs:
##########
@@ -54,65 +67,191 @@ impl SedonaScalarKernel for STBuffer {
         arg_types: &[SedonaType],
         args: &[ColumnarValue],
     ) -> Result<ColumnarValue> {
-        // Default params
-        let params_builder = BufferParams::builder();
+        invoke_batch_impl(arg_types, args)
+    }
+}
 
-        let params = params_builder
-            .build()
-            .map_err(|e| DataFusionError::External(Box::new(e)))?;
-
-        // Extract the constant scalar value before looping over the input 
geometries
-        let distance: Option<f64>;
-        let arg1 = args[1].cast_to(&DataType::Float64, None)?;
-        if let ColumnarValue::Scalar(scalar_arg) = &arg1 {
-            if scalar_arg.is_null() {
-                distance = None;
-            } else {
-                distance = Some(f64::try_from(scalar_arg.clone())?);
-            }
-        } else {
-            return Err(DataFusionError::Execution(format!(
-                "Invalid distance: {:?}",
-                args[1]
-            )));
-        }
+pub fn st_buffer_style_impl() -> ScalarKernelRef {
+    Arc::new(STBufferStyle {})
+}
+#[derive(Debug)]
+struct STBufferStyle {}
 
-        let executor = GeosExecutor::new(arg_types, args);
-        let mut builder = BinaryBuilder::with_capacity(
-            executor.num_iterations(),
-            WKB_MIN_PROBABLE_BYTES * executor.num_iterations(),
-        );
-        executor.execute_wkb_void(|wkb| {
-            match (wkb, distance) {
-                (Some(wkb), Some(distance)) => {
-                    invoke_scalar(&wkb, distance, &params, &mut builder)?;
-                    builder.append_value([]);
-                }
-                _ => builder.append_null(),
-            }
+impl SedonaScalarKernel for STBufferStyle {
+    fn return_type(&self, args: &[SedonaType]) -> Result<Option<SedonaType>> {
+        let matcher = ArgMatcher::new(
+            vec![
+                ArgMatcher::is_geometry(),
+                ArgMatcher::is_numeric(),
+                ArgMatcher::is_string(),
+            ],
+            WKB_GEOMETRY,
+        );
 
-            Ok(())
-        })?;
+        matcher.match_args(args)
+    }
 
-        executor.finish(Arc::new(builder.finish()))
+    fn invoke_batch(
+        &self,
+        arg_types: &[SedonaType],
+        args: &[ColumnarValue],
+    ) -> Result<ColumnarValue> {
+        invoke_batch_impl(arg_types, args)
     }
 }
 
+fn invoke_batch_impl(arg_types: &[SedonaType], args: &[ColumnarValue]) -> 
Result<ColumnarValue> {
+    let executor = GeosExecutor::new(arg_types, args);
+    let mut builder = BinaryBuilder::with_capacity(
+        executor.num_iterations(),
+        WKB_MIN_PROBABLE_BYTES * executor.num_iterations(),
+    );
+
+    // Extract Args
+    let distance_value = args[1]
+        .cast_to(&DataType::Float64, None)?
+        .to_array(executor.num_iterations())?;
+    let distance_array = as_float64_array(&distance_value)?;
+    let mut distance_iter = distance_array.iter();
+
+    let buffer_style_params = extract_optional_string(args.get(2))?;
+
+    // Build BufferParams based on style parameters
+    let params = parse_buffer_params(buffer_style_params.as_deref())?;
+
+    executor.execute_wkb_void(|wkb| {
+        match (wkb, distance_iter.next().unwrap()) {
+            (Some(wkb), Some(distance)) => {
+                builder.append_value(invoke_scalar(&wkb, distance, &params)?);
+            }
+            _ => builder.append_null(),
+        }
+        Ok(())
+    })?;
+
+    executor.finish(Arc::new(builder.finish()))
+}
+
 fn invoke_scalar(
     geos_geom: &geos::Geometry,
     distance: f64,
     params: &BufferParams,
-    writer: &mut impl std::io::Write,
-) -> Result<()> {
+) -> Result<Vec<u8>> {
     let geometry = geos_geom
         .buffer_with_params(distance, params)
         .map_err(|e| DataFusionError::External(Box::new(e)))?;
     let wkb = geometry
         .to_wkb()
         .map_err(|e| DataFusionError::Execution(format!("Failed to convert to 
wkb: {e}")))?;
 
-    writer.write_all(wkb.as_ref())?;
-    Ok(())
+    Ok(wkb.into())
+}
+
+fn extract_optional_string(arg: Option<&ColumnarValue>) -> 
Result<Option<String>> {
+    let Some(arg) = arg else { return Ok(None) };
+    let casted = arg.cast_to(&DataType::Utf8, None)?;
+    match &casted {
+        ColumnarValue::Scalar(ScalarValue::Utf8(Some(s)) | 
ScalarValue::LargeUtf8(Some(s))) => {
+            Ok(Some(s.clone()))
+        }
+        ColumnarValue::Scalar(scalar) if scalar.is_null() => Ok(None),
+        ColumnarValue::Scalar(_) => Ok(None),
+        _ => Err(DataFusionError::Execution(format!(
+            "Expected scalar bufferStyleParameters, got: {arg:?}",
+        ))),
+    }
+}
+
+fn parse_buffer_params(params_str: Option<&str>) -> Result<BufferParams> {
+    let Some(params_str) = params_str else {
+        return BufferParams::builder()
+            .build()
+            .map_err(|e| DataFusionError::External(Box::new(e)));
+    };
+
+    let mut params_builder = BufferParams::builder();
+
+    for param in params_str.split_whitespace() {
+        let Some((key, value)) = param.split_once('=') else {
+            return Err(DataFusionError::Execution(format!(
+                "Missing value for buffer parameter: {param}",
+            )));
+        };
+
+        if key.eq_ignore_ascii_case("endcap") {
+            params_builder = 
params_builder.end_cap_style(parse_cap_style(value)?);
+        } else if key.eq_ignore_ascii_case("join") {
+            params_builder = 
params_builder.join_style(parse_join_style(value)?);
+        } else if key.eq_ignore_ascii_case("side") {
+            params_builder = 
params_builder.single_sided(is_single_sided(value)?);

Review Comment:
   We're still missing this logic:
   
https://github.com/apache/sedona/blame/d6ea87cf9f2a27adee00ff0fb41ee92002b9a834/common/src/main/java/org/apache/sedona/common/Functions.java#L399-L402
   
   Here's a better docstring to follow because the PostGIS docs hasn't been 
updated yet.
   
   - `side=both|left|right` : Defaults to `both`. Setting `left` or `right` 
enables a single-sided buffer operation on the geometry, with the buffered side 
aligned according to the direction of the line. This functionality is specific 
to LINESTRING geometry and has no impact on POINT or POLYGON geometries. By 
default, square end caps are applied when `left` or `right` are specified.
   
   Also, when I was experimenting with the python tests, they didn't behave as 
I thought they would. While I expected `side=right` to fail, I thought 
`side=right endcap=square` would pass, but the result was the same. I think 
it's possible there's another bug somewhere. Though I wouldn't worry about this 
for now. Just implement the logic for `side`, and we'll see if there's still 
strange behavior.



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