-
Notifications
You must be signed in to change notification settings - Fork 2k
feat: Implement Spark bin function
#20479
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
kazantsev-maksim
wants to merge
12
commits into
apache:main
Choose a base branch
from
kazantsev-maksim:spark_bin
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+244
−20
Open
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
6550560
Spark bin function implementation
c9515a9
Fix clippy
474f8fc
Fix tests
98c2066
Fix
38dd166
Fix PR issues
5ca5b5f
Fix PR issues
c87661e
Fix clippy
536f9f1
Fix PR issues
f2494dc
Fix PR issues
df2b053
Fix fmt
2031010
Fix tests
89cdfec
Fix tests
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,177 @@ | ||
| // 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 arrow::array::{ArrayRef, AsArray, StringArray}; | ||
| use arrow::datatypes::{ | ||
| DataType, Decimal32Type, Decimal64Type, Field, FieldRef, Float16Type, Float32Type, | ||
| Float64Type, Int8Type, Int16Type, Int32Type, Int64Type, | ||
| }; | ||
| use bigdecimal::ToPrimitive; | ||
| use datafusion::logical_expr::{ColumnarValue, Signature, TypeSignature, Volatility}; | ||
| use datafusion_common::types::{NativeType, logical_int64}; | ||
| use datafusion_common::utils::take_function_args; | ||
| use datafusion_common::{Result, internal_err}; | ||
| use datafusion_expr::{Coercion, ScalarFunctionArgs, ScalarUDFImpl, TypeSignatureClass}; | ||
| use datafusion_functions::utils::make_scalar_function; | ||
| use std::any::Any; | ||
| use std::sync::Arc; | ||
|
|
||
| /// Spark-compatible `bin` expression | ||
| /// <https://spark.apache.org/docs/latest/api/sql/index.html#bin> | ||
| #[derive(Debug, PartialEq, Eq, Hash)] | ||
| pub struct SparkBin { | ||
| signature: Signature, | ||
| } | ||
|
|
||
| impl Default for SparkBin { | ||
| fn default() -> Self { | ||
| Self::new() | ||
| } | ||
| } | ||
|
|
||
| impl SparkBin { | ||
| pub fn new() -> Self { | ||
| Self { | ||
| signature: Signature::one_of( | ||
| vec![TypeSignature::Coercible(vec![Coercion::new_implicit( | ||
| TypeSignatureClass::Native(logical_int64()), | ||
| vec![TypeSignatureClass::Numeric], | ||
| NativeType::Int64, | ||
| )])], | ||
| Volatility::Immutable, | ||
| ), | ||
| } | ||
| } | ||
| } | ||
|
|
||
| impl ScalarUDFImpl for SparkBin { | ||
| fn as_any(&self) -> &dyn Any { | ||
| self | ||
| } | ||
|
|
||
| fn name(&self) -> &str { | ||
| "bin" | ||
| } | ||
|
|
||
| fn signature(&self) -> &Signature { | ||
| &self.signature | ||
| } | ||
|
|
||
| fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> { | ||
| internal_err!("return_field_from_args should be used instead") | ||
| } | ||
|
|
||
| fn return_field_from_args( | ||
| &self, | ||
| args: datafusion_expr::ReturnFieldArgs, | ||
| ) -> Result<FieldRef> { | ||
| Ok(Arc::new(Field::new( | ||
| self.name(), | ||
| DataType::Utf8, | ||
| args.arg_fields[0].is_nullable(), | ||
| ))) | ||
| } | ||
|
|
||
| fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> { | ||
| make_scalar_function(spark_bin_inner, vec![])(&args.args) | ||
| } | ||
| } | ||
|
|
||
| pub fn spark_bin_inner(arg: &[ArrayRef]) -> Result<ArrayRef> { | ||
| let [array] = take_function_args("bin", arg)?; | ||
| match &array.data_type() { | ||
| DataType::Int8 => { | ||
| let result: StringArray = array | ||
| .as_primitive::<Int8Type>() | ||
| .iter() | ||
| .map(|opt| opt.map(|value| spark_bin(value.into()))) | ||
| .collect(); | ||
| Ok(Arc::new(result)) | ||
| } | ||
| DataType::Int16 => { | ||
| let result: StringArray = array | ||
| .as_primitive::<Int16Type>() | ||
| .iter() | ||
| .map(|opt| opt.map(|value| spark_bin(value.into()))) | ||
| .collect(); | ||
| Ok(Arc::new(result)) | ||
| } | ||
| DataType::Int32 => { | ||
| let result: StringArray = array | ||
| .as_primitive::<Int32Type>() | ||
| .iter() | ||
| .map(|opt| opt.map(|value| spark_bin(value.into()))) | ||
| .collect(); | ||
| Ok(Arc::new(result)) | ||
| } | ||
| DataType::Int64 => { | ||
| let result: StringArray = array | ||
| .as_primitive::<Int64Type>() | ||
| .iter() | ||
| .map(|opt| opt.map(spark_bin)) | ||
| .collect(); | ||
| Ok(Arc::new(result)) | ||
| } | ||
| DataType::Float16 => { | ||
| let result: StringArray = array | ||
| .as_primitive::<Float16Type>() | ||
| .iter() | ||
| .map(|opt| opt.map(|value| spark_bin(value.to_i64().unwrap()))) | ||
| .collect(); | ||
| Ok(Arc::new(result)) | ||
| } | ||
| DataType::Float32 => { | ||
| let result: StringArray = array | ||
| .as_primitive::<Float32Type>() | ||
| .iter() | ||
| .map(|opt| opt.map(|value| spark_bin(value.to_i64().unwrap()))) | ||
| .collect(); | ||
| Ok(Arc::new(result)) | ||
| } | ||
| DataType::Float64 => { | ||
| let result: StringArray = array | ||
| .as_primitive::<Float64Type>() | ||
| .iter() | ||
| .map(|opt| opt.map(|value| spark_bin(value.to_i64().unwrap()))) | ||
| .collect(); | ||
| Ok(Arc::new(result)) | ||
| } | ||
| DataType::Decimal32(_, _) => { | ||
| let result: StringArray = array | ||
| .as_primitive::<Decimal32Type>() | ||
| .iter() | ||
| .map(|opt| opt.map(|value| spark_bin(value.into()))) | ||
| .collect(); | ||
| Ok(Arc::new(result)) | ||
| } | ||
| DataType::Decimal64(_, _) => { | ||
| let result: StringArray = array | ||
| .as_primitive::<Decimal64Type>() | ||
| .iter() | ||
| .map(|opt| opt.map(spark_bin)) | ||
| .collect(); | ||
| Ok(Arc::new(result)) | ||
| } | ||
| data_type => { | ||
| internal_err!("bin does not support: {data_type}") | ||
| } | ||
| } | ||
| } | ||
|
|
||
| fn spark_bin(value: i64) -> String { | ||
| format!("{value:b}") | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -15,23 +15,62 @@ | |
| # 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 | ||
|
|
||
| ## Original Query: SELECT bin(-13); | ||
| ## PySpark 3.5.5 Result: {'bin(-13)': '1111111111111111111111111111111111111111111111111111111111110011', 'typeof(bin(-13))': 'string', 'typeof(-13)': 'int'} | ||
| #query | ||
| #SELECT bin(-13::int); | ||
|
|
||
| ## Original Query: SELECT bin(13); | ||
| ## PySpark 3.5.5 Result: {'bin(13)': '1101', 'typeof(bin(13))': 'string', 'typeof(13)': 'int'} | ||
| #query | ||
| #SELECT bin(13::int); | ||
|
|
||
| ## Original Query: SELECT bin(13.3); | ||
| ## PySpark 3.5.5 Result: {'bin(13.3)': '1101', 'typeof(bin(13.3))': 'string', 'typeof(13.3)': 'decimal(3,1)'} | ||
| #query | ||
| #SELECT bin(13.3::decimal(3,1)); | ||
| query T | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We should try to add some null handling test cases + handling actual table columns |
||
| SELECT bin(arrow_cast(NULL, 'Int8')); | ||
| ---- | ||
| NULL | ||
|
|
||
| query T | ||
| SELECT bin(arrow_cast(0, 'Int8')); | ||
| ---- | ||
| 0 | ||
|
|
||
| query T | ||
| SELECT bin(arrow_cast(13, 'Int8')); | ||
| ---- | ||
| 1101 | ||
|
|
||
| query T | ||
| SELECT bin(arrow_cast(13.36, 'Float16')); | ||
| ---- | ||
| 1101 | ||
|
|
||
| query T | ||
| SELECT bin(13.3::decimal(3,1)); | ||
| ---- | ||
| 1101 | ||
|
|
||
| query T | ||
| SELECT bin(arrow_cast(-13, 'Int8')); | ||
| ---- | ||
| 1111111111111111111111111111111111111111111111111111111111110011 | ||
|
|
||
| query T | ||
| SELECT bin(arrow_cast(256, 'Int16')); | ||
| ---- | ||
| 100000000 | ||
|
|
||
| query T | ||
| SELECT bin(arrow_cast(-32768, 'Int16')); | ||
| ---- | ||
| 1111111111111111111111111111111111111111111111111000000000000000 | ||
|
|
||
| query T | ||
| SELECT bin(arrow_cast(-2147483648, 'Int32')); | ||
| ---- | ||
| 1111111111111111111111111111111110000000000000000000000000000000 | ||
|
|
||
| query T | ||
| SELECT bin(arrow_cast(1073741824, 'Int32')); | ||
| ---- | ||
| 1000000000000000000000000000000 | ||
|
|
||
| query T | ||
| SELECT bin(arrow_cast(-9223372036854775808, 'Int64')); | ||
| ---- | ||
| 1000000000000000000000000000000000000000000000000000000000000000 | ||
|
|
||
| query T | ||
| SELECT bin(arrow_cast(9223372036854775807, 'Int64')); | ||
| ---- | ||
| 111111111111111111111111111111111111111111111111111111111111111 | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Spark supports decimal, we should add this support to this PR as well