Skip to content

Apache DataFusion SQL Query Engine

feat: ADD sha2 spark function (#16168)

Namgung Chan260a28a5c1e4
diff --git a/datafusion/spark/src/function/hash/mod.rs b/datafusion/spark/src/function/hash/mod.rs
index a87df9a2c8..f31918e6a4 100644
--- a/datafusion/spark/src/function/hash/mod.rs
+++ b/datafusion/spark/src/function/hash/mod.rs
@@ -15,11 +15,19 @@
// specific language governing permissions and limitations
// under the License.
+pub mod sha2;
+
use datafusion_expr::ScalarUDF;
+use datafusion_functions::make_udf_function;
use std::sync::Arc;
-pub mod expr_fn {}
+make_udf_function!(sha2::SparkSha2, sha2);
+
+pub mod expr_fn {
+ use datafusion_functions::export_functions;
+ export_functions!((sha2, "sha2(expr, bitLength) - Returns a checksum of SHA-2 family as a hex string of expr. SHA-224, SHA-256, SHA-384, and SHA-512 are supported. Bit length of 0 is equivalent to 256.", arg1 arg2));
+}
pub fn functions() -> Vec<Arc<ScalarUDF>> {
- vec![]
+ vec![sha2()]
}
diff --git a/datafusion/spark/src/function/hash/sha2.rs b/datafusion/spark/src/function/hash/sha2.rs
new file mode 100644
index 0000000000..b4b29ef334
--- /dev/null
+++ b/datafusion/spark/src/function/hash/sha2.rs
@@ -0,0 +1,217 @@
+// 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.
+
+extern crate datafusion_functions;
+
+use crate::function::error_utils::{
+ invalid_arg_count_exec_err, unsupported_data_type_exec_err,
+};
+use crate::function::math::hex::spark_hex;
+use arrow::array::{ArrayRef, AsArray, StringArray};
+use arrow::datatypes::{DataType, UInt32Type};
+use datafusion_common::{exec_err, internal_datafusion_err, Result, ScalarValue};
+use datafusion_expr::Signature;
+use datafusion_expr::{ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Volatility};
+pub use datafusion_functions::crypto::basic::{sha224, sha256, sha384, sha512};
+use std::any::Any;
+use std::sync::Arc;
+
+/// <https://spark.apache.org/docs/latest/api/sql/index.html#sha2>
+#[derive(Debug)]
+pub struct SparkSha2 {
+ signature: Signature,
+ aliases: Vec<String>,
+}
+
+impl Default for SparkSha2 {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl SparkSha2 {
+ pub fn new() -> Self {
+ Self {
+ signature: Signature::user_defined(Volatility::Immutable),
+ aliases: vec![],
+ }
+ }
+}
+
+impl ScalarUDFImpl for SparkSha2 {
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+
+ fn name(&self) -> &str {
+ "sha2"
+ }
+
+ fn signature(&self) -> &Signature {
+ &self.signature
+ }
+
+ fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
+ if arg_types[1].is_null() {
+ return Ok(DataType::Null);
+ }
+ Ok(match arg_types[0] {
+ DataType::Utf8View
+ | DataType::LargeUtf8
+ | DataType::Utf8
+ | DataType::Binary
+ | DataType::BinaryView
+ | DataType::LargeBinary => DataType::Utf8,
+ DataType::Null => DataType::Null,
+ _ => {
+ return exec_err!(
+ "{} function can only accept strings or binary arrays.",
+ self.name()
+ )
+ }
+ })
+ }
+
+ fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
+ let args: [ColumnarValue; 2] = args.args.try_into().map_err(|_| {
+ internal_datafusion_err!("Expected 2 arguments for function sha2")
+ })?;
+
+ sha2(args)
+ }
+
+ fn aliases(&self) -> &[String] {
+ &self.aliases
+ }
+
+ fn coerce_types(&self, arg_types: &[DataType]) -> Result<Vec<DataType>> {
+ if arg_types.len() != 2 {
+ return Err(invalid_arg_count_exec_err(
+ self.name(),
+ (2, 2),
+ arg_types.len(),
+ ));
+ }
+ let expr_type = match &arg_types[0] {
+ DataType::Utf8View
+ | DataType::LargeUtf8
+ | DataType::Utf8
+ | DataType::Binary
+ | DataType::BinaryView
+ | DataType::LargeBinary
+ | DataType::Null => Ok(arg_types[0].clone()),
+ _ => Err(unsupported_data_type_exec_err(
+ self.name(),
+ "String, Binary",
+ &arg_types[0],
+ )),
+ }?;
+ let bit_length_type = if arg_types[1].is_numeric() {
+ Ok(DataType::UInt32)
+ } else if arg_types[1].is_null() {
+ Ok(DataType::Null)
+ } else {
+ Err(unsupported_data_type_exec_err(
+ self.name(),
+ "Numeric Type",
+ &arg_types[1],
+ ))
+ }?;
+
+ Ok(vec![expr_type, bit_length_type])
+ }
+}
+
+pub fn sha2(args: [ColumnarValue; 2]) -> Result<ColumnarValue> {
+ match args {
+ [ColumnarValue::Scalar(ScalarValue::Utf8(expr_arg)), ColumnarValue::Scalar(ScalarValue::UInt32(Some(bit_length_arg)))] => {
+ match bit_length_arg {
+ 0 | 256 => sha256(&[ColumnarValue::from(ScalarValue::Utf8(expr_arg))]),
+ 224 => sha224(&[ColumnarValue::from(ScalarValue::Utf8(expr_arg))]),
+ 384 => sha384(&[ColumnarValue::from(ScalarValue::Utf8(expr_arg))]),
+ 512 => sha512(&[ColumnarValue::from(ScalarValue::Utf8(expr_arg))]),
+ _ => exec_err!(
+ "sha2 function only supports 224, 256, 384, and 512 bit lengths."
+ ),
+ }
+ .map(|hashed| spark_hex(&[hashed]).unwrap())
+ }
+ [ColumnarValue::Array(expr_arg), ColumnarValue::Scalar(ScalarValue::UInt32(Some(bit_length_arg)))] => {
+ match bit_length_arg {
+ 0 | 256 => sha256(&[ColumnarValue::from(expr_arg)]),
+ 224 => sha224(&[ColumnarValue::from(expr_arg)]),
+ 384 => sha384(&[ColumnarValue::from(expr_arg)]),
+ 512 => sha512(&[ColumnarValue::from(expr_arg)]),
+ _ => exec_err!(
+ "sha2 function only supports 224, 256, 384, and 512 bit lengths."
+ ),
+ }
+ .map(|hashed| spark_hex(&[hashed]).unwrap())
+ }
+ [ColumnarValue::Scalar(ScalarValue::Utf8(expr_arg)), ColumnarValue::Array(bit_length_arg)] =>
+ {
+ let arr: StringArray = bit_length_arg
+ .as_primitive::<UInt32Type>()
+ .iter()
+ .map(|bit_length| {
+ match sha2([
+ ColumnarValue::Scalar(ScalarValue::Utf8(expr_arg.clone())),
+ ColumnarValue::Scalar(ScalarValue::UInt32(bit_length)),
+ ])
+ .unwrap()
+ {
+ ColumnarValue::Scalar(ScalarValue::Utf8(str)) => str,
+ ColumnarValue::Array(arr) => arr
+ .as_string::<i32>()
+ .iter()
+ .map(|str| str.unwrap().to_string())
+ .next(), // first element
+ _ => unreachable!(),
+ }
+ })
+ .collect();
+ Ok(ColumnarValue::Array(Arc::new(arr) as ArrayRef))
+ }
+ [ColumnarValue::Array(expr_arg), ColumnarValue::Array(bit_length_arg)] => {
+ let expr_iter = expr_arg.as_string::<i32>().iter();
+ let bit_length_iter = bit_length_arg.as_primitive::<UInt32Type>().iter();
+ let arr: StringArray = expr_iter
+ .zip(bit_length_iter)
+ .map(|(expr, bit_length)| {
+ match sha2([
+ ColumnarValue::Scalar(ScalarValue::Utf8(Some(
+ expr.unwrap().to_string(),
+ ))),
+ ColumnarValue::Scalar(ScalarValue::UInt32(bit_length)),
+ ])
+ .unwrap()
+ {
+ ColumnarValue::Scalar(ScalarValue::Utf8(str)) => str,
+ ColumnarValue::Array(arr) => arr
+ .as_string::<i32>()
+ .iter()
+ .map(|str| str.unwrap().to_string())
+ .next(), // first element
+ _ => unreachable!(),
+ }
+ })
+ .collect();
+ Ok(ColumnarValue::Array(Arc::new(arr) as ArrayRef))
+ }
+ _ => exec_err!("Unsupported argument types for sha2 function"),
+ }
+}
diff --git a/datafusion/sqllogictest/test_files/spark/hash/sha2.slt b/datafusion/sqllogictest/test_files/spark/hash/sha2.slt
new file mode 100644
index 0000000000..e2341df164
--- /dev/null
+++ b/datafusion/sqllogictest/test_files/spark/hash/sha2.slt
@@ -0,0 +1,65 @@
+# 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
+SELECT sha2('Spark', 0::INT);
+----
+529BC3B07127ECB7E53A4DCF1991D9152C24537D919178022B2C42657F79A26B
+
+query T
+SELECT sha2('Spark', 256::INT);
+----
+529BC3B07127ECB7E53A4DCF1991D9152C24537D919178022B2C42657F79A26B
+
+query T
+SELECT sha2('Spark', 224::INT);
+----
+DBEAB94971678D36AF2195851C0F7485775A2A7C60073D62FC04549C
+
+query T
+SELECT sha2('Spark', 384::INT);
+----
+1E40B8D06C248A1CC32428C22582B6219D072283078FA140D9AD297ECADF2CABEFC341B857AD36226AA8D6D79F2AB67D
+
+query T
+SELECT sha2('Spark', 512::INT);
+----
+44844A586C54C9A212DA1DBFE05C5F1705DE1AF5FDA1F0D36297623249B279FD8F0CCEC03F888F4FB13BF7CD83FDAD58591C797F81121A23CFDD5E0897795238
+
+query T
+SELECT sha2(expr, 256::INT) FROM VALUES ('foo'), ('bar') AS t(expr);
+----
+2C26B46B68FFC68FF99B453C1D30413413422D706483BFA0F98A5E886266E7AE
+FCDE2B2EDBA56BF408601FB721FE9B5C338D10EE429EA04FAE5511B68FBF8FB9
+
+query T
+SELECT sha2('foo', bit_length) FROM VALUES (0::INT), (256::INT), (224::INT), (384::INT), (512::INT) AS t(bit_length);
+----
+2C26B46B68FFC68FF99B453C1D30413413422D706483BFA0F98A5E886266E7AE
+2C26B46B68FFC68FF99B453C1D30413413422D706483BFA0F98A5E886266E7AE
+0808F64E60D58979FCB676C96EC938270DEA42445AEEFCD3A4E6F8DB
+98C11FFDFDD540676B1A137CB1A22B2A70350C9A44171D6B1180C6BE5CBB2EE3F79D532C8A1DD9EF2E8E08E752A3BABB
+F7FBBA6E0636F890E56FBBF3283E524C6FA3204AE298382D624741D0DC6638326E282C41BE5E4254D8820772C5518A2C5A8C0C7F7EDA19594A7EB539453E1ED7
+
+
+query T
+SELECT sha2(expr, bit_length) FROM VALUES ('foo',0::INT), ('bar',224::INT), ('baz',384::INT), ('qux',512::INT) AS t(expr, bit_length);
+----
+2C26B46B68FFC68FF99B453C1D30413413422D706483BFA0F98A5E886266E7AE
+07DAF010DE7F7F0D8D76A76EB8D1EB40182C8D1E7A3877A6686C9BF0
+967004D25DE4ABC1BD6A7C9A216254A5AC0733E8AD96DC9F1EA0FAD9619DA7C32D654EC8AD8BA2F9B5728FED6633BD91
+8C6BE9ED448A34883A13A13F4EAD4AEFA036B67DCDA59020C01E57EA075EA8A4792D428F2C6FD0C09D1C49994D6C22789336E062188DF29572ED07E7F9779C52