-
Notifications
You must be signed in to change notification settings - Fork 1.8k
feat: DISTINCT bitwise and boolean aggregate functions
#6581
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
Merged
alamb
merged 3 commits into
apache:main
from
izveigor:bitwise_boolean_distinct_aggregate_functions
Jun 9, 2023
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
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
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
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 |
|---|---|---|
|
|
@@ -17,6 +17,7 @@ | |
|
|
||
| //! Defines physical expressions that can evaluated at runtime during query execution | ||
|
|
||
| use ahash::RandomState; | ||
| use std::any::Any; | ||
| use std::convert::TryFrom; | ||
| use std::sync::Arc; | ||
|
|
@@ -32,6 +33,7 @@ use arrow::{ | |
| }; | ||
| use datafusion_common::{downcast_value, DataFusionError, Result, ScalarValue}; | ||
| use datafusion_expr::Accumulator; | ||
| use std::collections::HashSet; | ||
|
|
||
| use crate::aggregate::row_accumulator::{ | ||
| is_row_accumulator_support_dtype, RowAccumulator, | ||
|
|
@@ -751,6 +753,170 @@ impl RowAccumulator for BitXorRowAccumulator { | |
| } | ||
| } | ||
|
|
||
| /// Expression for a BIT_XOR(DISTINCT) aggregation. | ||
| #[derive(Debug, Clone)] | ||
| pub struct DistinctBitXor { | ||
|
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. I wonder if it is possible to avoid duplicated code for distinct aggregates -- they are all basically doing the same thing 🤔 |
||
| name: String, | ||
| pub data_type: DataType, | ||
| expr: Arc<dyn PhysicalExpr>, | ||
| nullable: bool, | ||
| } | ||
|
|
||
| impl DistinctBitXor { | ||
| /// Create a new DistinctBitXor aggregate function | ||
| pub fn new( | ||
| expr: Arc<dyn PhysicalExpr>, | ||
| name: impl Into<String>, | ||
| data_type: DataType, | ||
| ) -> Self { | ||
| Self { | ||
| name: name.into(), | ||
| expr, | ||
| data_type, | ||
| nullable: true, | ||
| } | ||
| } | ||
| } | ||
|
|
||
| impl AggregateExpr for DistinctBitXor { | ||
| /// Return a reference to Any that can be used for downcasting | ||
| fn as_any(&self) -> &dyn Any { | ||
| self | ||
| } | ||
|
|
||
| fn field(&self) -> Result<Field> { | ||
| Ok(Field::new( | ||
| &self.name, | ||
| self.data_type.clone(), | ||
| self.nullable, | ||
| )) | ||
| } | ||
|
|
||
| fn create_accumulator(&self) -> Result<Box<dyn Accumulator>> { | ||
| Ok(Box::new(DistinctBitXorAccumulator::try_new( | ||
| &self.data_type, | ||
| )?)) | ||
| } | ||
|
|
||
| fn state_fields(&self) -> Result<Vec<Field>> { | ||
| // State field is a List which stores items to rebuild hash set. | ||
| Ok(vec![Field::new_list( | ||
| format_state_name(&self.name, "bit_xor distinct"), | ||
| Field::new("item", self.data_type.clone(), true), | ||
| false, | ||
| )]) | ||
| } | ||
|
|
||
| fn expressions(&self) -> Vec<Arc<dyn PhysicalExpr>> { | ||
| vec![self.expr.clone()] | ||
| } | ||
|
|
||
| fn name(&self) -> &str { | ||
| &self.name | ||
| } | ||
| } | ||
|
|
||
| impl PartialEq<dyn Any> for DistinctBitXor { | ||
| fn eq(&self, other: &dyn Any) -> bool { | ||
| down_cast_any_ref(other) | ||
| .downcast_ref::<Self>() | ||
| .map(|x| { | ||
| self.name == x.name | ||
| && self.data_type == x.data_type | ||
| && self.nullable == x.nullable | ||
| && self.expr.eq(&x.expr) | ||
| }) | ||
| .unwrap_or(false) | ||
| } | ||
| } | ||
|
|
||
| #[derive(Debug)] | ||
| struct DistinctBitXorAccumulator { | ||
| hash_values: HashSet<ScalarValue, RandomState>, | ||
| data_type: DataType, | ||
| } | ||
|
|
||
| impl DistinctBitXorAccumulator { | ||
| pub fn try_new(data_type: &DataType) -> Result<Self> { | ||
| Ok(Self { | ||
| hash_values: HashSet::default(), | ||
| data_type: data_type.clone(), | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| impl Accumulator for DistinctBitXorAccumulator { | ||
| fn state(&self) -> Result<Vec<ScalarValue>> { | ||
| // 1. Stores aggregate state in `ScalarValue::List` | ||
| // 2. Constructs `ScalarValue::List` state from distinct numeric stored in hash set | ||
| let state_out = { | ||
| let mut distinct_values = Vec::new(); | ||
| self.hash_values | ||
| .iter() | ||
| .for_each(|distinct_value| distinct_values.push(distinct_value.clone())); | ||
| vec![ScalarValue::new_list( | ||
| Some(distinct_values), | ||
| self.data_type.clone(), | ||
| )] | ||
| }; | ||
| Ok(state_out) | ||
| } | ||
|
|
||
| fn update_batch(&mut self, values: &[ArrayRef]) -> Result<()> { | ||
| if values.is_empty() { | ||
| return Ok(()); | ||
| } | ||
|
|
||
| let arr = &values[0]; | ||
| (0..values[0].len()).try_for_each(|index| { | ||
| if !arr.is_null(index) { | ||
| let v = ScalarValue::try_from_array(arr, index)?; | ||
| self.hash_values.insert(v); | ||
| } | ||
| Ok(()) | ||
| }) | ||
| } | ||
|
|
||
| fn merge_batch(&mut self, states: &[ArrayRef]) -> Result<()> { | ||
| if states.is_empty() { | ||
| return Ok(()); | ||
| } | ||
|
|
||
| let arr = &states[0]; | ||
| (0..arr.len()).try_for_each(|index| { | ||
| let scalar = ScalarValue::try_from_array(arr, index)?; | ||
|
|
||
| if let ScalarValue::List(Some(scalar), _) = scalar { | ||
| scalar.iter().for_each(|scalar| { | ||
| if !ScalarValue::is_null(scalar) { | ||
| self.hash_values.insert(scalar.clone()); | ||
| } | ||
| }); | ||
| } else { | ||
| return Err(DataFusionError::Internal( | ||
| "Unexpected accumulator state".into(), | ||
| )); | ||
| } | ||
| Ok(()) | ||
| }) | ||
| } | ||
|
|
||
| fn evaluate(&self) -> Result<ScalarValue> { | ||
| let mut bit_xor_value = ScalarValue::try_from(&self.data_type)?; | ||
| for distinct_value in self.hash_values.iter() { | ||
| bit_xor_value = bit_xor_value.bitxor(distinct_value)?; | ||
| } | ||
| Ok(bit_xor_value) | ||
| } | ||
|
|
||
| fn size(&self) -> usize { | ||
| std::mem::size_of_val(self) + ScalarValue::size_of_hashset(&self.hash_values) | ||
| - std::mem::size_of_val(&self.hash_values) | ||
| + self.data_type.size() | ||
| - std::mem::size_of_val(&self.data_type) | ||
| } | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
|
|
@@ -813,15 +979,20 @@ mod tests { | |
|
|
||
| #[test] | ||
| fn bit_xor_i32() -> Result<()> { | ||
| let a: ArrayRef = Arc::new(Int32Array::from(vec![4, 7, 15])); | ||
| generic_test_op!(a, DataType::Int32, BitXor, ScalarValue::from(12i32)) | ||
| let a: ArrayRef = Arc::new(Int32Array::from(vec![4, 7, 4, 7, 15])); | ||
| generic_test_op!(a, DataType::Int32, BitXor, ScalarValue::from(15i32)) | ||
| } | ||
|
|
||
| #[test] | ||
| fn bit_xor_i32_with_nulls() -> Result<()> { | ||
| let a: ArrayRef = | ||
| Arc::new(Int32Array::from(vec![Some(1), None, Some(3), Some(5)])); | ||
| generic_test_op!(a, DataType::Int32, BitXor, ScalarValue::from(7i32)) | ||
| let a: ArrayRef = Arc::new(Int32Array::from(vec![ | ||
| Some(1), | ||
| Some(1), | ||
| None, | ||
| Some(3), | ||
| Some(5), | ||
| ])); | ||
| generic_test_op!(a, DataType::Int32, BitXor, ScalarValue::from(6i32)) | ||
| } | ||
|
|
||
| #[test] | ||
|
|
@@ -832,7 +1003,44 @@ mod tests { | |
|
|
||
| #[test] | ||
| fn bit_xor_u32() -> Result<()> { | ||
| let a: ArrayRef = Arc::new(UInt32Array::from(vec![4_u32, 7_u32, 15_u32])); | ||
| generic_test_op!(a, DataType::UInt32, BitXor, ScalarValue::from(12u32)) | ||
| let a: ArrayRef = | ||
| Arc::new(UInt32Array::from(vec![4_u32, 7_u32, 4_u32, 7_u32, 15_u32])); | ||
| generic_test_op!(a, DataType::UInt32, BitXor, ScalarValue::from(15u32)) | ||
| } | ||
|
|
||
| #[test] | ||
| fn bit_xor_distinct_i32() -> Result<()> { | ||
| let a: ArrayRef = Arc::new(Int32Array::from(vec![4, 7, 4, 7, 15])); | ||
| generic_test_op!(a, DataType::Int32, DistinctBitXor, ScalarValue::from(12i32)) | ||
| } | ||
|
|
||
| #[test] | ||
| fn bit_xor_distinct_i32_with_nulls() -> Result<()> { | ||
| let a: ArrayRef = Arc::new(Int32Array::from(vec![ | ||
| Some(1), | ||
| Some(1), | ||
| None, | ||
| Some(3), | ||
| Some(5), | ||
| ])); | ||
| generic_test_op!(a, DataType::Int32, DistinctBitXor, ScalarValue::from(7i32)) | ||
| } | ||
|
|
||
| #[test] | ||
| fn bit_xor_distinct_i32_all_nulls() -> Result<()> { | ||
| let a: ArrayRef = Arc::new(Int32Array::from(vec![None, None])); | ||
| generic_test_op!(a, DataType::Int32, DistinctBitXor, ScalarValue::Int32(None)) | ||
| } | ||
|
|
||
| #[test] | ||
| fn bit_xor_distinct_u32() -> Result<()> { | ||
| let a: ArrayRef = | ||
| Arc::new(UInt32Array::from(vec![4_u32, 7_u32, 4_u32, 7_u32, 15_u32])); | ||
| generic_test_op!( | ||
| a, | ||
| DataType::UInt32, | ||
| DistinctBitXor, | ||
| ScalarValue::from(12u32) | ||
| ) | ||
| } | ||
| } | ||
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
Oops, something went wrong.
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.
even though, as you note,
BIT_AND(DISTINCT), BIT_OR(DISTINCT), BOOL_AND(DISTINCT) and BOOL_OR(DISTINCT)are the same as their non distinct versions, I think we should still add SQL coverage so that we don't accidentally break the feature during some future refactoring