You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@datafusion.apache.org by "anhvdq (via GitHub)" <gi...@apache.org> on 2025/09/04 02:12:08 UTC
[PR] feat(spark): Implement Spark functions `url_encode` and `url_decode` [datafusion]
anhvdq opened a new pull request, #17399:
URL: https://github.com/apache/datafusion/pull/17399
## Which issue does this PR close?
- Part of #15914
## Rationale for this change
## What changes are included in this PR?
Implement Spark functions `url_encode` and `url_decode`
## Are these changes tested?
Yes
## Are there any user-facing changes?
Yes
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat(spark): Implement Spark functions `url_encode`, `url_decode` and `try_url_decode` [datafusion]
Posted by "Jefffrey (via GitHub)" <gi...@apache.org>.
Jefffrey merged PR #17399:
URL: https://github.com/apache/datafusion/pull/17399
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat(spark): Implement Spark functions `url_encode`, `url_decode` and `try_url_decode` [datafusion]
Posted by "Jefffrey (via GitHub)" <gi...@apache.org>.
Jefffrey commented on PR #17399:
URL: https://github.com/apache/datafusion/pull/17399#issuecomment-3618880696
CI failures seem unrelated 🤔
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat(spark): Implement Spark functions `url_encode` and `url_decode` [datafusion]
Posted by "anhvdq (via GitHub)" <gi...@apache.org>.
anhvdq commented on code in PR #17399:
URL: https://github.com/apache/datafusion/pull/17399#discussion_r2404288926
##########
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:
This is a reminder to expand this function supporting the `try_url_decode`, it's unnecessary in this PR
Let me remove this
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat(spark): Implement Spark functions `url_encode` and `url_decode` [datafusion]
Posted by "Jefffrey (via GitHub)" <gi...@apache.org>.
Jefffrey commented on code in PR #17399:
URL: https://github.com/apache/datafusion/pull/17399#discussion_r2324182515
##########
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:
Could be simplified to just `Ok(arg_types[0].clone())` since the type signature should already guarantee the arguments are as expected
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat(spark): Implement Spark functions `url_encode` and `url_decode` [datafusion]
Posted by "anhvdq (via GitHub)" <gi...@apache.org>.
anhvdq commented on PR #17399:
URL: https://github.com/apache/datafusion/pull/17399#issuecomment-3541905553
Thank @Jefffrey
For the plus replacement, the function is copied as it is from rust-url crate which is widely used. Do we still need to add test case for this case?
Let me know if you have any suggestions
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat(spark): Implement Spark functions `url_encode`, `url_decode` and `try_url_decode` [datafusion]
Posted by "anhvdq (via GitHub)" <gi...@apache.org>.
anhvdq commented on PR #17399:
URL: https://github.com/apache/datafusion/pull/17399#issuecomment-3617542833
Hi @Jefffrey
I have pushed the new changes which include:
- More test cases as mentioned to cover the plus replacement, roundtrips, etc
- Add a new `try_url_decode` function which is basically identical to `url_decode` except that it returns None instead of error when the value is invalid.
Please help review and let me know your feedback
Thanks
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat(spark): Implement Spark functions `url_encode` and `url_decode` [datafusion]
Posted by "anhvdq (via GitHub)" <gi...@apache.org>.
anhvdq commented on code in PR #17399:
URL: https://github.com/apache/datafusion/pull/17399#discussion_r2404301634
##########
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:
@timsaucer Let me explain a bit about the specific needs here. What we are trying to archieve in encode/decode functions are to transform the string from/to `application/x-www-form-urlencoded` format. The `url::form_urlencoded` crate is already support this transformation.
- So for the `encode` function, we can just simply use the `byte_serialize` function exported from the crates
- For `decode` function, there are 2 drawbacks:
- The crate doesn't expose `decode` function for public use
- It doesn't return Error when there is invalid format, for example: %2s is an invalid percent encoded string
This is the reason why on the `url_decode`, I tried to do the transformation manually. It's actually the same code as the `decode` function in the crate except that there is a valiation step.
So to answer your question:
- `encode`: The function already did the necessary manipulation
- `decode`: The `decode` function in the crate is not exposed and there's no format validation, so we try to copy the logic of the `decode` function in the crate with a validation step
Let me know if you have any suggestion on this
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat(spark): Implement Spark functions `url_encode` and `url_decode` [datafusion]
Posted by "timsaucer (via GitHub)" <gi...@apache.org>.
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat(spark): Implement Spark functions `url_encode` and `url_decode` [datafusion]
Posted by "anhvdq (via GitHub)" <gi...@apache.org>.
anhvdq commented on PR #17399:
URL: https://github.com/apache/datafusion/pull/17399#issuecomment-3256869783
Thank @timsaucer for your feedback.
Let me check and update accordingly
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat(spark): Implement Spark functions `url_encode`, `url_decode` and `try_url_decode` [datafusion]
Posted by "Jefffrey (via GitHub)" <gi...@apache.org>.
Jefffrey commented on PR #17399:
URL: https://github.com/apache/datafusion/pull/17399#issuecomment-3619684509
Thanks @anhvdq & @timsaucer
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat(spark): Implement Spark functions `url_encode` and `url_decode` [datafusion]
Posted by "anhvdq (via GitHub)" <gi...@apache.org>.
anhvdq commented on code in PR #17399:
URL: https://github.com/apache/datafusion/pull/17399#discussion_r2404289126
##########
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:
Appreciate your review, will do this
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat(spark): Implement Spark functions `url_encode` and `url_decode` [datafusion]
Posted by "Jefffrey (via GitHub)" <gi...@apache.org>.
Jefffrey commented on PR #17399:
URL: https://github.com/apache/datafusion/pull/17399#issuecomment-3541929737
> Thank @Jefffrey For the plus replacement, the function is copied as it is from rust-url crate which is widely used. Do we still need to add test case for this case?
>
> Let me know if you have any suggestions
Yes, we should still have a test case for this, preferably in an SLT case. Consider what happens if someone decides to refactor that code; there is currently no test case that would prevent them breaking it, I believe?
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat(spark): Implement Spark functions `url_encode`, `url_decode` and `try_url_decode` [datafusion]
Posted by "anhvdq (via GitHub)" <gi...@apache.org>.
anhvdq commented on PR #17399:
URL: https://github.com/apache/datafusion/pull/17399#issuecomment-3619078814
> CI failures seem unrelated 🤔
Seem so, the error code is unfamiliar to me.
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat(spark): Implement Spark functions `url_encode` and `url_decode` [datafusion]
Posted by "Jefffrey (via GitHub)" <gi...@apache.org>.
Jefffrey commented on PR #17399:
URL: https://github.com/apache/datafusion/pull/17399#issuecomment-3541723151
Still seeing a lack of test cases mentioned by previous review comments: nulls, empty strings, roundtrips, plus replacement
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org