-
Notifications
You must be signed in to change notification settings - Fork 1.2k
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
#554: Lead/lag window function with offset and default value arguments #687
Merged
Merged
Changes from all commits
Commits
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 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 |
---|---|---|
|
@@ -21,11 +21,13 @@ | |
use crate::error::{DataFusionError, Result}; | ||
use crate::physical_plan::window_functions::PartitionEvaluator; | ||
use crate::physical_plan::{window_functions::BuiltInWindowFunctionExpr, PhysicalExpr}; | ||
use crate::scalar::ScalarValue; | ||
use arrow::array::ArrayRef; | ||
use arrow::compute::kernels::window::shift; | ||
use arrow::compute::cast; | ||
use arrow::datatypes::{DataType, Field}; | ||
use arrow::record_batch::RecordBatch; | ||
use std::any::Any; | ||
use std::ops::Neg; | ||
use std::ops::Range; | ||
use std::sync::Arc; | ||
|
||
|
@@ -36,19 +38,23 @@ pub struct WindowShift { | |
data_type: DataType, | ||
shift_offset: i64, | ||
expr: Arc<dyn PhysicalExpr>, | ||
default_value: Option<ScalarValue>, | ||
} | ||
|
||
/// lead() window function | ||
pub fn lead( | ||
name: String, | ||
data_type: DataType, | ||
expr: Arc<dyn PhysicalExpr>, | ||
shift_offset: Option<i64>, | ||
default_value: Option<ScalarValue>, | ||
) -> WindowShift { | ||
WindowShift { | ||
name, | ||
data_type, | ||
shift_offset: -1, | ||
shift_offset: shift_offset.map(|v| v.neg()).unwrap_or(-1), | ||
expr, | ||
default_value, | ||
} | ||
} | ||
|
||
|
@@ -57,12 +63,15 @@ pub fn lag( | |
name: String, | ||
data_type: DataType, | ||
expr: Arc<dyn PhysicalExpr>, | ||
shift_offset: Option<i64>, | ||
default_value: Option<ScalarValue>, | ||
) -> WindowShift { | ||
WindowShift { | ||
name, | ||
data_type, | ||
shift_offset: 1, | ||
shift_offset: shift_offset.unwrap_or(1), | ||
expr, | ||
default_value, | ||
} | ||
} | ||
|
||
|
@@ -98,20 +107,71 @@ impl BuiltInWindowFunctionExpr for WindowShift { | |
Ok(Box::new(WindowShiftEvaluator { | ||
shift_offset: self.shift_offset, | ||
values, | ||
default_value: self.default_value.clone(), | ||
})) | ||
} | ||
} | ||
|
||
pub(crate) struct WindowShiftEvaluator { | ||
shift_offset: i64, | ||
values: Vec<ArrayRef>, | ||
default_value: Option<ScalarValue>, | ||
} | ||
|
||
fn create_empty_array( | ||
value: &Option<ScalarValue>, | ||
data_type: &DataType, | ||
size: usize, | ||
) -> Result<ArrayRef> { | ||
use arrow::array::new_null_array; | ||
let array = value | ||
.as_ref() | ||
.map(|scalar| scalar.to_array_of_size(size)) | ||
.unwrap_or_else(|| new_null_array(data_type, size)); | ||
if array.data_type() != data_type { | ||
cast(&array, data_type).map_err(DataFusionError::ArrowError) | ||
} else { | ||
Ok(array) | ||
} | ||
} | ||
|
||
// TODO: change the original arrow::compute::kernels::window::shift impl to support an optional default value | ||
fn shift_with_default_value( | ||
array: &ArrayRef, | ||
offset: i64, | ||
value: &Option<ScalarValue>, | ||
) -> Result<ArrayRef> { | ||
use arrow::compute::concat; | ||
|
||
let value_len = array.len() as i64; | ||
if offset == 0 { | ||
Ok(arrow::array::make_array(array.data_ref().clone())) | ||
} else if offset == i64::MIN || offset.abs() >= value_len { | ||
create_empty_array(value, array.data_type(), array.len()) | ||
} else { | ||
let slice_offset = (-offset).clamp(0, value_len) as usize; | ||
let length = array.len() - offset.abs() as usize; | ||
let slice = array.slice(slice_offset, length); | ||
|
||
// Generate array with remaining `null` items | ||
let nulls = offset.abs() as usize; | ||
let default_values = create_empty_array(value, slice.data_type(), nulls)?; | ||
// Concatenate both arrays, add nulls after if shift > 0 else before | ||
if offset > 0 { | ||
concat(&[default_values.as_ref(), slice.as_ref()]) | ||
.map_err(DataFusionError::ArrowError) | ||
} else { | ||
concat(&[slice.as_ref(), default_values.as_ref()]) | ||
.map_err(DataFusionError::ArrowError) | ||
} | ||
} | ||
} | ||
|
||
impl PartitionEvaluator for WindowShiftEvaluator { | ||
fn evaluate_partition(&self, partition: Range<usize>) -> Result<ArrayRef> { | ||
let value = &self.values[0]; | ||
let value = value.slice(partition.start, partition.end - partition.start); | ||
shift(value.as_ref(), self.shift_offset).map_err(DataFusionError::ArrowError) | ||
shift_with_default_value(&value, self.shift_offset, &self.default_value) | ||
} | ||
} | ||
|
||
|
@@ -142,6 +202,8 @@ mod tests { | |
"lead".to_owned(), | ||
DataType::Float32, | ||
Arc::new(Column::new("c3", 0)), | ||
None, | ||
None, | ||
), | ||
vec![ | ||
Some(-2), | ||
|
@@ -162,6 +224,8 @@ mod tests { | |
"lead".to_owned(), | ||
DataType::Float32, | ||
Arc::new(Column::new("c3", 0)), | ||
None, | ||
None, | ||
), | ||
vec![ | ||
None, | ||
|
@@ -176,6 +240,28 @@ mod tests { | |
.iter() | ||
.collect::<Int32Array>(), | ||
)?; | ||
|
||
test_i32_result( | ||
lag( | ||
"lead".to_owned(), | ||
DataType::Int32, | ||
Arc::new(Column::new("c3", 0)), | ||
None, | ||
Some(ScalarValue::Int32(Some(100))), | ||
), | ||
vec![ | ||
Some(100), | ||
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. 👍 |
||
Some(1), | ||
Some(-2), | ||
Some(3), | ||
Some(-4), | ||
Some(5), | ||
Some(-6), | ||
Some(7), | ||
] | ||
.iter() | ||
.collect::<Int32Array>(), | ||
)?; | ||
Ok(()) | ||
} | ||
} |
This file contains 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 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 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
27 changes: 27 additions & 0 deletions
27
integration-tests/sqls/simple_window_lead_built_in_functions.sql
This file contains 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,27 @@ | ||
-- 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. | ||
|
||
SELECT | ||
c8, | ||
LEAD(c8) OVER () next_c8, | ||
LEAD(c8, 10, 10) OVER() next_10_c8, | ||
LEAD(c8, 100, 10) OVER() next_out_of_bounds_c8, | ||
LAG(c8) OVER() prev_c8, | ||
LAG(c8, -2, 0) OVER() AS prev_2_c8, | ||
LAG(c8, -200, 10) OVER() AS prev_out_of_bounds_c8 | ||
|
||
FROM test | ||
ORDER BY c8; |
This file contains 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
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.
you can add a comment of todo to push this upstream to arrow-rs
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.
Added a TODO comment