timsaucer commented on code in PR #17399:
URL: https://github.com/apache/datafusion/pull/17399#discussion_r2322435591


##########
datafusion/spark/src/function/url/url_decode.rs:
##########
@@ -0,0 +1,195 @@
+// 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::borrow::Cow;
+use std::sync::Arc;
+
+use arrow::array::{ArrayRef, LargeStringArray, StringArray, StringViewArray};
+use arrow::datatypes::DataType;
+use datafusion_common::cast::{
+    as_large_string_array, as_string_array, as_string_view_array,
+};
+use datafusion_common::{exec_datafusion_err, exec_err, plan_err, Result};
+use datafusion_expr::{
+    ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Signature, Volatility,
+};
+use datafusion_functions::utils::make_scalar_function;
+use percent_encoding::percent_decode;
+
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct UrlDecode {
+    signature: Signature,
+}
+
+impl Default for UrlDecode {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl UrlDecode {
+    pub fn new() -> Self {
+        Self {
+            signature: Signature::string(1, Volatility::Immutable),
+        }
+    }
+
+    /// Decodes a URL-encoded string from application/x-www-form-urlencoded 
format.
+    ///
+    /// # Arguments
+    ///
+    /// * `value` - The URL-encoded string to decode
+    ///
+    /// # Returns
+    ///
+    /// * `Ok(String)` - The decoded string
+    /// * `Err(DataFusionError)` - If the input is malformed or contains 
invalid UTF-8
+    ///
+    fn decode(value: &str) -> Result<String> {
+        // Check if the string has valid percent encoding
+        // TODO: Support `try_url_decode`

Review Comment:
   Is this TODO still valid? Should we open an issue and link to it if so?



##########
datafusion/spark/src/function/url/url_decode.rs:
##########
@@ -0,0 +1,195 @@
+// 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::borrow::Cow;
+use std::sync::Arc;
+
+use arrow::array::{ArrayRef, LargeStringArray, StringArray, StringViewArray};
+use arrow::datatypes::DataType;
+use datafusion_common::cast::{
+    as_large_string_array, as_string_array, as_string_view_array,
+};
+use datafusion_common::{exec_datafusion_err, exec_err, plan_err, Result};
+use datafusion_expr::{
+    ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Signature, Volatility,
+};
+use datafusion_functions::utils::make_scalar_function;
+use percent_encoding::percent_decode;
+
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct UrlDecode {
+    signature: Signature,
+}
+
+impl Default for UrlDecode {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl UrlDecode {
+    pub fn new() -> Self {
+        Self {
+            signature: Signature::string(1, Volatility::Immutable),
+        }
+    }
+
+    /// Decodes a URL-encoded string from application/x-www-form-urlencoded 
format.
+    ///
+    /// # Arguments
+    ///
+    /// * `value` - The URL-encoded string to decode
+    ///
+    /// # Returns
+    ///
+    /// * `Ok(String)` - The decoded string
+    /// * `Err(DataFusionError)` - If the input is malformed or contains 
invalid UTF-8
+    ///
+    fn decode(value: &str) -> Result<String> {
+        // Check if the string has valid percent encoding
+        // TODO: Support `try_url_decode`
+        Self::validate_percent_encoding(value)?;
+
+        let replaced = Self::replace_plus(value.as_bytes());
+        percent_decode(&replaced)
+            .decode_utf8()
+            .map_err(|e| exec_datafusion_err!("Invalid UTF-8 sequence: {e}"))
+            .map(|parsed| parsed.into_owned())
+    }
+
+    /// Replace b'+' with b' '
+    fn replace_plus(input: &[u8]) -> Cow<'_, [u8]> {

Review Comment:
   Could we add a test case that covers this replacement?



##########
datafusion/sqllogictest/test_files/spark/url/url_decode.slt:
##########
@@ -15,13 +15,11 @@
 # specific language governing permissions and limitations
 # under the License.
 
-# This file was originally created by a porting script from:
-#   
https://github.com/lakehq/sail/tree/43b6ed8221de5c4c4adbedbb267ae1351158b43c/crates/sail-spark-connect/tests/gold_data/function
-# This file is part of the implementation of the datafusion-spark function 
library.
-# For more information, please see:
-#   https://github.com/apache/datafusion/issues/15914
+query T
+SELECT url_decode('https%3A%2F%2Fspark.apache.org'::string);

Review Comment:
   I am unfamiliar with the slt files, but if there was a way to have these do 
all 3 types of input (utf8, utf8view, largeutf8) that would be nice.



##########
datafusion/spark/src/function/url/url_decode.rs:
##########
@@ -0,0 +1,195 @@
+// 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::borrow::Cow;
+use std::sync::Arc;
+
+use arrow::array::{ArrayRef, LargeStringArray, StringArray, StringViewArray};
+use arrow::datatypes::DataType;
+use datafusion_common::cast::{
+    as_large_string_array, as_string_array, as_string_view_array,
+};
+use datafusion_common::{exec_datafusion_err, exec_err, plan_err, Result};
+use datafusion_expr::{
+    ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Signature, Volatility,
+};
+use datafusion_functions::utils::make_scalar_function;
+use percent_encoding::percent_decode;
+
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct UrlDecode {
+    signature: Signature,
+}
+
+impl Default for UrlDecode {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl UrlDecode {
+    pub fn new() -> Self {
+        Self {
+            signature: Signature::string(1, Volatility::Immutable),
+        }
+    }
+
+    /// Decodes a URL-encoded string from application/x-www-form-urlencoded 
format.
+    ///
+    /// # Arguments
+    ///
+    /// * `value` - The URL-encoded string to decode
+    ///
+    /// # Returns
+    ///
+    /// * `Ok(String)` - The decoded string
+    /// * `Err(DataFusionError)` - If the input is malformed or contains 
invalid UTF-8
+    ///
+    fn decode(value: &str) -> Result<String> {
+        // Check if the string has valid percent encoding
+        // TODO: Support `try_url_decode`
+        Self::validate_percent_encoding(value)?;
+
+        let replaced = Self::replace_plus(value.as_bytes());
+        percent_decode(&replaced)
+            .decode_utf8()
+            .map_err(|e| exec_datafusion_err!("Invalid UTF-8 sequence: {e}"))
+            .map(|parsed| parsed.into_owned())
+    }
+
+    /// Replace b'+' with b' '
+    fn replace_plus(input: &[u8]) -> Cow<'_, [u8]> {
+        match input.iter().position(|&b| b == b'+') {
+            None => Cow::Borrowed(input),
+            Some(first_position) => {
+                let mut replaced = input.to_owned();
+                replaced[first_position] = b' ';
+                for byte in &mut replaced[first_position + 1..] {
+                    if *byte == b'+' {
+                        *byte = b' ';
+                    }
+                }
+                Cow::Owned(replaced)
+            }
+        }
+    }
+
+    /// Validate percent-encoding of the string
+    fn validate_percent_encoding(value: &str) -> Result<()> {
+        let bytes = value.as_bytes();
+        let mut i = 0;
+
+        while i < bytes.len() {
+            if bytes[i] == b'%' {
+                // Check if we have at least 2 more characters
+                if i + 2 >= bytes.len() {
+                    return exec_err!(
+                        "Invalid percent-encoding: incomplete sequence at 
position {}",
+                        i
+                    );
+                }
+
+                let hex1 = bytes[i + 1];
+                let hex2 = bytes[i + 2];
+
+                if !hex1.is_ascii_hexdigit() || !hex2.is_ascii_hexdigit() {
+                    return exec_err!(
+                        "Invalid percent-encoding: invalid hex sequence 
'%{}{}' at position {}",
+                        hex1 as char,
+                        hex2 as char,
+                        i
+                    );
+                }
+                i += 3;
+            } else {
+                i += 1;
+            }
+        }
+        Ok(())
+    }
+}
+
+impl ScalarUDFImpl for UrlDecode {
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    fn name(&self) -> &str {
+        "url_decode"
+    }
+
+    fn signature(&self) -> &Signature {
+        &self.signature
+    }
+
+    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
+        if arg_types.len() != 1 {
+            return plan_err!(
+                "{} expects 1 argument, but got {}",
+                self.name(),
+                arg_types.len()
+            );
+        }
+        match arg_types[0] {
+            DataType::Utf8 | DataType::Utf8View => Ok(DataType::Utf8),

Review Comment:
   It looks like you're collecting to a StringView for input type of Utf8View, 
so shouldn't this be more like
   
   ```
   DataType::Utf8 | DataType::Utf8View | DataType::LargeUtf8 => 
Ok(arg_types[0].clone())
   ```



##########
datafusion/spark/src/function/url/url_encode.rs:
##########
@@ -0,0 +1,134 @@
+// 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::{ArrayRef, LargeStringArray, StringArray, StringViewArray};
+use arrow::datatypes::DataType;
+use datafusion_common::cast::{
+    as_large_string_array, as_string_array, as_string_view_array,
+};
+use datafusion_common::{exec_err, plan_err, Result};
+use datafusion_expr::{
+    ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Signature, Volatility,
+};
+use datafusion_functions::utils::make_scalar_function;
+use url::form_urlencoded::byte_serialize;
+
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct UrlEncode {
+    signature: Signature,
+}
+
+impl Default for UrlEncode {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl UrlEncode {
+    pub fn new() -> Self {
+        Self {
+            signature: Signature::string(1, Volatility::Immutable),
+        }
+    }
+
+    /// Encode a string to application/x-www-form-urlencoded format.
+    ///
+    /// # Arguments
+    ///
+    /// * `value` - The string to encode
+    ///
+    /// # Returns
+    ///
+    /// * `Ok(String)` - The encoded string
+    ///
+    fn encode(value: &str) -> Result<String> {
+        Ok(byte_serialize(value.as_bytes()).collect::<String>())

Review Comment:
   So for encoding you don't need to do the inverse operations you do in 
decoding? Like the + -> ' ' manipulation? I am unfamiliar with the specific 
needs here.



##########
datafusion/spark/src/function/url/url_encode.rs:
##########
@@ -0,0 +1,134 @@
+// 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::{ArrayRef, LargeStringArray, StringArray, StringViewArray};
+use arrow::datatypes::DataType;
+use datafusion_common::cast::{
+    as_large_string_array, as_string_array, as_string_view_array,
+};
+use datafusion_common::{exec_err, plan_err, Result};
+use datafusion_expr::{
+    ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Signature, Volatility,
+};
+use datafusion_functions::utils::make_scalar_function;
+use url::form_urlencoded::byte_serialize;
+
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct UrlEncode {
+    signature: Signature,
+}
+
+impl Default for UrlEncode {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl UrlEncode {
+    pub fn new() -> Self {
+        Self {
+            signature: Signature::string(1, Volatility::Immutable),
+        }
+    }
+
+    /// Encode a string to application/x-www-form-urlencoded format.
+    ///
+    /// # Arguments
+    ///
+    /// * `value` - The string to encode
+    ///
+    /// # Returns
+    ///
+    /// * `Ok(String)` - The encoded string
+    ///
+    fn encode(value: &str) -> Result<String> {
+        Ok(byte_serialize(value.as_bytes()).collect::<String>())
+    }
+}
+
+impl ScalarUDFImpl for UrlEncode {
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    fn name(&self) -> &str {
+        "url_encode"
+    }
+
+    fn signature(&self) -> &Signature {
+        &self.signature
+    }
+
+    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
+        if arg_types.len() != 1 {
+            return plan_err!(
+                "{} expects 1 argument, but got {}",
+                self.name(),
+                arg_types.len()
+            );
+        }
+        match arg_types[0] {
+            DataType::Utf8 | DataType::Utf8View => Ok(DataType::Utf8),

Review Comment:
   Same question as for decode



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