davidlghellin commented on code in PR #22890:
URL: https://github.com/apache/datafusion/pull/22890#discussion_r3391119951


##########
datafusion/spark/src/function/string/levenshtein.rs:
##########
@@ -0,0 +1,594 @@
+// 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::any::Any;
+use std::sync::Arc;
+
+use arrow::array::{Array, ArrayRef, Int32Array, Int64Array, OffsetSizeTrait};
+use arrow::datatypes::DataType;
+use datafusion_common::cast::{
+    as_generic_string_array, as_int32_array, as_string_view_array,
+};
+use datafusion_common::types::{NativeType, logical_int32, logical_string};
+use datafusion_common::utils::datafusion_strsim;
+use datafusion_common::{Result, ScalarValue, exec_err};
+use datafusion_expr::type_coercion::binary::{
+    binary_to_string_coercion, string_coercion,
+};
+use datafusion_expr::{
+    Coercion, ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Signature, 
TypeSignature,
+    TypeSignatureClass, Volatility,
+};
+use datafusion_functions::utils::make_scalar_function;
+
+/// Spark-compatible `levenshtein` function.
+///
+/// Differs from DataFusion core's `levenshtein` in that it supports an 
optional
+/// third argument `threshold`. When the computed Levenshtein distance exceeds
+/// the threshold, the function returns -1 instead of the actual distance.
+///
+/// ```sql
+/// levenshtein('kitten', 'sitting')     -- returns 3
+/// levenshtein('kitten', 'sitting', 2)  -- returns -1 (distance 3 > threshold 
2)
+/// levenshtein('kitten', 'sitting', 4)  -- returns 3  (distance 3 <= 
threshold 4)
+/// ```
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct SparkLevenshtein {
+    signature: Signature,
+}
+
+impl Default for SparkLevenshtein {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl SparkLevenshtein {
+    pub fn new() -> Self {
+        Self {
+            signature: Signature::one_of(
+                vec![
+                    TypeSignature::Coercible(vec![
+                        
Coercion::new_exact(TypeSignatureClass::Native(logical_string())),
+                        
Coercion::new_exact(TypeSignatureClass::Native(logical_string())),
+                    ]),
+                    TypeSignature::Coercible(vec![
+                        
Coercion::new_exact(TypeSignatureClass::Native(logical_string())),
+                        
Coercion::new_exact(TypeSignatureClass::Native(logical_string())),
+                        Coercion::new_implicit(
+                            TypeSignatureClass::Native(logical_int32()),
+                            vec![TypeSignatureClass::Integer],
+                            NativeType::Int32,
+                        ),
+                    ]),
+                ],
+                Volatility::Immutable,
+            ),
+        }
+    }
+}
+
+impl ScalarUDFImpl for SparkLevenshtein {
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    fn name(&self) -> &str {
+        "levenshtein"
+    }
+
+    fn signature(&self) -> &Signature {
+        &self.signature
+    }
+
+    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
+        if arg_types.len() != 2 && arg_types.len() != 3 {
+            return exec_err!(
+                "levenshtein expects 2 or 3 arguments, got {}",
+                arg_types.len()
+            );
+        }
+        if let Some(coercion_data_type) = string_coercion(&arg_types[0], 
&arg_types[1])
+            .or_else(|| binary_to_string_coercion(&arg_types[0], 
&arg_types[1]))
+        {
+            match coercion_data_type {
+                DataType::LargeUtf8 => Ok(DataType::Int64),
+                DataType::Utf8 | DataType::Utf8View => Ok(DataType::Int32),
+                other => exec_err!(
+                    "levenshtein requires Utf8, LargeUtf8 or Utf8View, got 
{other}"
+                ),
+            }
+        } else {
+            exec_err!(
+                "Unsupported data types for levenshtein. Expected Utf8, 
LargeUtf8 or Utf8View"
+            )
+        }
+    }
+
+    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> 
Result<ColumnarValue> {
+        let ScalarFunctionArgs { args, .. } = args;
+
+        // Determine the coerced string type (handles mixed Utf8 + LargeUtf8)
+        let coerced_type = string_coercion(&args[0].data_type(), 
&args[1].data_type())
+            .or_else(|| {
+                binary_to_string_coercion(&args[0].data_type(), 
&args[1].data_type())
+            })
+            .unwrap_or(DataType::Utf8);

Review Comment:
   Done — added an arity check at the start of `invoke_with_args` that errors 
with `exec_err!` before any `args[0]/[1]` indexing. Same shape as the one in 
`return_type`.
   



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


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to