You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@datafusion.apache.org by "andygrove (via GitHub)" <gi...@apache.org> on 2025/05/05 15:54:19 UTC
[PR] [datafusion-spark] Add Spark-compatible hex function [datafusion]
andygrove opened a new pull request, #15947:
URL: https://github.com/apache/datafusion/pull/15947
## Which issue does this PR close?
<!--
We generally require a GitHub issue to be filed for all bug fixes and enhancements and this helps us generate change logs for our releases. You can link an issue to this PR using the GitHub syntax. For example `Closes #123` indicates that this PR will close issue #123.
-->
Part of https://github.com/apache/datafusion/issues/15914 and https://github.com/apache/datafusion-comet/issues/1704
## Rationale for this change
<!--
Why are you proposing this change? If this is already explained clearly in the issue then this section is not needed.
Explaining clearly why changes are proposed helps reviewers understand your changes and offer better suggestions for fixes.
-->
Test the process for contributing a Comet function to datafusion-spark/
## What changes are included in this PR?
<!--
There is no need to duplicate the description in the issue here but it is sometimes worth providing a summary of the individual changes in this PR.
-->
Add new `hex` function.
## Are these changes tested?
<!--
We typically require tests for all PRs in order to:
1. Prevent the code from being accidentally broken by subsequent changes
2. Serve as another way to document the expected behavior of the code
If tests are not included in your PR, please explain why (for example, are they covered by existing tests)?
-->
Yes, unit tests and slt.
## Are there any user-facing changes?
<!--
If there are user-facing changes then we may require documentation to be updated before approving the PR.
-->
No.
<!--
If there are any breaking changes to public APIs, please add the `api change` label.
-->
--
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] [datafusion-spark] Add Spark-compatible hex function [datafusion]
Posted by "andygrove (via GitHub)" <gi...@apache.org>.
andygrove commented on PR #15947:
URL: https://github.com/apache/datafusion/pull/15947#issuecomment-2860489815
> Thanks @shehabgamin and @andygrove
>
> What I think we should do is to merge this PR and file a follow on ticket for any follow on performance optimizations (aka avoid allocating strings)
I filed https://github.com/apache/datafusion/issues/15986
--
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] [datafusion-spark] Add Spark-compatible hex function [datafusion]
Posted by "andygrove (via GitHub)" <gi...@apache.org>.
andygrove merged PR #15947:
URL: https://github.com/apache/datafusion/pull/15947
--
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] [datafusion-spark] Add Spark-compatible hex function [datafusion]
Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #15947:
URL: https://github.com/apache/datafusion/pull/15947#discussion_r2078491599
##########
datafusion/sqllogictest/test_files/spark/math/hex.slt:
##########
@@ -0,0 +1,26 @@
+# 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.
+
+query T
Review Comment:
I pushed a few new tests
--
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] [datafusion-spark] Add Spark-compatible hex function [datafusion]
Posted by "andygrove (via GitHub)" <gi...@apache.org>.
andygrove commented on code in PR #15947:
URL: https://github.com/apache/datafusion/pull/15947#discussion_r2078546921
##########
datafusion/spark/src/function/math/hex.rs:
##########
@@ -0,0 +1,404 @@
+// 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 crate::function::error_utils::{
+ invalid_arg_count_exec_err, unsupported_data_type_exec_err,
+};
+use arrow::array::{Array, StringArray};
+use arrow::datatypes::DataType;
+use arrow::{
+ array::{as_dictionary_array, as_largestring_array, as_string_array},
+ datatypes::Int32Type,
+};
+use datafusion_common::{
+ cast::{as_binary_array, as_fixed_size_binary_array, as_int64_array},
+ exec_err, DataFusionError,
+};
+use datafusion_expr::Signature;
+use datafusion_expr::{ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Volatility};
+use std::fmt::Write;
+
+/// <https://spark.apache.org/docs/latest/api/sql/index.html#hex>
+#[derive(Debug)]
+pub struct SparkHex {
+ signature: Signature,
+ aliases: Vec<String>,
+}
+
+impl Default for SparkHex {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl SparkHex {
+ pub fn new() -> Self {
+ Self {
+ signature: Signature::user_defined(Volatility::Immutable),
+ aliases: vec![],
+ }
+ }
+}
+
+impl ScalarUDFImpl for SparkHex {
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+
+ fn name(&self) -> &str {
+ "hex"
+ }
+
+ fn signature(&self) -> &Signature {
+ &self.signature
+ }
+
+ fn return_type(
+ &self,
+ _arg_types: &[DataType],
+ ) -> datafusion_common::Result<DataType> {
+ Ok(DataType::Utf8)
+ }
+
+ fn invoke_with_args(
+ &self,
+ args: ScalarFunctionArgs,
+ ) -> datafusion_common::Result<ColumnarValue> {
+ spark_hex(&args.args)
+ }
+
+ fn aliases(&self) -> &[String] {
+ &self.aliases
+ }
+
+ fn coerce_types(
+ &self,
+ arg_types: &[DataType],
+ ) -> datafusion_common::Result<Vec<DataType>> {
+ if arg_types.len() != 1 {
+ return Err(invalid_arg_count_exec_err("hex", (1, 1), arg_types.len()));
+ }
+ match &arg_types[0] {
+ DataType::Int64
+ | DataType::Utf8
+ | DataType::LargeUtf8
+ | DataType::Binary
+ | DataType::LargeBinary => Ok(vec![arg_types[0].clone()]),
+ DataType::Dictionary(key_type, value_type) => match value_type.as_ref() {
+ DataType::Int64
+ | DataType::Utf8
+ | DataType::LargeUtf8
+ | DataType::Binary
+ | DataType::LargeBinary => Ok(vec![arg_types[0].clone()]),
+ other => {
+ if other.is_numeric() {
+ Ok(vec![DataType::Dictionary(
+ key_type.clone(),
+ Box::new(DataType::Int64),
+ )])
+ } else {
+ Err(unsupported_data_type_exec_err(
+ "hex",
+ "Numeric, String, or Binary",
+ &arg_types[0],
+ ))
+ }
+ }
+ },
+ other => {
+ if other.is_numeric() {
+ Ok(vec![DataType::Int64])
+ } else {
+ Err(unsupported_data_type_exec_err(
+ "hex",
+ "Numeric, String, or Binary",
+ &arg_types[0],
+ ))
+ }
+ }
+ }
+ }
+}
+
+fn hex_int64(num: i64) -> String {
+ format!("{:X}", num)
+}
+
+#[inline(always)]
+fn hex_encode<T: AsRef<[u8]>>(data: T, lower_case: bool) -> String {
+ let mut s = String::with_capacity(data.as_ref().len() * 2);
+ if lower_case {
+ for b in data.as_ref() {
+ // Writing to a string never errors, so we can unwrap here.
+ write!(&mut s, "{b:02x}").unwrap();
+ }
+ } else {
+ for b in data.as_ref() {
+ // Writing to a string never errors, so we can unwrap here.
+ write!(&mut s, "{b:02X}").unwrap();
+ }
+ }
+ s
+}
+
+#[inline(always)]
+fn hex_bytes<T: AsRef<[u8]>>(bytes: T) -> Result<String, std::fmt::Error> {
+ let hex_string = hex_encode(bytes, false);
+ Ok(hex_string)
+}
+
+/// Spark-compatible `hex` function
+pub fn spark_hex(args: &[ColumnarValue]) -> Result<ColumnarValue, DataFusionError> {
+ if args.len() != 1 {
+ return Err(DataFusionError::Internal(
+ "hex expects exactly one argument".to_string(),
+ ));
+ }
+
+ let input = match &args[0] {
+ ColumnarValue::Scalar(value) => ColumnarValue::Array(value.to_array()?),
+ ColumnarValue::Array(_) => args[0].clone(),
+ };
+
+ match &input {
+ ColumnarValue::Array(array) => match array.data_type() {
+ DataType::Int64 => {
+ let array = as_int64_array(array)?;
+
+ let hexed_array: StringArray =
+ array.iter().map(|v| v.map(hex_int64)).collect();
+
+ Ok(ColumnarValue::Array(Arc::new(hexed_array)))
+ }
+ DataType::Utf8 => {
+ let array = as_string_array(array);
+
+ let hexed: StringArray = array
+ .iter()
+ .map(|v| v.map(hex_bytes).transpose())
+ .collect::<Result<_, _>>()?;
+
+ Ok(ColumnarValue::Array(Arc::new(hexed)))
+ }
+ DataType::LargeUtf8 => {
+ let array = as_largestring_array(array);
+
+ let hexed: StringArray = array
+ .iter()
+ .map(|v| v.map(hex_bytes).transpose())
+ .collect::<Result<_, _>>()?;
+
+ Ok(ColumnarValue::Array(Arc::new(hexed)))
+ }
+ DataType::Binary => {
+ let array = as_binary_array(array)?;
+
+ let hexed: StringArray = array
+ .iter()
+ .map(|v| v.map(hex_bytes).transpose())
+ .collect::<Result<_, _>>()?;
+
+ Ok(ColumnarValue::Array(Arc::new(hexed)))
+ }
+ DataType::FixedSizeBinary(_) => {
+ let array = as_fixed_size_binary_array(array)?;
+
+ let hexed: StringArray = array
+ .iter()
+ .map(|v| v.map(hex_bytes).transpose())
+ .collect::<Result<_, _>>()?;
+
+ Ok(ColumnarValue::Array(Arc::new(hexed)))
+ }
+ DataType::Dictionary(_, value_type) => {
+ let dict = as_dictionary_array::<Int32Type>(&array);
+
+ let values = match **value_type {
+ DataType::Int64 => as_int64_array(dict.values())?
+ .iter()
+ .map(|v| v.map(hex_int64))
+ .collect::<Vec<_>>(),
+ DataType::Utf8 => as_string_array(dict.values())
+ .iter()
+ .map(|v| v.map(hex_bytes).transpose())
+ .collect::<Result<_, _>>()?,
+ DataType::Binary => as_binary_array(dict.values())?
+ .iter()
+ .map(|v| v.map(hex_bytes).transpose())
+ .collect::<Result<_, _>>()?,
+ _ => exec_err!(
+ "hex got an unexpected argument type: {:?}",
+ array.data_type()
+ )?,
+ };
+
+ let new_values: Vec<Option<String>> = dict
+ .keys()
+ .iter()
+ .map(|key| key.map(|k| values[k as usize].clone()).unwrap_or(None))
+ .collect();
+
+ let string_array_values = StringArray::from(new_values);
+
+ Ok(ColumnarValue::Array(Arc::new(string_array_values)))
+ }
+ _ => exec_err!(
+ "hex got an unexpected argument type: {:?}",
+ array.data_type()
+ ),
+ },
+ _ => exec_err!("native hex does not support scalar values at this time"),
+ }
+}
+
+#[cfg(test)]
+mod test {
Review Comment:
Credit for the tests goes to @tshauck who originally implemented `hex` in https://github.com/apache/datafusion-comet/pull/449
--
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] [datafusion-spark] Add Spark-compatible hex function [datafusion]
Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #15947:
URL: https://github.com/apache/datafusion/pull/15947#discussion_r2073954485
##########
datafusion/spark/src/function/math/hex.rs:
##########
@@ -0,0 +1,404 @@
+// 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 crate::function::error_utils::{
+ invalid_arg_count_exec_err, unsupported_data_type_exec_err,
+};
+use arrow::array::{Array, StringArray};
+use arrow::datatypes::DataType;
+use arrow::{
+ array::{as_dictionary_array, as_largestring_array, as_string_array},
+ datatypes::Int32Type,
+};
+use datafusion_common::{
+ cast::{as_binary_array, as_fixed_size_binary_array, as_int64_array},
+ exec_err, DataFusionError,
+};
+use datafusion_expr::Signature;
+use datafusion_expr::{ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Volatility};
+use std::fmt::Write;
+
+/// <https://spark.apache.org/docs/latest/api/sql/index.html#hex>
+#[derive(Debug)]
+pub struct SparkHex {
+ signature: Signature,
+ aliases: Vec<String>,
+}
+
+impl Default for SparkHex {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl SparkHex {
+ pub fn new() -> Self {
+ Self {
+ signature: Signature::user_defined(Volatility::Immutable),
+ aliases: vec![],
+ }
+ }
+}
+
+impl ScalarUDFImpl for SparkHex {
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+
+ fn name(&self) -> &str {
+ "hex"
+ }
+
+ fn signature(&self) -> &Signature {
+ &self.signature
+ }
+
+ fn return_type(
+ &self,
+ _arg_types: &[DataType],
+ ) -> datafusion_common::Result<DataType> {
+ Ok(DataType::Utf8)
+ }
+
+ fn invoke_with_args(
+ &self,
+ args: ScalarFunctionArgs,
+ ) -> datafusion_common::Result<ColumnarValue> {
+ spark_hex(&args.args)
+ }
+
+ fn aliases(&self) -> &[String] {
+ &self.aliases
+ }
+
+ fn coerce_types(
+ &self,
+ arg_types: &[DataType],
+ ) -> datafusion_common::Result<Vec<DataType>> {
+ if arg_types.len() != 1 {
+ return Err(invalid_arg_count_exec_err("hex", (1, 1), arg_types.len()));
+ }
+ match &arg_types[0] {
+ DataType::Int64
+ | DataType::Utf8
+ | DataType::LargeUtf8
+ | DataType::Binary
+ | DataType::LargeBinary => Ok(vec![arg_types[0].clone()]),
+ DataType::Dictionary(key_type, value_type) => match value_type.as_ref() {
+ DataType::Int64
+ | DataType::Utf8
+ | DataType::LargeUtf8
+ | DataType::Binary
+ | DataType::LargeBinary => Ok(vec![arg_types[0].clone()]),
+ other => {
+ if other.is_numeric() {
+ Ok(vec![DataType::Dictionary(
+ key_type.clone(),
+ Box::new(DataType::Int64),
+ )])
+ } else {
+ Err(unsupported_data_type_exec_err(
+ "hex",
+ "Numeric, String, or Binary",
+ &arg_types[0],
+ ))
+ }
+ }
+ },
+ other => {
+ if other.is_numeric() {
+ Ok(vec![DataType::Int64])
+ } else {
+ Err(unsupported_data_type_exec_err(
+ "hex",
+ "Numeric, String, or Binary",
+ &arg_types[0],
+ ))
+ }
+ }
+ }
+ }
+}
+
+fn hex_int64(num: i64) -> String {
+ format!("{:X}", num)
+}
+
+#[inline(always)]
+fn hex_encode<T: AsRef<[u8]>>(data: T, lower_case: bool) -> String {
+ let mut s = String::with_capacity(data.as_ref().len() * 2);
+ if lower_case {
+ for b in data.as_ref() {
+ // Writing to a string never errors, so we can unwrap here.
+ write!(&mut s, "{b:02x}").unwrap();
+ }
+ } else {
+ for b in data.as_ref() {
+ // Writing to a string never errors, so we can unwrap here.
+ write!(&mut s, "{b:02X}").unwrap();
+ }
+ }
+ s
+}
+
+#[inline(always)]
+fn hex_bytes<T: AsRef<[u8]>>(bytes: T) -> Result<String, std::fmt::Error> {
+ let hex_string = hex_encode(bytes, false);
+ Ok(hex_string)
+}
+
+/// Spark-compatible `hex` function
+pub fn spark_hex(args: &[ColumnarValue]) -> Result<ColumnarValue, DataFusionError> {
+ if args.len() != 1 {
+ return Err(DataFusionError::Internal(
+ "hex expects exactly one argument".to_string(),
+ ));
+ }
+
+ let input = match &args[0] {
+ ColumnarValue::Scalar(value) => ColumnarValue::Array(value.to_array()?),
+ ColumnarValue::Array(_) => args[0].clone(),
+ };
+
+ match &input {
+ ColumnarValue::Array(array) => match array.data_type() {
+ DataType::Int64 => {
+ let array = as_int64_array(array)?;
+
+ let hexed_array: StringArray =
+ array.iter().map(|v| v.map(hex_int64)).collect();
+
+ Ok(ColumnarValue::Array(Arc::new(hexed_array)))
+ }
+ DataType::Utf8 => {
+ let array = as_string_array(array);
+
+ let hexed: StringArray = array
+ .iter()
+ .map(|v| v.map(hex_bytes).transpose())
+ .collect::<Result<_, _>>()?;
+
+ Ok(ColumnarValue::Array(Arc::new(hexed)))
+ }
+ DataType::LargeUtf8 => {
+ let array = as_largestring_array(array);
+
+ let hexed: StringArray = array
+ .iter()
+ .map(|v| v.map(hex_bytes).transpose())
+ .collect::<Result<_, _>>()?;
+
+ Ok(ColumnarValue::Array(Arc::new(hexed)))
+ }
+ DataType::Binary => {
+ let array = as_binary_array(array)?;
+
+ let hexed: StringArray = array
+ .iter()
+ .map(|v| v.map(hex_bytes).transpose())
+ .collect::<Result<_, _>>()?;
+
+ Ok(ColumnarValue::Array(Arc::new(hexed)))
+ }
+ DataType::FixedSizeBinary(_) => {
+ let array = as_fixed_size_binary_array(array)?;
+
+ let hexed: StringArray = array
+ .iter()
+ .map(|v| v.map(hex_bytes).transpose())
+ .collect::<Result<_, _>>()?;
+
+ Ok(ColumnarValue::Array(Arc::new(hexed)))
+ }
+ DataType::Dictionary(_, value_type) => {
+ let dict = as_dictionary_array::<Int32Type>(&array);
+
+ let values = match **value_type {
+ DataType::Int64 => as_int64_array(dict.values())?
+ .iter()
+ .map(|v| v.map(hex_int64))
+ .collect::<Vec<_>>(),
+ DataType::Utf8 => as_string_array(dict.values())
+ .iter()
+ .map(|v| v.map(hex_bytes).transpose())
+ .collect::<Result<_, _>>()?,
+ DataType::Binary => as_binary_array(dict.values())?
+ .iter()
+ .map(|v| v.map(hex_bytes).transpose())
+ .collect::<Result<_, _>>()?,
+ _ => exec_err!(
+ "hex got an unexpected argument type: {:?}",
+ array.data_type()
+ )?,
+ };
+
+ let new_values: Vec<Option<String>> = dict
Review Comment:
You can likely make this more efficient by avoiding the Strings here and reuse the dictionary values
Something like
```rust
let new_dict_array = DictionaryArray::new(dict.keys().clone(), values)
```
##########
datafusion/spark/src/function/math/hex.rs:
##########
@@ -0,0 +1,404 @@
+// 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 crate::function::error_utils::{
+ invalid_arg_count_exec_err, unsupported_data_type_exec_err,
+};
+use arrow::array::{Array, StringArray};
+use arrow::datatypes::DataType;
+use arrow::{
+ array::{as_dictionary_array, as_largestring_array, as_string_array},
+ datatypes::Int32Type,
+};
+use datafusion_common::{
+ cast::{as_binary_array, as_fixed_size_binary_array, as_int64_array},
+ exec_err, DataFusionError,
+};
+use datafusion_expr::Signature;
+use datafusion_expr::{ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Volatility};
+use std::fmt::Write;
+
+/// <https://spark.apache.org/docs/latest/api/sql/index.html#hex>
+#[derive(Debug)]
+pub struct SparkHex {
+ signature: Signature,
+ aliases: Vec<String>,
+}
+
+impl Default for SparkHex {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl SparkHex {
+ pub fn new() -> Self {
+ Self {
+ signature: Signature::user_defined(Volatility::Immutable),
+ aliases: vec![],
+ }
+ }
+}
+
+impl ScalarUDFImpl for SparkHex {
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+
+ fn name(&self) -> &str {
+ "hex"
+ }
+
+ fn signature(&self) -> &Signature {
+ &self.signature
+ }
+
+ fn return_type(
+ &self,
+ _arg_types: &[DataType],
+ ) -> datafusion_common::Result<DataType> {
+ Ok(DataType::Utf8)
Review Comment:
If this function outputs `Utf8View` it will likely be more performant rather than Utf8
##########
datafusion/spark/src/function/math/hex.rs:
##########
@@ -0,0 +1,404 @@
+// 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 crate::function::error_utils::{
+ invalid_arg_count_exec_err, unsupported_data_type_exec_err,
+};
+use arrow::array::{Array, StringArray};
+use arrow::datatypes::DataType;
+use arrow::{
+ array::{as_dictionary_array, as_largestring_array, as_string_array},
+ datatypes::Int32Type,
+};
+use datafusion_common::{
+ cast::{as_binary_array, as_fixed_size_binary_array, as_int64_array},
+ exec_err, DataFusionError,
+};
+use datafusion_expr::Signature;
+use datafusion_expr::{ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Volatility};
+use std::fmt::Write;
+
+/// <https://spark.apache.org/docs/latest/api/sql/index.html#hex>
+#[derive(Debug)]
+pub struct SparkHex {
+ signature: Signature,
+ aliases: Vec<String>,
+}
+
+impl Default for SparkHex {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl SparkHex {
+ pub fn new() -> Self {
+ Self {
+ signature: Signature::user_defined(Volatility::Immutable),
+ aliases: vec![],
+ }
+ }
+}
+
+impl ScalarUDFImpl for SparkHex {
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+
+ fn name(&self) -> &str {
+ "hex"
+ }
+
+ fn signature(&self) -> &Signature {
+ &self.signature
+ }
+
+ fn return_type(
+ &self,
+ _arg_types: &[DataType],
+ ) -> datafusion_common::Result<DataType> {
+ Ok(DataType::Utf8)
+ }
+
+ fn invoke_with_args(
+ &self,
+ args: ScalarFunctionArgs,
+ ) -> datafusion_common::Result<ColumnarValue> {
+ spark_hex(&args.args)
+ }
+
+ fn aliases(&self) -> &[String] {
+ &self.aliases
+ }
+
+ fn coerce_types(
+ &self,
+ arg_types: &[DataType],
+ ) -> datafusion_common::Result<Vec<DataType>> {
+ if arg_types.len() != 1 {
+ return Err(invalid_arg_count_exec_err("hex", (1, 1), arg_types.len()));
+ }
+ match &arg_types[0] {
+ DataType::Int64
+ | DataType::Utf8
+ | DataType::LargeUtf8
+ | DataType::Binary
+ | DataType::LargeBinary => Ok(vec![arg_types[0].clone()]),
+ DataType::Dictionary(key_type, value_type) => match value_type.as_ref() {
+ DataType::Int64
+ | DataType::Utf8
+ | DataType::LargeUtf8
+ | DataType::Binary
+ | DataType::LargeBinary => Ok(vec![arg_types[0].clone()]),
+ other => {
+ if other.is_numeric() {
+ Ok(vec![DataType::Dictionary(
+ key_type.clone(),
+ Box::new(DataType::Int64),
+ )])
+ } else {
+ Err(unsupported_data_type_exec_err(
+ "hex",
+ "Numeric, String, or Binary",
+ &arg_types[0],
+ ))
+ }
+ }
+ },
+ other => {
+ if other.is_numeric() {
+ Ok(vec![DataType::Int64])
+ } else {
+ Err(unsupported_data_type_exec_err(
+ "hex",
+ "Numeric, String, or Binary",
+ &arg_types[0],
+ ))
+ }
+ }
+ }
+ }
+}
+
+fn hex_int64(num: i64) -> String {
+ format!("{:X}", num)
+}
+
+#[inline(always)]
+fn hex_encode<T: AsRef<[u8]>>(data: T, lower_case: bool) -> String {
+ let mut s = String::with_capacity(data.as_ref().len() * 2);
+ if lower_case {
+ for b in data.as_ref() {
+ // Writing to a string never errors, so we can unwrap here.
+ write!(&mut s, "{b:02x}").unwrap();
+ }
+ } else {
+ for b in data.as_ref() {
+ // Writing to a string never errors, so we can unwrap here.
+ write!(&mut s, "{b:02X}").unwrap();
+ }
+ }
+ s
+}
+
+#[inline(always)]
+fn hex_bytes<T: AsRef<[u8]>>(bytes: T) -> Result<String, std::fmt::Error> {
+ let hex_string = hex_encode(bytes, false);
+ Ok(hex_string)
+}
+
+/// Spark-compatible `hex` function
+pub fn spark_hex(args: &[ColumnarValue]) -> Result<ColumnarValue, DataFusionError> {
+ if args.len() != 1 {
+ return Err(DataFusionError::Internal(
+ "hex expects exactly one argument".to_string(),
+ ));
+ }
+
+ let input = match &args[0] {
+ ColumnarValue::Scalar(value) => ColumnarValue::Array(value.to_array()?),
+ ColumnarValue::Array(_) => args[0].clone(),
+ };
+
+ match &input {
+ ColumnarValue::Array(array) => match array.data_type() {
+ DataType::Int64 => {
+ let array = as_int64_array(array)?;
+
+ let hexed_array: StringArray =
Review Comment:
You can probably make this much faster by avoiding the allocation by using StringBuilder directly
If you are using StringArray something like this:
https://docs.rs/arrow/latest/arrow/array/type.GenericStringBuilder.html#example-incrementally-writing-strings-with-stdfmtwrite
If you are using StringView I think you'll have to provide a fast path for shorter strings and use the StringView builder for longer strings
##########
datafusion/spark/src/function/math/hex.rs:
##########
@@ -0,0 +1,404 @@
+// 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 crate::function::error_utils::{
+ invalid_arg_count_exec_err, unsupported_data_type_exec_err,
+};
+use arrow::array::{Array, StringArray};
+use arrow::datatypes::DataType;
+use arrow::{
+ array::{as_dictionary_array, as_largestring_array, as_string_array},
+ datatypes::Int32Type,
+};
+use datafusion_common::{
+ cast::{as_binary_array, as_fixed_size_binary_array, as_int64_array},
+ exec_err, DataFusionError,
+};
+use datafusion_expr::Signature;
+use datafusion_expr::{ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Volatility};
+use std::fmt::Write;
+
+/// <https://spark.apache.org/docs/latest/api/sql/index.html#hex>
+#[derive(Debug)]
+pub struct SparkHex {
+ signature: Signature,
+ aliases: Vec<String>,
+}
+
+impl Default for SparkHex {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl SparkHex {
+ pub fn new() -> Self {
+ Self {
+ signature: Signature::user_defined(Volatility::Immutable),
+ aliases: vec![],
+ }
+ }
+}
+
+impl ScalarUDFImpl for SparkHex {
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+
+ fn name(&self) -> &str {
+ "hex"
+ }
+
+ fn signature(&self) -> &Signature {
+ &self.signature
+ }
+
+ fn return_type(
+ &self,
+ _arg_types: &[DataType],
+ ) -> datafusion_common::Result<DataType> {
+ Ok(DataType::Utf8)
+ }
+
+ fn invoke_with_args(
+ &self,
+ args: ScalarFunctionArgs,
+ ) -> datafusion_common::Result<ColumnarValue> {
+ spark_hex(&args.args)
+ }
+
+ fn aliases(&self) -> &[String] {
+ &self.aliases
+ }
+
+ fn coerce_types(
+ &self,
+ arg_types: &[DataType],
+ ) -> datafusion_common::Result<Vec<DataType>> {
+ if arg_types.len() != 1 {
+ return Err(invalid_arg_count_exec_err("expm1", (1, 1), arg_types.len()));
+ }
+ match &arg_types[0] {
+ DataType::Int64
+ | DataType::Utf8
+ | DataType::LargeUtf8
+ | DataType::Binary
+ | DataType::LargeBinary => Ok(vec![arg_types[0].clone()]),
+ DataType::Dictionary(key_type, value_type) => match value_type.as_ref() {
Review Comment:
I think it would be simpler if you could use some of the existing signatures and then return something for `signature()`:
https://github.com/apache/datafusion/blob/a39c07a2338a46fccc1111cafb5a2ffdcf6fd329/datafusion/functions/src/string/to_hex.rs#L116
That way the built in coercion logic would take over. If that doesn't work for spark functions, perhaps we can define some spark compatible signatures (as in implement `SparkSignature` that would return a https://docs.rs/datafusion/latest/datafusion/logical_expr/enum.TypeSignature.html)
##########
datafusion/sqllogictest/test_files/spark/math/hex.slt:
##########
@@ -0,0 +1,26 @@
+# 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.
+
+query T
Review Comment:
It would be nice to add some array level tests, which is described in https://github.com/apache/datafusion/blob/main/datafusion/sqllogictest/test_files/spark/README.md
##########
datafusion/spark/src/function/math/hex.rs:
##########
@@ -0,0 +1,404 @@
+// 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 crate::function::error_utils::{
+ invalid_arg_count_exec_err, unsupported_data_type_exec_err,
+};
+use arrow::array::{Array, StringArray};
+use arrow::datatypes::DataType;
+use arrow::{
+ array::{as_dictionary_array, as_largestring_array, as_string_array},
+ datatypes::Int32Type,
+};
+use datafusion_common::{
+ cast::{as_binary_array, as_fixed_size_binary_array, as_int64_array},
+ exec_err, DataFusionError,
+};
+use datafusion_expr::Signature;
+use datafusion_expr::{ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Volatility};
+use std::fmt::Write;
+
+/// <https://spark.apache.org/docs/latest/api/sql/index.html#hex>
+#[derive(Debug)]
+pub struct SparkHex {
+ signature: Signature,
+ aliases: Vec<String>,
+}
+
+impl Default for SparkHex {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl SparkHex {
+ pub fn new() -> Self {
+ Self {
+ signature: Signature::user_defined(Volatility::Immutable),
+ aliases: vec![],
+ }
+ }
+}
+
+impl ScalarUDFImpl for SparkHex {
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+
+ fn name(&self) -> &str {
+ "hex"
+ }
+
+ fn signature(&self) -> &Signature {
+ &self.signature
+ }
+
+ fn return_type(
+ &self,
+ _arg_types: &[DataType],
+ ) -> datafusion_common::Result<DataType> {
+ Ok(DataType::Utf8)
+ }
+
+ fn invoke_with_args(
+ &self,
+ args: ScalarFunctionArgs,
+ ) -> datafusion_common::Result<ColumnarValue> {
+ spark_hex(&args.args)
+ }
+
+ fn aliases(&self) -> &[String] {
+ &self.aliases
+ }
+
+ fn coerce_types(
+ &self,
+ arg_types: &[DataType],
+ ) -> datafusion_common::Result<Vec<DataType>> {
+ if arg_types.len() != 1 {
+ return Err(invalid_arg_count_exec_err("hex", (1, 1), arg_types.len()));
+ }
+ match &arg_types[0] {
+ DataType::Int64
+ | DataType::Utf8
+ | DataType::LargeUtf8
+ | DataType::Binary
+ | DataType::LargeBinary => Ok(vec![arg_types[0].clone()]),
+ DataType::Dictionary(key_type, value_type) => match value_type.as_ref() {
+ DataType::Int64
+ | DataType::Utf8
+ | DataType::LargeUtf8
+ | DataType::Binary
+ | DataType::LargeBinary => Ok(vec![arg_types[0].clone()]),
+ other => {
+ if other.is_numeric() {
+ Ok(vec![DataType::Dictionary(
+ key_type.clone(),
+ Box::new(DataType::Int64),
+ )])
+ } else {
+ Err(unsupported_data_type_exec_err(
+ "hex",
+ "Numeric, String, or Binary",
+ &arg_types[0],
+ ))
+ }
+ }
+ },
+ other => {
+ if other.is_numeric() {
+ Ok(vec![DataType::Int64])
+ } else {
+ Err(unsupported_data_type_exec_err(
+ "hex",
+ "Numeric, String, or Binary",
+ &arg_types[0],
+ ))
+ }
+ }
+ }
+ }
+}
+
+fn hex_int64(num: i64) -> String {
+ format!("{:X}", num)
+}
+
+#[inline(always)]
+fn hex_encode<T: AsRef<[u8]>>(data: T, lower_case: bool) -> String {
+ let mut s = String::with_capacity(data.as_ref().len() * 2);
+ if lower_case {
+ for b in data.as_ref() {
+ // Writing to a string never errors, so we can unwrap here.
+ write!(&mut s, "{b:02x}").unwrap();
+ }
+ } else {
+ for b in data.as_ref() {
+ // Writing to a string never errors, so we can unwrap here.
+ write!(&mut s, "{b:02X}").unwrap();
+ }
+ }
+ s
+}
+
+#[inline(always)]
+fn hex_bytes<T: AsRef<[u8]>>(bytes: T) -> Result<String, std::fmt::Error> {
+ let hex_string = hex_encode(bytes, false);
+ Ok(hex_string)
+}
+
+/// Spark-compatible `hex` function
+pub fn spark_hex(args: &[ColumnarValue]) -> Result<ColumnarValue, DataFusionError> {
+ if args.len() != 1 {
+ return Err(DataFusionError::Internal(
+ "hex expects exactly one argument".to_string(),
+ ));
+ }
+
+ let input = match &args[0] {
+ ColumnarValue::Scalar(value) => ColumnarValue::Array(value.to_array()?),
+ ColumnarValue::Array(_) => args[0].clone(),
+ };
+
+ match &input {
+ ColumnarValue::Array(array) => match array.data_type() {
+ DataType::Int64 => {
+ let array = as_int64_array(array)?;
+
+ let hexed_array: StringArray =
+ array.iter().map(|v| v.map(hex_int64)).collect();
+
+ Ok(ColumnarValue::Array(Arc::new(hexed_array)))
+ }
+ DataType::Utf8 => {
+ let array = as_string_array(array);
+
+ let hexed: StringArray = array
+ .iter()
+ .map(|v| v.map(hex_bytes).transpose())
+ .collect::<Result<_, _>>()?;
+
+ Ok(ColumnarValue::Array(Arc::new(hexed)))
+ }
+ DataType::LargeUtf8 => {
+ let array = as_largestring_array(array);
+
+ let hexed: StringArray = array
+ .iter()
+ .map(|v| v.map(hex_bytes).transpose())
+ .collect::<Result<_, _>>()?;
+
+ Ok(ColumnarValue::Array(Arc::new(hexed)))
+ }
+ DataType::Binary => {
+ let array = as_binary_array(array)?;
+
+ let hexed: StringArray = array
+ .iter()
+ .map(|v| v.map(hex_bytes).transpose())
+ .collect::<Result<_, _>>()?;
+
+ Ok(ColumnarValue::Array(Arc::new(hexed)))
+ }
+ DataType::FixedSizeBinary(_) => {
+ let array = as_fixed_size_binary_array(array)?;
+
+ let hexed: StringArray = array
+ .iter()
+ .map(|v| v.map(hex_bytes).transpose())
+ .collect::<Result<_, _>>()?;
+
+ Ok(ColumnarValue::Array(Arc::new(hexed)))
+ }
+ DataType::Dictionary(_, value_type) => {
+ let dict = as_dictionary_array::<Int32Type>(&array);
+
+ let values = match **value_type {
+ DataType::Int64 => as_int64_array(dict.values())?
+ .iter()
+ .map(|v| v.map(hex_int64))
+ .collect::<Vec<_>>(),
+ DataType::Utf8 => as_string_array(dict.values())
+ .iter()
+ .map(|v| v.map(hex_bytes).transpose())
+ .collect::<Result<_, _>>()?,
+ DataType::Binary => as_binary_array(dict.values())?
+ .iter()
+ .map(|v| v.map(hex_bytes).transpose())
+ .collect::<Result<_, _>>()?,
+ _ => exec_err!(
+ "hex got an unexpected argument type: {:?}",
+ array.data_type()
+ )?,
+ };
+
+ let new_values: Vec<Option<String>> = dict
Review Comment:
You can likely make this more efficient by avoiding the Strings here and reuse the dictionary keys with the new values
Something like
```rust
let new_dict_array = DictionaryArray::new(dict.keys().clone(), values)
```
--
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] [datafusion-spark] Add Spark-compatible hex function [datafusion]
Posted by "andygrove (via GitHub)" <gi...@apache.org>.
andygrove commented on code in PR #15947:
URL: https://github.com/apache/datafusion/pull/15947#discussion_r2073711784
##########
datafusion/spark/src/function/math/hex.rs:
##########
@@ -0,0 +1,404 @@
+// 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 crate::function::error_utils::{
+ invalid_arg_count_exec_err, unsupported_data_type_exec_err,
+};
+use arrow::array::{Array, StringArray};
+use arrow::datatypes::DataType;
+use arrow::{
+ array::{as_dictionary_array, as_largestring_array, as_string_array},
+ datatypes::Int32Type,
+};
+use datafusion_common::{
+ cast::{as_binary_array, as_fixed_size_binary_array, as_int64_array},
+ exec_err, DataFusionError,
+};
+use datafusion_expr::Signature;
+use datafusion_expr::{ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Volatility};
+use std::fmt::Write;
+
+/// <https://spark.apache.org/docs/latest/api/sql/index.html#hex>
+#[derive(Debug)]
+pub struct SparkHex {
+ signature: Signature,
+ aliases: Vec<String>,
+}
+
+impl Default for SparkHex {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl SparkHex {
+ pub fn new() -> Self {
+ Self {
+ signature: Signature::user_defined(Volatility::Immutable),
+ aliases: vec![],
+ }
+ }
+}
+
+impl ScalarUDFImpl for SparkHex {
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+
+ fn name(&self) -> &str {
+ "hex"
+ }
+
+ fn signature(&self) -> &Signature {
+ &self.signature
+ }
+
+ fn return_type(
+ &self,
+ _arg_types: &[DataType],
+ ) -> datafusion_common::Result<DataType> {
+ Ok(DataType::Utf8)
+ }
+
+ fn invoke_with_args(
+ &self,
+ args: ScalarFunctionArgs,
+ ) -> datafusion_common::Result<ColumnarValue> {
+ spark_hex(&args.args)
+ }
+
+ fn aliases(&self) -> &[String] {
+ &self.aliases
+ }
+
+ fn coerce_types(
+ &self,
+ arg_types: &[DataType],
+ ) -> datafusion_common::Result<Vec<DataType>> {
+ if arg_types.len() != 1 {
+ return Err(invalid_arg_count_exec_err("expm1", (1, 1), arg_types.len()));
+ }
+ match &arg_types[0] {
+ DataType::Int64
+ | DataType::Utf8
+ | DataType::LargeUtf8
+ | DataType::Binary
+ | DataType::LargeBinary => Ok(vec![arg_types[0].clone()]),
+ DataType::Dictionary(key_type, value_type) => match value_type.as_ref() {
Review Comment:
@shehabgamin @alamb Is the correct way to handle dictionary-encoding coercion? I did not see this handled in the `expm1` function.
--
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] [datafusion-spark] Add Spark-compatible hex function [datafusion]
Posted by "andygrove (via GitHub)" <gi...@apache.org>.
andygrove commented on PR #15947:
URL: https://github.com/apache/datafusion/pull/15947#issuecomment-2863214007
I agree with @alamb that we should go ahead and merge this, and then I can update Comet to use it so we have confidence that this approach is working (I think it is). Thanks for the reviews @alamb and @shehabgamin.
--
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] [datafusion-spark] Add Spark-compatible hex function [datafusion]
Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #15947:
URL: https://github.com/apache/datafusion/pull/15947#discussion_r2074113601
##########
datafusion/spark/src/function/math/hex.rs:
##########
@@ -0,0 +1,404 @@
+// 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 crate::function::error_utils::{
+ invalid_arg_count_exec_err, unsupported_data_type_exec_err,
+};
+use arrow::array::{Array, StringArray};
+use arrow::datatypes::DataType;
+use arrow::{
+ array::{as_dictionary_array, as_largestring_array, as_string_array},
+ datatypes::Int32Type,
+};
+use datafusion_common::{
+ cast::{as_binary_array, as_fixed_size_binary_array, as_int64_array},
+ exec_err, DataFusionError,
+};
+use datafusion_expr::Signature;
+use datafusion_expr::{ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Volatility};
+use std::fmt::Write;
+
+/// <https://spark.apache.org/docs/latest/api/sql/index.html#hex>
+#[derive(Debug)]
+pub struct SparkHex {
+ signature: Signature,
+ aliases: Vec<String>,
+}
+
+impl Default for SparkHex {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl SparkHex {
+ pub fn new() -> Self {
+ Self {
+ signature: Signature::user_defined(Volatility::Immutable),
+ aliases: vec![],
+ }
+ }
+}
+
+impl ScalarUDFImpl for SparkHex {
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+
+ fn name(&self) -> &str {
+ "hex"
+ }
+
+ fn signature(&self) -> &Signature {
+ &self.signature
+ }
+
+ fn return_type(
+ &self,
+ _arg_types: &[DataType],
+ ) -> datafusion_common::Result<DataType> {
+ Ok(DataType::Utf8)
+ }
+
+ fn invoke_with_args(
+ &self,
+ args: ScalarFunctionArgs,
+ ) -> datafusion_common::Result<ColumnarValue> {
+ spark_hex(&args.args)
+ }
+
+ fn aliases(&self) -> &[String] {
+ &self.aliases
+ }
+
+ fn coerce_types(
+ &self,
+ arg_types: &[DataType],
+ ) -> datafusion_common::Result<Vec<DataType>> {
+ if arg_types.len() != 1 {
+ return Err(invalid_arg_count_exec_err("expm1", (1, 1), arg_types.len()));
+ }
+ match &arg_types[0] {
+ DataType::Int64
+ | DataType::Utf8
+ | DataType::LargeUtf8
+ | DataType::Binary
+ | DataType::LargeBinary => Ok(vec![arg_types[0].clone()]),
+ DataType::Dictionary(key_type, value_type) => match value_type.as_ref() {
Review Comment:
We can also wait for a few more PRs to see if there is a common pattern emerging before refactoring
--
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] [datafusion-spark] Add Spark-compatible hex function [datafusion]
Posted by "shehabgamin (via GitHub)" <gi...@apache.org>.
shehabgamin commented on code in PR #15947:
URL: https://github.com/apache/datafusion/pull/15947#discussion_r2077032231
##########
datafusion/sqllogictest/test_files/spark/math/hex.slt:
##########
@@ -0,0 +1,26 @@
+# 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.
+
+query T
Review Comment:
+1 on the array level tests
##########
datafusion/spark/src/function/math/hex.rs:
##########
@@ -0,0 +1,404 @@
+// 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 crate::function::error_utils::{
+ invalid_arg_count_exec_err, unsupported_data_type_exec_err,
+};
+use arrow::array::{Array, StringArray};
+use arrow::datatypes::DataType;
+use arrow::{
+ array::{as_dictionary_array, as_largestring_array, as_string_array},
+ datatypes::Int32Type,
+};
+use datafusion_common::{
+ cast::{as_binary_array, as_fixed_size_binary_array, as_int64_array},
+ exec_err, DataFusionError,
+};
+use datafusion_expr::Signature;
+use datafusion_expr::{ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Volatility};
+use std::fmt::Write;
+
+/// <https://spark.apache.org/docs/latest/api/sql/index.html#hex>
+#[derive(Debug)]
+pub struct SparkHex {
+ signature: Signature,
+ aliases: Vec<String>,
+}
+
+impl Default for SparkHex {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl SparkHex {
+ pub fn new() -> Self {
+ Self {
+ signature: Signature::user_defined(Volatility::Immutable),
+ aliases: vec![],
+ }
+ }
+}
+
+impl ScalarUDFImpl for SparkHex {
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+
+ fn name(&self) -> &str {
+ "hex"
+ }
+
+ fn signature(&self) -> &Signature {
+ &self.signature
+ }
+
+ fn return_type(
+ &self,
+ _arg_types: &[DataType],
+ ) -> datafusion_common::Result<DataType> {
+ Ok(DataType::Utf8)
+ }
+
+ fn invoke_with_args(
+ &self,
+ args: ScalarFunctionArgs,
+ ) -> datafusion_common::Result<ColumnarValue> {
+ spark_hex(&args.args)
+ }
+
+ fn aliases(&self) -> &[String] {
+ &self.aliases
+ }
+
+ fn coerce_types(
+ &self,
+ arg_types: &[DataType],
+ ) -> datafusion_common::Result<Vec<DataType>> {
+ if arg_types.len() != 1 {
+ return Err(invalid_arg_count_exec_err("hex", (1, 1), arg_types.len()));
+ }
+ match &arg_types[0] {
+ DataType::Int64
+ | DataType::Utf8
+ | DataType::LargeUtf8
+ | DataType::Binary
+ | DataType::LargeBinary => Ok(vec![arg_types[0].clone()]),
+ DataType::Dictionary(key_type, value_type) => match value_type.as_ref() {
+ DataType::Int64
+ | DataType::Utf8
+ | DataType::LargeUtf8
+ | DataType::Binary
+ | DataType::LargeBinary => Ok(vec![arg_types[0].clone()]),
+ other => {
+ if other.is_numeric() {
+ Ok(vec![DataType::Dictionary(
+ key_type.clone(),
+ Box::new(DataType::Int64),
+ )])
+ } else {
+ Err(unsupported_data_type_exec_err(
+ "hex",
+ "Numeric, String, or Binary",
+ &arg_types[0],
+ ))
+ }
+ }
+ },
+ other => {
+ if other.is_numeric() {
+ Ok(vec![DataType::Int64])
+ } else {
+ Err(unsupported_data_type_exec_err(
+ "hex",
+ "Numeric, String, or Binary",
+ &arg_types[0],
+ ))
+ }
+ }
+ }
+ }
+}
+
+fn hex_int64(num: i64) -> String {
+ format!("{:X}", num)
+}
+
+#[inline(always)]
+fn hex_encode<T: AsRef<[u8]>>(data: T, lower_case: bool) -> String {
+ let mut s = String::with_capacity(data.as_ref().len() * 2);
+ if lower_case {
+ for b in data.as_ref() {
+ // Writing to a string never errors, so we can unwrap here.
+ write!(&mut s, "{b:02x}").unwrap();
+ }
+ } else {
+ for b in data.as_ref() {
+ // Writing to a string never errors, so we can unwrap here.
+ write!(&mut s, "{b:02X}").unwrap();
+ }
+ }
+ s
+}
+
+#[inline(always)]
+fn hex_bytes<T: AsRef<[u8]>>(bytes: T) -> Result<String, std::fmt::Error> {
+ let hex_string = hex_encode(bytes, false);
+ Ok(hex_string)
+}
+
+/// Spark-compatible `hex` function
+pub fn spark_hex(args: &[ColumnarValue]) -> Result<ColumnarValue, DataFusionError> {
+ if args.len() != 1 {
+ return Err(DataFusionError::Internal(
+ "hex expects exactly one argument".to_string(),
+ ));
+ }
+
+ let input = match &args[0] {
+ ColumnarValue::Scalar(value) => ColumnarValue::Array(value.to_array()?),
+ ColumnarValue::Array(_) => args[0].clone(),
+ };
+
+ match &input {
+ ColumnarValue::Array(array) => match array.data_type() {
+ DataType::Int64 => {
+ let array = as_int64_array(array)?;
+
+ let hexed_array: StringArray =
+ array.iter().map(|v| v.map(hex_int64)).collect();
+
+ Ok(ColumnarValue::Array(Arc::new(hexed_array)))
+ }
+ DataType::Utf8 => {
+ let array = as_string_array(array);
+
+ let hexed: StringArray = array
+ .iter()
+ .map(|v| v.map(hex_bytes).transpose())
+ .collect::<Result<_, _>>()?;
+
+ Ok(ColumnarValue::Array(Arc::new(hexed)))
+ }
+ DataType::LargeUtf8 => {
+ let array = as_largestring_array(array);
+
+ let hexed: StringArray = array
+ .iter()
+ .map(|v| v.map(hex_bytes).transpose())
+ .collect::<Result<_, _>>()?;
+
+ Ok(ColumnarValue::Array(Arc::new(hexed)))
+ }
+ DataType::Binary => {
+ let array = as_binary_array(array)?;
+
+ let hexed: StringArray = array
+ .iter()
+ .map(|v| v.map(hex_bytes).transpose())
+ .collect::<Result<_, _>>()?;
+
+ Ok(ColumnarValue::Array(Arc::new(hexed)))
+ }
+ DataType::FixedSizeBinary(_) => {
+ let array = as_fixed_size_binary_array(array)?;
+
+ let hexed: StringArray = array
+ .iter()
+ .map(|v| v.map(hex_bytes).transpose())
+ .collect::<Result<_, _>>()?;
+
+ Ok(ColumnarValue::Array(Arc::new(hexed)))
+ }
+ DataType::Dictionary(_, value_type) => {
+ let dict = as_dictionary_array::<Int32Type>(&array);
+
+ let values = match **value_type {
+ DataType::Int64 => as_int64_array(dict.values())?
+ .iter()
+ .map(|v| v.map(hex_int64))
+ .collect::<Vec<_>>(),
+ DataType::Utf8 => as_string_array(dict.values())
+ .iter()
+ .map(|v| v.map(hex_bytes).transpose())
+ .collect::<Result<_, _>>()?,
+ DataType::Binary => as_binary_array(dict.values())?
+ .iter()
+ .map(|v| v.map(hex_bytes).transpose())
+ .collect::<Result<_, _>>()?,
+ _ => exec_err!(
+ "hex got an unexpected argument type: {:?}",
+ array.data_type()
+ )?,
+ };
+
+ let new_values: Vec<Option<String>> = dict
+ .keys()
+ .iter()
+ .map(|key| key.map(|k| values[k as usize].clone()).unwrap_or(None))
+ .collect();
+
+ let string_array_values = StringArray::from(new_values);
+
+ Ok(ColumnarValue::Array(Arc::new(string_array_values)))
+ }
+ _ => exec_err!(
+ "hex got an unexpected argument type: {:?}",
+ array.data_type()
+ ),
+ },
+ _ => exec_err!("native hex does not support scalar values at this time"),
+ }
+}
+
+#[cfg(test)]
+mod test {
Review Comment:
These tests are great!
--
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] [datafusion-spark] Add Spark-compatible hex function [datafusion]
Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #15947:
URL: https://github.com/apache/datafusion/pull/15947#discussion_r2074114006
##########
datafusion/spark/src/function/math/hex.rs:
##########
@@ -0,0 +1,404 @@
+// 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 crate::function::error_utils::{
+ invalid_arg_count_exec_err, unsupported_data_type_exec_err,
+};
+use arrow::array::{Array, StringArray};
+use arrow::datatypes::DataType;
+use arrow::{
+ array::{as_dictionary_array, as_largestring_array, as_string_array},
+ datatypes::Int32Type,
+};
+use datafusion_common::{
+ cast::{as_binary_array, as_fixed_size_binary_array, as_int64_array},
+ exec_err, DataFusionError,
+};
+use datafusion_expr::Signature;
+use datafusion_expr::{ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Volatility};
+use std::fmt::Write;
+
+/// <https://spark.apache.org/docs/latest/api/sql/index.html#hex>
+#[derive(Debug)]
+pub struct SparkHex {
+ signature: Signature,
+ aliases: Vec<String>,
+}
+
+impl Default for SparkHex {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl SparkHex {
+ pub fn new() -> Self {
+ Self {
+ signature: Signature::user_defined(Volatility::Immutable),
+ aliases: vec![],
+ }
+ }
+}
+
+impl ScalarUDFImpl for SparkHex {
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+
+ fn name(&self) -> &str {
+ "hex"
+ }
+
+ fn signature(&self) -> &Signature {
+ &self.signature
+ }
+
+ fn return_type(
+ &self,
+ _arg_types: &[DataType],
+ ) -> datafusion_common::Result<DataType> {
+ Ok(DataType::Utf8)
+ }
+
+ fn invoke_with_args(
+ &self,
+ args: ScalarFunctionArgs,
+ ) -> datafusion_common::Result<ColumnarValue> {
+ spark_hex(&args.args)
+ }
+
+ fn aliases(&self) -> &[String] {
+ &self.aliases
+ }
+
+ fn coerce_types(
+ &self,
+ arg_types: &[DataType],
+ ) -> datafusion_common::Result<Vec<DataType>> {
+ if arg_types.len() != 1 {
+ return Err(invalid_arg_count_exec_err("expm1", (1, 1), arg_types.len()));
+ }
+ match &arg_types[0] {
+ DataType::Int64
+ | DataType::Utf8
+ | DataType::LargeUtf8
+ | DataType::Binary
+ | DataType::LargeBinary => Ok(vec![arg_types[0].clone()]),
+ DataType::Dictionary(key_type, value_type) => match value_type.as_ref() {
Review Comment:
> @shehabgamin @alamb Is the correct way to handle dictionary-encoding coercion? I did not see this handled in the expm1 function.
FWIW I think it is the correct way to handle the dictionary coercion
--
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] [datafusion-spark] Add Spark-compatible hex function [datafusion]
Posted by "shehabgamin (via GitHub)" <gi...@apache.org>.
shehabgamin commented on code in PR #15947:
URL: https://github.com/apache/datafusion/pull/15947#discussion_r2074093408
##########
datafusion/spark/src/function/math/hex.rs:
##########
@@ -0,0 +1,404 @@
+// 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 crate::function::error_utils::{
+ invalid_arg_count_exec_err, unsupported_data_type_exec_err,
+};
+use arrow::array::{Array, StringArray};
+use arrow::datatypes::DataType;
+use arrow::{
+ array::{as_dictionary_array, as_largestring_array, as_string_array},
+ datatypes::Int32Type,
+};
+use datafusion_common::{
+ cast::{as_binary_array, as_fixed_size_binary_array, as_int64_array},
+ exec_err, DataFusionError,
+};
+use datafusion_expr::Signature;
+use datafusion_expr::{ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Volatility};
+use std::fmt::Write;
+
+/// <https://spark.apache.org/docs/latest/api/sql/index.html#hex>
+#[derive(Debug)]
+pub struct SparkHex {
+ signature: Signature,
+ aliases: Vec<String>,
+}
+
+impl Default for SparkHex {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl SparkHex {
+ pub fn new() -> Self {
+ Self {
+ signature: Signature::user_defined(Volatility::Immutable),
+ aliases: vec![],
+ }
+ }
+}
+
+impl ScalarUDFImpl for SparkHex {
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+
+ fn name(&self) -> &str {
+ "hex"
+ }
+
+ fn signature(&self) -> &Signature {
+ &self.signature
+ }
+
+ fn return_type(
+ &self,
+ _arg_types: &[DataType],
+ ) -> datafusion_common::Result<DataType> {
+ Ok(DataType::Utf8)
+ }
+
+ fn invoke_with_args(
+ &self,
+ args: ScalarFunctionArgs,
+ ) -> datafusion_common::Result<ColumnarValue> {
+ spark_hex(&args.args)
+ }
+
+ fn aliases(&self) -> &[String] {
+ &self.aliases
+ }
+
+ fn coerce_types(
+ &self,
+ arg_types: &[DataType],
+ ) -> datafusion_common::Result<Vec<DataType>> {
+ if arg_types.len() != 1 {
+ return Err(invalid_arg_count_exec_err("expm1", (1, 1), arg_types.len()));
+ }
+ match &arg_types[0] {
+ DataType::Int64
+ | DataType::Utf8
+ | DataType::LargeUtf8
+ | DataType::Binary
+ | DataType::LargeBinary => Ok(vec![arg_types[0].clone()]),
+ DataType::Dictionary(key_type, value_type) => match value_type.as_ref() {
Review Comment:
@andygrove This seems fine to me. If the logic is unique to `hex`, it probably doesn't make sense to extract it into a reusable function.
If the logic is reusable, we could add `SparkSignature` like @alamb suggested. I've found that the existing DataFusion signatures are not always compatible with Spark's behavior. I've also found that a lot of Spark functions have custom and unique coercion 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: 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