Skip to content

Apache DataFusion SQL Query Engine

Unordered PARTITION BY column implementation (to prevent pipeline breaking) (#6036)

Mustafa Akur729586258fe6
diff --git a/datafusion/common/src/utils.rs b/datafusion/common/src/utils.rs
index e29fd7e021..5ed2ff121b 100644
--- a/datafusion/common/src/utils.rs
+++ b/datafusion/common/src/utils.rs
@@ -18,11 +18,11 @@
//! This module provides the bisect function, which implements binary search.
use crate::{DataFusionError, Result, ScalarValue};
-use arrow::array::ArrayRef;
+use arrow::array::{ArrayRef, PrimitiveArray};
use arrow::compute;
use arrow::compute::{lexicographical_partition_ranges, SortColumn, SortOptions};
-use arrow_array::types::UInt32Type;
-use arrow_array::PrimitiveArray;
+use arrow::datatypes::UInt32Type;
+use arrow::record_batch::RecordBatch;
use sqlparser::ast::Ident;
use sqlparser::dialect::GenericDialect;
use sqlparser::parser::{Parser, ParserError};
@@ -39,6 +39,16 @@ pub fn get_row_at_idx(columns: &[ArrayRef], idx: usize) -> Result<Vec<ScalarValu
.collect()
}
+/// Construct a new RecordBatch from the rows of the `record_batch` at the `indices`.
+pub fn get_record_batch_at_indices(
+ record_batch: &RecordBatch,
+ indices: &PrimitiveArray<UInt32Type>,
+) -> Result<RecordBatch> {
+ let new_columns = get_arrayref_at_indices(record_batch.columns(), indices)?;
+ RecordBatch::try_new(record_batch.schema(), new_columns)
+ .map_err(DataFusionError::ArrowError)
+}
+
/// This function compares two tuples depending on the given sort options.
pub fn compare_rows(
x: &[ScalarValue],
diff --git a/datafusion/core/src/physical_optimizer/pipeline_fixer.rs b/datafusion/core/src/physical_optimizer/pipeline_fixer.rs
index 77ffb9fb41..7a55aa607f 100644
--- a/datafusion/core/src/physical_optimizer/pipeline_fixer.rs
+++ b/datafusion/core/src/physical_optimizer/pipeline_fixer.rs
@@ -61,16 +61,11 @@ impl PhysicalOptimizerRule for PipelineFixer {
_config: &ConfigOptions,
) -> Result<Arc<dyn ExecutionPlan>> {
let pipeline = PipelineStatePropagator::new(plan);
- let physical_optimizer_subrules: Vec<Box<PipelineFixerSubrule>> = vec![
+ let subrules: Vec<Box<PipelineFixerSubrule>> = vec![
Box::new(hash_join_convert_symmetric_subrule),
Box::new(hash_join_swap_subrule),
];
- let state = pipeline.transform_up(&|p| {
- apply_subrules_and_check_finiteness_requirements(
- p,
- &physical_optimizer_subrules,
- )
- })?;
+ let state = pipeline.transform_up(&|p| apply_subrules(p, &subrules))?;
Ok(state.plan)
}
@@ -88,13 +83,13 @@ impl PhysicalOptimizerRule for PipelineFixer {
/// question. If possible, it makes this replacement; otherwise, it has no
/// effect.
fn hash_join_convert_symmetric_subrule(
- input: PipelineStatePropagator,
+ mut input: PipelineStatePropagator,
) -> Option<Result<PipelineStatePropagator>> {
- let plan = input.plan;
- if let Some(hash_join) = plan.as_any().downcast_ref::<HashJoinExec>() {
- let ub_flags = input.children_unbounded;
+ if let Some(hash_join) = input.plan.as_any().downcast_ref::<HashJoinExec>() {
+ let ub_flags = &input.children_unbounded;
let (left_unbounded, right_unbounded) = (ub_flags[0], ub_flags[1]);
- let new_plan = if left_unbounded && right_unbounded {
+ input.unbounded = left_unbounded || right_unbounded;
+ let result = if left_unbounded && right_unbounded {
SymmetricHashJoinExec::try_new(
hash_join.left().clone(),
hash_join.right().clone(),
@@ -107,15 +102,14 @@ fn hash_join_convert_symmetric_subrule(
hash_join.join_type(),
hash_join.null_equals_null(),
)
- .map(|e| Arc::new(e) as _)
+ .map(|exec| {
+ input.plan = Arc::new(exec) as _;
+ input
+ })
} else {
- Ok(plan)
+ Ok(input)
};
- Some(new_plan.map(|plan| PipelineStatePropagator {
- plan,
- unbounded: left_unbounded || right_unbounded,
- children_unbounded: ub_flags,
- }))
+ Some(result)
} else {
None
}
@@ -163,32 +157,29 @@ fn hash_join_convert_symmetric_subrule(
///
/// ```
fn hash_join_swap_subrule(
- input: PipelineStatePropagator,
+ mut input: PipelineStatePropagator,
) -> Option<Result<PipelineStatePropagator>> {
- let plan = input.plan;
- if let Some(hash_join) = plan.as_any().downcast_ref::<HashJoinExec>() {
- let ub_flags = input.children_unbounded;
+ if let Some(hash_join) = input.plan.as_any().downcast_ref::<HashJoinExec>() {
+ let ub_flags = &input.children_unbounded;
let (left_unbounded, right_unbounded) = (ub_flags[0], ub_flags[1]);
- let new_plan = if left_unbounded && !right_unbounded {
- if matches!(
+ input.unbounded = left_unbounded || right_unbounded;
+ let result = if left_unbounded
+ && !right_unbounded
+ && matches!(
*hash_join.join_type(),
JoinType::Inner
| JoinType::Left
| JoinType::LeftSemi
| JoinType::LeftAnti
) {
- swap(hash_join)
- } else {
- Ok(plan)
- }
+ swap(hash_join).map(|plan| {
+ input.plan = plan;
+ input
+ })
} else {
- Ok(plan)
+ Ok(input)
};
- Some(new_plan.map(|plan| PipelineStatePropagator {
- plan,
- unbounded: left_unbounded || right_unbounded,
- children_unbounded: ub_flags,
- }))
+ Some(result)
} else {
None
}
@@ -220,22 +211,24 @@ fn swap(hash_join: &HashJoinExec) -> Result<Arc<dyn ExecutionPlan>> {
}
}
-fn apply_subrules_and_check_finiteness_requirements(
+fn apply_subrules(
mut input: PipelineStatePropagator,
- physical_optimizer_subrules: &Vec<Box<PipelineFixerSubrule>>,
+ subrules: &Vec<Box<PipelineFixerSubrule>>,
) -> Result<Transformed<PipelineStatePropagator>> {
- for sub_rule in physical_optimizer_subrules {
- if let Some(value) = sub_rule(input.clone()).transpose()? {
+ for subrule in subrules {
+ if let Some(value) = subrule(input.clone()).transpose()? {
input = value;
}
}
let is_unbounded = input
.plan
.unbounded_output(&input.children_unbounded)
- // Treat the cases where executor cannot be run on unbounded data
- // as generating unbounded data. These executors may be fixed during optimization
- // (Sort will be removed, Window will be swapped etc.), If cannot
- // be fixed Pipeline checker will generate error anyway.
+ // Treat the case where an operator can not run on unbounded data as
+ // if it can and it outputs unbounded data. Do not raise an error yet.
+ // Such operators may be fixed, adjusted or replaced later on during
+ // optimization passes -- sorts may be removed, windows may be adjusted
+ // etc. If this doesn't happen, the final `PipelineChecker` rule will
+ // catch this and raise an error anyway.
.unwrap_or(true);
input.unbounded = is_unbounded;
Ok(Transformed::Yes(input))
diff --git a/datafusion/core/src/physical_optimizer/sort_enforcement.rs b/datafusion/core/src/physical_optimizer/sort_enforcement.rs
index 20f67d7021..8bb71445a4 100644
--- a/datafusion/core/src/physical_optimizer/sort_enforcement.rs
+++ b/datafusion/core/src/physical_optimizer/sort_enforcement.rs
@@ -46,7 +46,9 @@ use crate::physical_optimizer::PhysicalOptimizerRule;
use crate::physical_plan::coalesce_partitions::CoalescePartitionsExec;
use crate::physical_plan::sorts::sort::SortExec;
use crate::physical_plan::sorts::sort_preserving_merge::SortPreservingMergeExec;
-use crate::physical_plan::windows::{BoundedWindowAggExec, WindowAggExec};
+use crate::physical_plan::windows::{
+ BoundedWindowAggExec, PartitionSearchMode, WindowAggExec,
+};
use crate::physical_plan::{with_new_children_if_necessary, Distribution, ExecutionPlan};
use arrow::datatypes::SchemaRef;
use datafusion_common::tree_node::{Transformed, TreeNode, VisitRecursion};
@@ -57,7 +59,7 @@ use datafusion_physical_expr::utils::{
ordering_satisfy_requirement_concrete,
};
use datafusion_physical_expr::{PhysicalExpr, PhysicalSortExpr, PhysicalSortRequirement};
-use itertools::{concat, izip};
+use itertools::{concat, izip, Itertools};
use std::sync::Arc;
/// This rule inspects [`SortExec`]'s in the given physical plan and removes the
@@ -589,27 +591,44 @@ fn analyze_window_sort_removal(
"Expects to receive either WindowAggExec of BoundedWindowAggExec".to_string(),
));
};
-
- let mut needs_reverse = None;
+ let partitionby_exprs = window_expr[0].partition_by();
+ let orderby_sort_keys = window_expr[0].order_by();
+
+ // search_flags stores return value of the can_skip_sort.
+ // `None` case represents `SortExec` cannot be removed.
+ // `PartitionSearch` mode stores at which mode executor should work to remove
+ // `SortExec` before it,
+ // `bool` stores whether or not we need to reverse window expressions to remove `SortExec`.
+ let mut search_flags = None;
for sort_any in sort_tree.get_leaves() {
// Variable `sort_any` will either be a `SortExec` or a
// `SortPreservingMergeExec`, and both have a single child.
// Therefore, we can use the 0th index without loss of generality.
- let sort_input = sort_any.children()[0].clone();
- if let Some(should_reverse) = can_skip_sort(
- window_expr[0].partition_by(),
- window_expr[0].order_by(),
- &sort_input,
- )? {
- if should_reverse == *needs_reverse.get_or_insert(should_reverse) {
- continue;
- }
+ let sort_input = &sort_any.children()[0];
+ let flags = can_skip_sort(partitionby_exprs, orderby_sort_keys, sort_input)?;
+ if flags.is_some() && (search_flags.is_none() || search_flags == flags) {
+ search_flags = flags;
+ continue;
}
// We can not skip the sort, or window reversal requirements are not
// uniform; then sort removal is not possible -- we immediately return.
return Ok(None);
}
- let new_window_expr = if needs_reverse.unwrap() {
+ let (should_reverse, partition_search_mode) = if let Some(search_flags) = search_flags
+ {
+ search_flags
+ } else {
+ // We can not skip the sort return:
+ return Ok(None);
+ };
+ let is_unbounded = unbounded_output(window_exec);
+ if !is_unbounded && partition_search_mode != PartitionSearchMode::Sorted {
+ // Executor has bounded input and `partition_search_mode` is not `PartitionSearchMode::Sorted`
+ // in this case removing the sort is not helpful, return:
+ return Ok(None);
+ };
+
+ let new_window_expr = if should_reverse {
window_expr
.iter()
.map(|e| e.get_reverse_expr())
@@ -622,7 +641,7 @@ fn analyze_window_sort_removal(
window_exec.required_input_distribution()[sort_tree.idx],
Distribution::SinglePartition
);
- let new_child = remove_corresponding_sort_from_sub_plan(
+ let mut new_child = remove_corresponding_sort_from_sub_plan(
sort_tree,
requires_single_partition,
)?;
@@ -637,8 +656,21 @@ fn analyze_window_sort_removal(
new_child,
new_schema,
partition_keys.to_vec(),
+ partition_search_mode,
)?) as _
} else {
+ if partition_search_mode != PartitionSearchMode::Sorted {
+ // For `WindowAggExec` to work correctly PARTITION BY columns should be sorted.
+ // Hence, if `partition_search_mode` is not `PartitionSearchMode::Sorted` we should convert
+ // input ordering such that it can work with PartitionSearchMode::Sorted (add `SortExec`).
+ // Effectively `WindowAggExec` works only in PartitionSearchMode::Sorted mode.
+ let reqs = window_exec
+ .required_input_ordering()
+ .swap_remove(0)
+ .unwrap_or(vec![]);
+ let sort_expr = PhysicalSortRequirement::to_sort_exprs(reqs);
+ add_sort_above(&mut new_child, sort_expr)?;
+ };
Arc::new(WindowAggExec::try_new(
window_expr,
new_child,
@@ -767,16 +799,20 @@ fn get_sort_exprs(sort_any: &Arc<dyn ExecutionPlan>) -> Result<&[PhysicalSortExp
}
}
-/// Compares physical ordering and required ordering of all [`PhysicalSortExpr`]s
-/// to decide whether a [`SortExec`] before a [`WindowAggExec`] can be removed.
-/// A `None` return value indicates that we can remove the sort in question.
-/// A `Some(bool)` value indicates otherwise, and signals whether we need to
-/// reverse the ordering in order to remove the sort in question.
+/// Compares physical ordering (output ordering of input executor) with
+/// `partitionby_exprs` and `orderby_keys`
+/// to decide whether existing ordering is sufficient to run current window executor.
+/// A `None` return value indicates that we can not remove the sort in question (input ordering is not
+/// sufficient to run current window executor).
+/// A `Some((bool, PartitionSearchMode))` value indicates window executor can be run with existing input ordering
+/// (Hence we can remove [`SortExec`] before it).
+/// `bool` represents whether we should reverse window executor to remove [`SortExec`] before it.
+/// `PartitionSearchMode` represents, in which mode Window Executor should work with existing ordering.
fn can_skip_sort(
partitionby_exprs: &[Arc<dyn PhysicalExpr>],
orderby_keys: &[PhysicalSortExpr],
input: &Arc<dyn ExecutionPlan>,
-) -> Result<Option<bool>> {
+) -> Result<Option<(bool, PartitionSearchMode)>> {
let physical_ordering = if let Some(physical_ordering) = input.output_ordering() {
physical_ordering
} else {
@@ -793,14 +829,13 @@ fn can_skip_sort(
&physical_ordering_exprs,
equal_properties,
);
- let contains_all_orderbys = ob_indices.len() == orderby_exprs.len();
- if !contains_all_orderbys {
- // If all order by expressions are not in the input ordering. There is no way to remove a sort
- // immediately return
+ if ob_indices.len() != orderby_exprs.len() {
+ // If all order by expressions are not in the input ordering,
+ // there is no way to remove a sort -- immediately return:
return Ok(None);
}
// indices of the partition by expressions among input ordering expressions
- let mut pb_indices = get_indices_of_matching_exprs(
+ let pb_indices = get_indices_of_matching_exprs(
partitionby_exprs,
&physical_ordering_exprs,
equal_properties,
@@ -828,7 +863,7 @@ fn can_skip_sort(
}
let input_orderby_columns = get_at_indices(physical_ordering, &unique_ob_indices)?;
let expected_orderby_columns =
- get_at_indices(orderby_keys, find_indices(&ob_indices, unique_ob_indices)?)?;
+ get_at_indices(orderby_keys, find_indices(&ob_indices, &unique_ob_indices)?)?;
let should_reverse = if let Some(should_reverse) = check_alignments(
&input.schema(),
&input_orderby_columns,
@@ -840,13 +875,28 @@ fn can_skip_sort(
return Ok(None);
};
+ let ordered_pb_indices = pb_indices.iter().copied().sorted().collect::<Vec<_>>();
// Determine how many elements in the partition by columns defines a consecutive range from zero.
- pb_indices.sort();
- let first_n = longest_consecutive_prefix(pb_indices);
- if first_n < partitionby_exprs.len() {
- return Ok(None);
- }
- Ok(Some(should_reverse))
+ let first_n = longest_consecutive_prefix(&ordered_pb_indices);
+ let mode = if first_n == partitionby_exprs.len() {
+ // All of the partition by columns defines a consecutive range from zero.
+ PartitionSearchMode::Sorted
+ } else if first_n > 0 {
+ // All of the partition by columns defines a consecutive range from zero.
+ let ordered_range = &ordered_pb_indices[0..first_n];
+ let input_pb_exprs = get_at_indices(&physical_ordering_exprs, ordered_range)?;
+ let partially_ordered_indices = get_indices_of_matching_exprs(
+ &input_pb_exprs,
+ partitionby_exprs,
+ equal_properties,
+ );
+ PartitionSearchMode::PartiallySorted(partially_ordered_indices)
+ } else {
+ // None of the partition by columns defines a consecutive range from zero.
+ PartitionSearchMode::Linear
+ };
+
+ Ok(Some((should_reverse, mode)))
}
fn check_alignments(
@@ -895,6 +945,21 @@ fn check_alignment(
})
}
+// Get unbounded_output information for the executor
+fn unbounded_output(plan: &Arc<dyn ExecutionPlan>) -> bool {
+ let res = if plan.children().is_empty() {
+ plan.unbounded_output(&[])
+ } else {
+ let children_unbounded_output = plan
+ .children()
+ .iter()
+ .map(unbounded_output)
+ .collect::<Vec<_>>();
+ plan.unbounded_output(&children_unbounded_output)
+ };
+ res.unwrap_or(true)
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -913,6 +978,9 @@ mod tests {
use crate::physical_plan::sorts::sort_preserving_merge::SortPreservingMergeExec;
use crate::physical_plan::union::UnionExec;
use crate::physical_plan::windows::create_window_expr;
+ use crate::physical_plan::windows::PartitionSearchMode::{
+ Linear, PartiallySorted, Sorted,
+ };
use crate::physical_plan::{displayable, Partitioning};
use crate::prelude::SessionContext;
use crate::test::csv_exec_sorted;
@@ -1057,61 +1125,77 @@ mod tests {
// Second field in the tuple is Vec<str> where each element in the vector represents ORDER BY columns
// For instance, vec!["c"], corresponds to ORDER BY c ASC NULLS FIRST, (ordering is default ordering. We do not check
// for reversibility in this test).
- // Third field in the tuple is Option<bool>, which corresponds to expected result for `can_skip_sort` function.
- // None represents that existing ordering is not sufficient to run executor.
+ // Third field in the tuple is Option<PartitionSearchMode>, which corresponds to expected algorithm mode.
+ // None represents that existing ordering is not sufficient to run executor with any one of the algorithms
// (We need to add SortExec to be able to run it).
- // Some(bool) represents, we can run algorithm with existing ordering. If bool is `true`. We should reverse, window expressions
- // if bool is `false`. Existing window expression can be used as is.
+ // Some(PartitionSearchMode) represents, we can run algorithm with existing ordering; and algorithm should work in
+ // PartitionSearchMode.
let test_cases = vec![
- (vec!["a"], vec!["a"], Some(false)),
- (vec!["a"], vec!["b"], Some(false)),
+ (vec!["a"], vec!["a"], Some(Sorted)),
+ (vec!["a"], vec!["b"], Some(Sorted)),
(vec!["a"], vec!["c"], None),
- (vec!["a"], vec!["a", "b"], Some(false)),
- (vec!["a"], vec!["b", "c"], Some(false)),
+ (vec!["a"], vec!["a", "b"], Some(Sorted)),
+ (vec!["a"], vec!["b", "c"], Some(Sorted)),
(vec!["a"], vec!["a", "c"], None),
- (vec!["a"], vec!["a", "b", "c"], Some(false)),
- (vec!["b"], vec!["a"], None),
+ (vec!["a"], vec!["a", "b", "c"], Some(Sorted)),
+ (vec!["b"], vec!["a"], Some(Linear)),
(vec!["b"], vec!["b"], None),
(vec!["b"], vec!["c"], None),
- (vec!["b"], vec!["a", "b"], None),
+ (vec!["b"], vec!["a", "b"], Some(Linear)),
(vec!["b"], vec!["b", "c"], None),
- (vec!["b"], vec!["a", "c"], None),
- (vec!["b"], vec!["a", "b", "c"], None),
- (vec!["c"], vec!["a"], None),
+ (vec!["b"], vec!["a", "c"], Some(Linear)),
+ (vec!["b"], vec!["a", "b", "c"], Some(Linear)),
+ (vec!["c"], vec!["a"], Some(Linear)),
(vec!["c"], vec!["b"], None),
(vec!["c"], vec!["c"], None),
- (vec!["c"], vec!["a", "b"], None),
+ (vec!["c"], vec!["a", "b"], Some(Linear)),
(vec!["c"], vec!["b", "c"], None),
- (vec!["c"], vec!["a", "c"], None),
- (vec!["c"], vec!["a", "b", "c"], None),
- (vec!["b", "a"], vec!["a"], Some(false)),
- (vec!["b", "a"], vec!["b"], Some(false)),
- (vec!["b", "a"], vec!["c"], Some(false)),
- (vec!["b", "a"], vec!["a", "b"], Some(false)),
- (vec!["b", "a"], vec!["b", "c"], Some(false)),
- (vec!["b", "a"], vec!["a", "c"], Some(false)),
- (vec!["b", "a"], vec!["a", "b", "c"], Some(false)),
- (vec!["c", "b"], vec!["a"], None),
+ (vec!["c"], vec!["a", "c"], Some(Linear)),
+ (vec!["c"], vec!["a", "b", "c"], Some(Linear)),
+ (vec!["b", "a"], vec!["a"], Some(Sorted)),
+ (vec!["b", "a"], vec!["b"], Some(Sorted)),
+ (vec!["b", "a"], vec!["c"], Some(Sorted)),
+ (vec!["b", "a"], vec!["a", "b"], Some(Sorted)),
+ (vec!["b", "a"], vec!["b", "c"], Some(Sorted)),
+ (vec!["b", "a"], vec!["a", "c"], Some(Sorted)),
+ (vec!["b", "a"], vec!["a", "b", "c"], Some(Sorted)),
+ (vec!["c", "b"], vec!["a"], Some(Linear)),
(vec!["c", "b"], vec!["b"], None),
(vec!["c", "b"], vec!["c"], None),
- (vec!["c", "b"], vec!["a", "b"], None),
+ (vec!["c", "b"], vec!["a", "b"], Some(Linear)),
(vec!["c", "b"], vec!["b", "c"], None),
- (vec!["c", "b"], vec!["a", "c"], None),
- (vec!["c", "b"], vec!["a", "b", "c"], None),
- (vec!["c", "a"], vec!["a"], None),
- (vec!["c", "a"], vec!["b"], None),
- (vec!["c", "a"], vec!["c"], None),
- (vec!["c", "a"], vec!["a", "b"], None),
- (vec!["c", "a"], vec!["b", "c"], None),
- (vec!["c", "a"], vec!["a", "c"], None),
- (vec!["c", "a"], vec!["a", "b", "c"], None),
- (vec!["c", "b", "a"], vec!["a"], Some(false)),
- (vec!["c", "b", "a"], vec!["b"], Some(false)),
- (vec!["c", "b", "a"], vec!["c"], Some(false)),
- (vec!["c", "b", "a"], vec!["a", "b"], Some(false)),
- (vec!["c", "b", "a"], vec!["b", "c"], Some(false)),
- (vec!["c", "b", "a"], vec!["a", "c"], Some(false)),
- (vec!["c", "b", "a"], vec!["a", "b", "c"], Some(false)),
+ (vec!["c", "b"], vec!["a", "c"], Some(Linear)),
+ (vec!["c", "b"], vec!["a", "b", "c"], Some(Linear)),
+ (vec!["c", "a"], vec!["a"], Some(PartiallySorted(vec![1]))),
+ (vec!["c", "a"], vec!["b"], Some(PartiallySorted(vec![1]))),
+ (vec!["c", "a"], vec!["c"], Some(PartiallySorted(vec![1]))),
+ (
+ vec!["c", "a"],
+ vec!["a", "b"],
+ Some(PartiallySorted(vec![1])),
+ ),
+ (
+ vec!["c", "a"],
+ vec!["b", "c"],
+ Some(PartiallySorted(vec![1])),
+ ),
+ (
+ vec!["c", "a"],
+ vec!["a", "c"],
+ Some(PartiallySorted(vec![1])),
+ ),
+ (
+ vec!["c", "a"],
+ vec!["a", "b", "c"],
+ Some(PartiallySorted(vec![1])),
+ ),
+ (vec!["c", "b", "a"], vec!["a"], Some(Sorted)),
+ (vec!["c", "b", "a"], vec!["b"], Some(Sorted)),
+ (vec!["c", "b", "a"], vec!["c"], Some(Sorted)),
+ (vec!["c", "b", "a"], vec!["a", "b"], Some(Sorted)),
+ (vec!["c", "b", "a"], vec!["b", "c"], Some(Sorted)),
+ (vec!["c", "b", "a"], vec!["a", "c"], Some(Sorted)),
+ (vec!["c", "b", "a"], vec!["a", "b", "c"], Some(Sorted)),
];
for (case_idx, test_case) in test_cases.iter().enumerate() {
let (partition_by_columns, order_by_params, expected) = &test_case;
@@ -1130,6 +1214,8 @@ mod tests {
}
let res =
can_skip_sort(&partition_by_exprs, &order_by_exprs, &exec_unbounded)?;
+ // Since reversibility is not important in this test. Convert Option<(bool, PartitionSearchMode)> to Option<PartitionSearchMode>
+ let res = res.map(|(_, mode)| mode);
assert_eq!(
res, *expected,
"Unexpected result for in unbounded test case#: {case_idx:?}, case: {test_case:?}"
@@ -1139,6 +1225,169 @@ mod tests {
Ok(())
}
+ #[tokio::test]
+ async fn test_can_skip_ordering() -> Result<()> {
+ let test_schema = create_test_schema3()?;
+ // Columns a,c are nullable whereas b,d are not nullable.
+ // Source is sorted by a ASC NULLS FIRST, b ASC NULLS FIRST, c ASC NULLS FIRST, d ASC NULLS FIRST
+ // Column e is not ordered.
+ let sort_exprs = vec![
+ sort_expr("a", &test_schema),
+ sort_expr("b", &test_schema),
+ sort_expr("c", &test_schema),
+ sort_expr("d", &test_schema),
+ ];
+ let exec_unbounded = csv_exec_sorted(&test_schema, sort_exprs, true);
+
+ // test cases consists of vector of tuples. Where each tuple represents a single test case.
+ // First field in the tuple is Vec<str> where each element in the vector represents PARTITION BY columns
+ // For instance `vec!["a", "b"]` corresponds to PARTITION BY a, b
+ // Second field in the tuple is Vec<(str, bool, bool)> where each element in the vector represents ORDER BY columns
+ // For instance, vec![("c", false, false)], corresponds to ORDER BY c ASC NULLS LAST,
+ // similarly, vec![("c", true, true)], corresponds to ORDER BY c DESC NULLS FIRST,
+ // Third field in the tuple is Option<(bool, PartitionSearchMode)>, which corresponds to expected result.
+ // None represents that existing ordering is not sufficient to run executor with any one of the algorithms
+ // (We need to add SortExec to be able to run it).
+ // Some((bool, PartitionSearchMode)) represents, we can run algorithm with existing ordering. Algorithm should work in
+ // PartitionSearchMode, bool field represents whether we should reverse window expressions to run executor with existing ordering.
+ // For instance, `Some((false, PartitionSearchMode::Sorted))`, represents that we shouldn't reverse window expressions. And algorithm
+ // should work in Sorted mode to work with existing ordering.
+ let test_cases = vec![
+ // PARTITION BY a, b ORDER BY c ASC NULLS LAST
+ (vec!["a", "b"], vec![("c", false, false)], None),
+ // ORDER BY c ASC NULLS FIRST
+ (vec![], vec![("c", false, true)], None),
+ // PARTITION BY b, ORDER BY c ASC NULLS FIRST
+ (vec!["b"], vec![("c", false, true)], None),
+ // PARTITION BY a, ORDER BY c ASC NULLS FIRST
+ (vec!["a"], vec![("c", false, true)], None),
+ // PARTITION BY b, ORDER BY c ASC NULLS FIRST
+ (
+ vec!["a", "b"],
+ vec![("c", false, true), ("e", false, true)],
+ None,
+ ),
+ // PARTITION BY a, ORDER BY b ASC NULLS FIRST
+ (vec!["a"], vec![("b", false, true)], Some((false, Sorted))),
+ // PARTITION BY a, ORDER BY a ASC NULLS FIRST
+ (vec!["a"], vec![("a", false, true)], Some((false, Sorted))),
+ // PARTITION BY a, ORDER BY a ASC NULLS LAST
+ (vec!["a"], vec![("a", false, false)], Some((false, Sorted))),
+ // PARTITION BY a, ORDER BY a DESC NULLS FIRST
+ (vec!["a"], vec![("a", true, true)], Some((false, Sorted))),
+ // PARTITION BY a, ORDER BY a DESC NULLS LAST
+ (vec!["a"], vec![("a", true, false)], Some((false, Sorted))),
+ // PARTITION BY a, ORDER BY b ASC NULLS LAST
+ (vec!["a"], vec![("b", false, false)], Some((false, Sorted))),
+ // PARTITION BY a, ORDER BY b DESC NULLS LAST
+ (vec!["a"], vec![("b", true, false)], Some((true, Sorted))),
+ // PARTITION BY a, b ORDER BY c ASC NULLS FIRST
+ (
+ vec!["a", "b"],
+ vec![("c", false, true)],
+ Some((false, Sorted)),
+ ),
+ // PARTITION BY b, a ORDER BY c ASC NULLS FIRST
+ (
+ vec!["b", "a"],
+ vec![("c", false, true)],
+ Some((false, Sorted)),
+ ),
+ // PARTITION BY a, b ORDER BY c DESC NULLS LAST
+ (
+ vec!["a", "b"],
+ vec![("c", true, false)],
+ Some((true, Sorted)),
+ ),
+ // PARTITION BY e ORDER BY a ASC NULLS FIRST
+ (
+ vec!["e"],
+ vec![("a", false, true)],
+ // For unbounded, expects to work in Linear mode. Shouldn't reverse window function.
+ Some((false, Linear)),
+ ),
+ // PARTITION BY b, c ORDER BY a ASC NULLS FIRST, c ASC NULLS FIRST
+ (
+ vec!["b", "c"],
+ vec![("a", false, true), ("c", false, true)],
+ Some((false, Linear)),
+ ),
+ // PARTITION BY b ORDER BY a ASC NULLS FIRST
+ (vec!["b"], vec![("a", false, true)], Some((false, Linear))),
+ // PARTITION BY a, e ORDER BY b ASC NULLS FIRST
+ (
+ vec!["a", "e"],
+ vec![("b", false, true)],
+ Some((false, PartiallySorted(vec![0]))),
+ ),
+ // PARTITION BY a, c ORDER BY b ASC NULLS FIRST
+ (
+ vec!["a", "c"],
+ vec![("b", false, true)],
+ Some((false, PartiallySorted(vec![0]))),
+ ),
+ // PARTITION BY c, a ORDER BY b ASC NULLS FIRST
+ (
+ vec!["c", "a"],
+ vec![("b", false, true)],
+ Some((false, PartiallySorted(vec![1]))),
+ ),
+ // PARTITION BY d, b, a ORDER BY c ASC NULLS FIRST
+ (
+ vec!["d", "b", "a"],
+ vec![("c", false, true)],
+ Some((false, PartiallySorted(vec![2, 1]))),
+ ),
+ // PARTITION BY e, b, a ORDER BY c ASC NULLS FIRST
+ (
+ vec!["e", "b", "a"],
+ vec![("c", false, true)],
+ Some((false, PartiallySorted(vec![2, 1]))),
+ ),
+ // PARTITION BY d, a ORDER BY b ASC NULLS FIRST
+ (
+ vec!["d", "a"],
+ vec![("b", false, true)],
+ Some((false, PartiallySorted(vec![1]))),
+ ),
+ // PARTITION BY b, ORDER BY b, a ASC NULLS FIRST
+ (
+ vec!["a"],
+ vec![("b", false, true), ("a", false, true)],
+ Some((false, Sorted)),
+ ),
+ // ORDER BY b, a ASC NULLS FIRST
+ (vec![], vec![("b", false, true), ("a", false, true)], None),
+ ];
+ for (case_idx, test_case) in test_cases.iter().enumerate() {
+ let (partition_by_columns, order_by_params, expected) = &test_case;
+ let mut partition_by_exprs = vec![];
+ for col_name in partition_by_columns {
+ partition_by_exprs.push(col(col_name, &test_schema)?);
+ }
+
+ let mut order_by_exprs = vec![];
+ for (col_name, descending, nulls_first) in order_by_params {
+ let expr = col(col_name, &test_schema)?;
+ let options = SortOptions {
+ descending: *descending,
+ nulls_first: *nulls_first,
+ };
+ order_by_exprs.push(PhysicalSortExpr { expr, options });
+ }
+
+ assert_eq!(
+ can_skip_sort(&partition_by_exprs, &order_by_exprs, &exec_unbounded)?,
+ *expected,
+ "Unexpected result for in unbounded test case#: {:?}, case: {:?}",
+ case_idx,
+ test_case
+ );
+ }
+
+ Ok(())
+ }
+
/// Runs the sort enforcement optimizer and asserts the plan
/// against the original and expected plans
///
@@ -1239,10 +1488,10 @@ mod tests {
let physical_plan = bounded_window_exec("non_nullable_col", sort_exprs, filter);
let expected_input = vec![
- "BoundedWindowAggExec: wdw=[count: Ok(Field { name: \"count\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(NULL), end_bound: CurrentRow }]",
+ "BoundedWindowAggExec: wdw=[count: Ok(Field { name: \"count\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(NULL), end_bound: CurrentRow }], mode=[Sorted]",
" FilterExec: NOT non_nullable_col@1",
" SortExec: expr=[non_nullable_col@1 ASC NULLS LAST]",
- " BoundedWindowAggExec: wdw=[count: Ok(Field { name: \"count\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(NULL), end_bound: CurrentRow }]",
+ " BoundedWindowAggExec: wdw=[count: Ok(Field { name: \"count\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(NULL), end_bound: CurrentRow }], mode=[Sorted]",
" SortExec: expr=[non_nullable_col@1 DESC]",
" MemoryExec: partitions=0, partition_sizes=[]",
];
@@ -1250,7 +1499,7 @@ mod tests {
let expected_optimized = vec![
"WindowAggExec: wdw=[count: Ok(Field { name: \"count\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: CurrentRow, end_bound: Following(NULL) }]",
" FilterExec: NOT non_nullable_col@1",
- " BoundedWindowAggExec: wdw=[count: Ok(Field { name: \"count\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(NULL), end_bound: CurrentRow }]",
+ " BoundedWindowAggExec: wdw=[count: Ok(Field { name: \"count\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(NULL), end_bound: CurrentRow }], mode=[Sorted]",
" SortExec: expr=[non_nullable_col@1 DESC]",
" MemoryExec: partitions=0, partition_sizes=[]",
];
@@ -1982,7 +2231,7 @@ mod tests {
// corresponding SortExecs together. Also, the inputs of these `SortExec`s
// are not necessarily the same to be able to remove them.
let expected_input = vec![
- "BoundedWindowAggExec: wdw=[count: Ok(Field { name: \"count\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(NULL), end_bound: CurrentRow }]",
+ "BoundedWindowAggExec: wdw=[count: Ok(Field { name: \"count\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(NULL), end_bound: CurrentRow }], mode=[Sorted]",
" SortPreservingMergeExec: [nullable_col@0 DESC NULLS LAST]",
" UnionExec",
" SortExec: expr=[nullable_col@0 DESC NULLS LAST]",
@@ -2022,7 +2271,7 @@ mod tests {
// The `WindowAggExec` can get its required sorting from the leaf nodes directly.
// The unnecessary SortExecs should be removed
let expected_input = vec![
- "BoundedWindowAggExec: wdw=[count: Ok(Field { name: \"count\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(NULL), end_bound: CurrentRow }]",
+ "BoundedWindowAggExec: wdw=[count: Ok(Field { name: \"count\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(NULL), end_bound: CurrentRow }], mode=[Sorted]",
" SortPreservingMergeExec: [nullable_col@0 ASC,non_nullable_col@1 ASC]",
" UnionExec",
" SortExec: expr=[nullable_col@0 ASC,non_nullable_col@1 ASC]",
@@ -2031,7 +2280,7 @@ mod tests {
" ParquetExec: limit=None, partitions={1 group: [[x]]}, output_ordering=[nullable_col@0 ASC], projection=[nullable_col, non_nullable_col]",
];
let expected_optimized = vec![
- "BoundedWindowAggExec: wdw=[count: Ok(Field { name: \"count\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(NULL), end_bound: CurrentRow }]",
+ "BoundedWindowAggExec: wdw=[count: Ok(Field { name: \"count\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(NULL), end_bound: CurrentRow }], mode=[Sorted]",
" SortPreservingMergeExec: [nullable_col@0 ASC]",
" UnionExec",
" ParquetExec: limit=None, partitions={1 group: [[x]]}, output_ordering=[nullable_col@0 ASC], projection=[nullable_col, non_nullable_col]",
@@ -2333,17 +2582,17 @@ mod tests {
bounded_window_exec("non_nullable_col", sort_exprs1, window_agg2);
let expected_input = vec![
- "BoundedWindowAggExec: wdw=[count: Ok(Field { name: \"count\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(NULL), end_bound: CurrentRow }]",
- " BoundedWindowAggExec: wdw=[count: Ok(Field { name: \"count\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(NULL), end_bound: CurrentRow }]",
- " BoundedWindowAggExec: wdw=[count: Ok(Field { name: \"count\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(NULL), end_bound: CurrentRow }]",
+ "BoundedWindowAggExec: wdw=[count: Ok(Field { name: \"count\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(NULL), end_bound: CurrentRow }], mode=[Sorted]",
+ " BoundedWindowAggExec: wdw=[count: Ok(Field { name: \"count\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(NULL), end_bound: CurrentRow }], mode=[Sorted]",
+ " BoundedWindowAggExec: wdw=[count: Ok(Field { name: \"count\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(NULL), end_bound: CurrentRow }], mode=[Sorted]",
" SortExec: expr=[nullable_col@0 ASC]",
" MemoryExec: partitions=0, partition_sizes=[]",
];
let expected_optimized = vec![
- "BoundedWindowAggExec: wdw=[count: Ok(Field { name: \"count\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(NULL), end_bound: CurrentRow }]",
- " BoundedWindowAggExec: wdw=[count: Ok(Field { name: \"count\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(NULL), end_bound: CurrentRow }]",
- " BoundedWindowAggExec: wdw=[count: Ok(Field { name: \"count\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(NULL), end_bound: CurrentRow }]",
+ "BoundedWindowAggExec: wdw=[count: Ok(Field { name: \"count\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(NULL), end_bound: CurrentRow }], mode=[Sorted]",
+ " BoundedWindowAggExec: wdw=[count: Ok(Field { name: \"count\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(NULL), end_bound: CurrentRow }], mode=[Sorted]",
+ " BoundedWindowAggExec: wdw=[count: Ok(Field { name: \"count\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(NULL), end_bound: CurrentRow }], mode=[Sorted]",
" SortExec: expr=[nullable_col@0 ASC,non_nullable_col@1 ASC]",
" MemoryExec: partitions=0, partition_sizes=[]",
];
@@ -2539,6 +2788,7 @@ mod tests {
input.clone(),
input.schema(),
vec![],
+ Sorted,
)
.unwrap(),
)
@@ -2567,7 +2817,7 @@ mod tests {
fn parquet_exec_sorted(
schema: &SchemaRef,
sort_exprs: impl IntoIterator<Item = PhysicalSortExpr>,
- ) -> Arc<ParquetExec> {
+ ) -> Arc<dyn ExecutionPlan> {
let sort_exprs = sort_exprs.into_iter().collect();
Arc::new(ParquetExec::new(
diff --git a/datafusion/core/src/physical_plan/planner.rs b/datafusion/core/src/physical_plan/planner.rs
index 4bad535e52..8158351718 100644
--- a/datafusion/core/src/physical_plan/planner.rs
+++ b/datafusion/core/src/physical_plan/planner.rs
@@ -48,7 +48,9 @@ use crate::physical_plan::limit::{GlobalLimitExec, LocalLimitExec};
use crate::physical_plan::projection::ProjectionExec;
use crate::physical_plan::repartition::RepartitionExec;
use crate::physical_plan::sorts::sort::SortExec;
-use crate::physical_plan::windows::{BoundedWindowAggExec, WindowAggExec};
+use crate::physical_plan::windows::{
+ BoundedWindowAggExec, PartitionSearchMode, WindowAggExec,
+};
use crate::physical_plan::{joins::utils as join_utils, Partitioning};
use crate::physical_plan::{AggregateExpr, ExecutionPlan, PhysicalExpr, WindowExpr};
use crate::{
@@ -600,6 +602,7 @@ impl DefaultPhysicalPlanner {
input_exec,
physical_input_schema,
physical_partition_keys,
+ PartitionSearchMode::Sorted,
)?)
} else {
Arc::new(WindowAggExec::try_new(
diff --git a/datafusion/core/src/physical_plan/windows/bounded_window_agg_exec.rs b/datafusion/core/src/physical_plan/windows/bounded_window_agg_exec.rs
index a8d02bcd42..5dbafab76f 100644
--- a/datafusion/core/src/physical_plan/windows/bounded_window_agg_exec.rs
+++ b/datafusion/core/src/physical_plan/windows/bounded_window_agg_exec.rs
@@ -26,30 +26,41 @@ use crate::physical_plan::expressions::PhysicalSortExpr;
use crate::physical_plan::metrics::{
BaselineMetrics, ExecutionPlanMetricsSet, MetricsSet,
};
+use crate::physical_plan::windows::{
+ calc_requirements, get_ordered_partition_by_indices,
+};
use crate::physical_plan::{
ColumnStatistics, DisplayFormatType, Distribution, ExecutionPlan, Partitioning,
RecordBatchStream, SendableRecordBatchStream, Statistics, WindowExpr,
};
+
+use ahash::RandomState;
use arrow::{
- array::{Array, ArrayRef},
- compute::{concat, concat_batches, SortColumn},
+ array::{Array, ArrayRef, UInt32Builder},
+ compute::{concat, concat_batches, sort_to_indices},
datatypes::{Schema, SchemaBuilder, SchemaRef},
record_batch::RecordBatch,
};
-use datafusion_common::{DataFusionError, ScalarValue};
use futures::stream::Stream;
use futures::{ready, StreamExt};
+use hashbrown::raw::RawTable;
+use indexmap::IndexMap;
+use log::debug;
+
use std::any::Any;
-use std::cmp::min;
-use std::collections::HashMap;
+use std::cmp::{min, Ordering};
+use std::collections::{HashMap, VecDeque};
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
-use crate::physical_plan::windows::{
- calc_requirements, get_ordered_partition_by_indices,
+use datafusion_common::utils::{
+ evaluate_partition_ranges, get_arrayref_at_indices, get_at_indices,
+ get_record_batch_at_indices, get_row_at_idx,
};
-use datafusion_common::utils::{evaluate_partition_ranges, get_at_indices};
+use datafusion_common::DataFusionError;
+use datafusion_expr::ColumnarValue;
+use datafusion_physical_expr::hash_utils::create_hashes;
use datafusion_physical_expr::window::{
PartitionBatchState, PartitionBatches, PartitionKey, PartitionWindowAggStates,
WindowAggState, WindowState,
@@ -57,8 +68,17 @@ use datafusion_physical_expr::window::{
use datafusion_physical_expr::{
EquivalenceProperties, PhysicalExpr, PhysicalSortRequirement,
};
-use indexmap::IndexMap;
-use log::debug;
+
+#[derive(Debug, Clone, PartialEq)]
+/// Specifies partition column properties in terms of input ordering
+pub enum PartitionSearchMode {
+ /// None of the columns among the partition columns is ordered.
+ Linear,
+ /// Some columns of the partition columns are ordered but not all
+ PartiallySorted(Vec<usize>),
+ /// All Partition columns are ordered (Also empty case)
+ Sorted,
+}
/// Window execution plan
#[derive(Debug)]
@@ -75,8 +95,14 @@ pub struct BoundedWindowAggExec {
pub partition_keys: Vec<Arc<dyn PhysicalExpr>>,
/// Execution metrics
metrics: ExecutionPlanMetricsSet,
- /// Partition by indices that defines preset for existing ordering
- // see `get_ordered_partition_by_indices` for more details.
+ /// Partition by search mode
+ pub partition_search_mode: PartitionSearchMode,
+ /// Partition by indices that define ordering
+ // For example, if input ordering is ORDER BY a, b and window expression
+ // contains PARTITION BY b, a; `ordered_partition_by_indices` would be 1, 0.
+ // Similarly, if window expression contains PARTITION BY a, b; then
+ // `ordered_partition_by_indices` would be 0, 1.
+ // See `get_ordered_partition_by_indices` for more details.
ordered_partition_by_indices: Vec<usize>,
}
@@ -87,12 +113,30 @@ impl BoundedWindowAggExec {
input: Arc<dyn ExecutionPlan>,
input_schema: SchemaRef,
partition_keys: Vec<Arc<dyn PhysicalExpr>>,
+ partition_search_mode: PartitionSearchMode,
) -> Result<Self> {
let schema = create_schema(&input_schema, &window_expr)?;
let schema = Arc::new(schema);
-
- let ordered_partition_by_indices =
- get_ordered_partition_by_indices(window_expr[0].partition_by(), &input);
+ let partition_by_exprs = window_expr[0].partition_by();
+ let ordered_partition_by_indices = match &partition_search_mode {
+ PartitionSearchMode::Sorted => {
+ let indices = get_ordered_partition_by_indices(
+ window_expr[0].partition_by(),
+ &input,
+ );
+ if indices.len() == partition_by_exprs.len() {
+ indices
+ } else {
+ (0..partition_by_exprs.len()).collect::<Vec<_>>()
+ }
+ }
+ PartitionSearchMode::PartiallySorted(ordered_indices) => {
+ ordered_indices.clone()
+ }
+ PartitionSearchMode::Linear => {
+ vec![]
+ }
+ };
Ok(Self {
input,
window_expr,
@@ -100,6 +144,7 @@ impl BoundedWindowAggExec {
input_schema,
partition_keys,
metrics: ExecutionPlanMetricsSet::new(),
+ partition_search_mode,
ordered_partition_by_indices,
})
}
@@ -126,9 +171,34 @@ impl BoundedWindowAggExec {
// to calculate partition separation points
pub fn partition_by_sort_keys(&self) -> Result<Vec<PhysicalSortExpr>> {
// Partition by sort keys indices are stored in self.ordered_partition_by_indices.
- let sort_keys = self.input.output_ordering().unwrap_or(&[]);
+ let sort_keys = self.input.output_ordering();
+ let sort_keys = sort_keys.unwrap_or(&[]);
get_at_indices(sort_keys, &self.ordered_partition_by_indices)
}
+
+ /// Initializes the appropriate [`PartitionSearcher`] implementation from
+ /// the state.
+ fn get_search_algo(&self) -> Result<Box<dyn PartitionSearcher>> {
+ let partition_by_sort_keys = self.partition_by_sort_keys()?;
+ let ordered_partition_by_indices = self.ordered_partition_by_indices.clone();
+ Ok(match &self.partition_search_mode {
+ PartitionSearchMode::Sorted => {
+ // In Sorted mode, all partition by columns should be ordered.
+ if self.window_expr()[0].partition_by().len()
+ != ordered_partition_by_indices.len()
+ {
+ return Err(DataFusionError::Execution("All partition by columns should have an ordering in Sorted mode.".to_string()));
+ }
+ Box::new(SortedSearch {
+ partition_by_sort_keys,
+ ordered_partition_by_indices,
+ })
+ }
+ PartitionSearchMode::Linear | PartitionSearchMode::PartiallySorted(_) => {
+ Box::new(LinearSearch::new(ordered_partition_by_indices))
+ }
+ })
+ }
}
impl ExecutionPlan for BoundedWindowAggExec {
@@ -164,14 +234,16 @@ impl ExecutionPlan for BoundedWindowAggExec {
fn required_input_ordering(&self) -> Vec<Option<Vec<PhysicalSortRequirement>>> {
let partition_bys = self.window_expr()[0].partition_by();
let order_keys = self.window_expr()[0].order_by();
- if self.ordered_partition_by_indices.len() < partition_bys.len() {
- vec![calc_requirements(partition_bys, order_keys)]
- } else {
+ if self.partition_search_mode != PartitionSearchMode::Sorted
+ || self.ordered_partition_by_indices.len() >= partition_bys.len()
+ {
let partition_bys = self
.ordered_partition_by_indices
.iter()
.map(|idx| &partition_bys[*idx]);
vec![calc_requirements(partition_bys, order_keys)]
+ } else {
+ vec![calc_requirements(partition_bys, order_keys)]
}
}
@@ -201,6 +273,7 @@ impl ExecutionPlan for BoundedWindowAggExec {
children[0].clone(),
self.input_schema.clone(),
self.partition_keys.clone(),
+ self.partition_search_mode.clone(),
)?))
}
@@ -210,13 +283,13 @@ impl ExecutionPlan for BoundedWindowAggExec {
context: Arc<TaskContext>,
) -> Result<SendableRecordBatchStream> {
let input = self.input.execute(partition, context)?;
- let stream = Box::pin(SortedPartitionByBoundedWindowStream::new(
+ let search_mode = self.get_search_algo()?;
+ let stream = Box::pin(BoundedWindowAggStream::new(
self.schema.clone(),
self.window_expr.clone(),
input,
BaselineMetrics::new(&self.metrics, partition),
- self.partition_by_sort_keys()?,
- self.ordered_partition_by_indices.clone(),
+ search_mode,
)?);
Ok(stream)
}
@@ -241,7 +314,8 @@ impl ExecutionPlan for BoundedWindowAggExec {
)
})
.collect();
- write!(f, "wdw=[{}]", g.join(", "))?;
+ let mode = &self.partition_search_mode;
+ write!(f, "wdw=[{}], mode=[{:?}]", g.join(", "), mode)?;
}
}
Ok(())
@@ -272,6 +346,481 @@ impl ExecutionPlan for BoundedWindowAggExec {
}
}
+/// Trait that specifies how we search for (or calculate) partitions. It has two
+/// implementations: [`SortedSearch`] and [`LinearSearch`].
+trait PartitionSearcher: Send {
+ /// This method constructs output columns using the result of each window expression
+ /// (each entry in the output vector comes from a window expression).
+ /// Executor when producing output concatenates `input_buffer` (corresponding section), and
+ /// result of this function to generate output `RecordBatch`. `input_buffer` is used to determine
+ /// which sections of the window expression results should be used to generate output.
+ /// `partition_buffers` contains corresponding section of the `RecordBatch` for each partition.
+ /// `window_agg_states` stores per partition state for each window expression.
+ /// None case means that no result is generated
+ /// `Some(Vec<ArrayRef>)` is the result of each window expression.
+ fn calculate_out_columns(
+ &mut self,
+ input_buffer: &RecordBatch,
+ window_agg_states: &[PartitionWindowAggStates],
+ partition_buffers: &mut PartitionBatches,
+ window_expr: &[Arc<dyn WindowExpr>],
+ ) -> Result<Option<Vec<ArrayRef>>>;
+
+ // Constructs corresponding batches for each partition for the record_batch.
+ fn evaluate_partition_batches(
+ &mut self,
+ record_batch: &RecordBatch,
+ window_expr: &[Arc<dyn WindowExpr>],
+ ) -> Result<Vec<(PartitionKey, RecordBatch)>>;
+
+ /// Prunes the state.
+ fn prune(&mut self, _n_out: usize) {}
+
+ /// Marks the partition as done if we are sure that corresponding partition
+ /// cannot receive any more values.
+ fn mark_partition_end(&self, partition_buffers: &mut PartitionBatches);
+
+ /// Updates `input_buffer` and `partition_buffers` with the new `record_batch`.
+ fn update_partition_batch(
+ &mut self,
+ input_buffer: &mut RecordBatch,
+ record_batch: RecordBatch,
+ window_expr: &[Arc<dyn WindowExpr>],
+ partition_buffers: &mut PartitionBatches,
+ ) -> Result<()> {
+ if record_batch.num_rows() > 0 {
+ let partition_batches =
+ self.evaluate_partition_batches(&record_batch, window_expr)?;
+ for (partition_row, partition_batch) in partition_batches {
+ let partition_batch_state = partition_buffers
+ .entry(partition_row)
+ .or_insert_with(|| PartitionBatchState {
+ record_batch: RecordBatch::new_empty(partition_batch.schema()),
+ is_end: false,
+ n_out_row: 0,
+ });
+ partition_batch_state.record_batch = concat_batches(
+ &partition_batch.schema(),
+ [&partition_batch_state.record_batch, &partition_batch],
+ )?;
+ }
+ }
+ self.mark_partition_end(partition_buffers);
+
+ *input_buffer = if input_buffer.num_rows() == 0 {
+ record_batch
+ } else {
+ concat_batches(&input_buffer.schema(), [input_buffer, &record_batch])?
+ };
+
+ Ok(())
+ }
+}
+
+/// This object encapsulates the algorithm state for a simple linear scan
+/// algorithm for computing partitions.
+pub struct LinearSearch {
+ /// Keeps the hash of input buffer calculated from PARTITION BY columns.
+ /// Its length is equal to the `input_buffer` length.
+ input_buffer_hashes: VecDeque<u64>,
+ /// Used during hash value calculation.
+ random_state: RandomState,
+ /// Input ordering and partition by key ordering need not be the same, so
+ /// this vector stores the mapping between them. For instance, if the input
+ /// is ordered by a, b and the window expression contains a PARTITION BY b, a
+ /// clause, this attribute stores [1, 0].
+ ordered_partition_by_indices: Vec<usize>,
+ /// We use this [`RawTable`] to calculate unique partitions for each new
+ /// RecordBatch. First entry in the tuple is the hash value, the second
+ /// entry is the unique ID for each partition (increments from 0 to n).
+ row_map_batch: RawTable<(u64, usize)>,
+ /// We use this [`RawTable`] to calculate the output columns that we can
+ /// produce at each cycle. First entry in the tuple is the hash value, the
+ /// second entry is the unique ID for each partition (increments from 0 to n).
+ /// The third entry stores how many new outputs are calculated for the
+ /// corresponding partition.
+ row_map_out: RawTable<(u64, usize, usize)>,
+}
+
+impl PartitionSearcher for LinearSearch {
+ /// This method constructs output columns using the result of each window expression.
+ // Assume input buffer is | Partition Buffers would be (Where each partition and its data is seperated)
+ // a, 2 | a, 2
+ // b, 2 | a, 2
+ // a, 2 | a, 2
+ // b, 2 |
+ // a, 2 | b, 2
+ // b, 2 | b, 2
+ // b, 2 | b, 2
+ // | b, 2
+ // Also assume we happen to calculate 2 new values for a, and 3 for b (To be calculate missing values we may need to consider future values).
+ // Partition buffers effectively will be
+ // a, 2, 1
+ // a, 2, 2
+ // a, 2, (missing)
+ //
+ // b, 2, 1
+ // b, 2, 2
+ // b, 2, 3
+ // b, 2, (missing)
+ // When partition buffers are mapped back to the original record batch. Result becomes
+ // a, 2, 1
+ // b, 2, 1
+ // a, 2, 2
+ // b, 2, 2
+ // a, 2, (missing)
+ // b, 2, 3
+ // b, 2, (missing)
+ // This function calculates the column result of window expression(s) (First 4 entry of 3rd column in the above section.)
+ // 1
+ // 1
+ // 2
+ // 2
+ // Above section corresponds to calculated result which can be emitted without breaking input buffer ordering.
+ fn calculate_out_columns(
+ &mut self,
+ input_buffer: &RecordBatch,
+ window_agg_states: &[PartitionWindowAggStates],
+ partition_buffers: &mut PartitionBatches,
+ window_expr: &[Arc<dyn WindowExpr>],
+ ) -> Result<Option<Vec<ArrayRef>>> {
+ let partition_output_indices = self.calc_partition_output_indices(
+ input_buffer,
+ window_agg_states,
+ window_expr,
+ )?;
+
+ let n_window_col = window_agg_states.len();
+ let mut new_columns = vec![vec![]; n_window_col];
+ // Size of all_indices can be at most input_buffer.num_rows():
+ let mut all_indices = UInt32Builder::with_capacity(input_buffer.num_rows());
+ for (row, indices) in partition_output_indices {
+ let length = indices.len();
+ for (idx, window_agg_state) in window_agg_states.iter().enumerate() {
+ let partition = &window_agg_state[&row];
+ let values = partition.state.out_col.slice(0, length).clone();
+ new_columns[idx].push(values);
+ }
+ let partition_batch_state = &mut partition_buffers[&row];
+ // Store how many rows are generated for each partition
+ partition_batch_state.n_out_row = length;
+ // For each row keep corresponding index in the input record batch
+ all_indices.append_slice(&indices);
+ }
+ let all_indices = all_indices.finish();
+ if all_indices.is_empty() {
+ // We couldn't generate any new value, return early:
+ return Ok(None);
+ }
+
+ // Concatenate results for each column by converting `Vec<Vec<ArrayRef>>`
+ // to Vec<ArrayRef> where inner `Vec<ArrayRef>`s are converted to `ArrayRef`s.
+ let new_columns = new_columns
+ .iter()
+ .map(|items| {
+ concat(&items.iter().map(|e| e.as_ref()).collect::<Vec<_>>())
+ .map_err(DataFusionError::ArrowError)
+ })
+ .collect::<Result<Vec<_>>>()?;
+ // We should emit columns according to row index ordering.
+ let sorted_indices = sort_to_indices(&all_indices, None, None)?;
+ // Construct new column according to row ordering. This fixes ordering
+ get_arrayref_at_indices(&new_columns, &sorted_indices).map(Some)
+ }
+
+ fn evaluate_partition_batches(
+ &mut self,
+ record_batch: &RecordBatch,
+ window_expr: &[Arc<dyn WindowExpr>],
+ ) -> Result<Vec<(PartitionKey, RecordBatch)>> {
+ let partition_bys =
+ self.evaluate_partition_by_column_values(record_batch, window_expr)?;
+ // NOTE: In Linear or PartiallySorted modes, we are sure that
+ // `partition_bys` are not empty.
+ // Calculate indices for each partition and construct a new record
+ // batch from the rows at these indices for each partition:
+ self.get_per_partition_indices(&partition_bys, record_batch)?
+ .into_iter()
+ .map(|(row, indices)| {
+ let mut new_indices = UInt32Builder::with_capacity(indices.len());
+ new_indices.append_slice(&indices);
+ let indices = new_indices.finish();
+ Ok((row, get_record_batch_at_indices(record_batch, &indices)?))
+ })
+ .collect()
+ }
+
+ fn prune(&mut self, n_out: usize) {
+ // Delete hashes for the rows that are outputted.
+ self.input_buffer_hashes.drain(0..n_out);
+ }
+
+ fn mark_partition_end(&self, partition_buffers: &mut PartitionBatches) {
+ // We should be in the `PartiallySorted` case, otherwise we can not
+ // tell when we are at the end of a given partition.
+ if !self.ordered_partition_by_indices.is_empty() {
+ if let Some((last_row, _)) = partition_buffers.last() {
+ let last_sorted_cols = self
+ .ordered_partition_by_indices
+ .iter()
+ .map(|idx| last_row[*idx].clone())
+ .collect::<Vec<_>>();
+ for (row, partition_batch_state) in partition_buffers.iter_mut() {
+ let sorted_cols = self
+ .ordered_partition_by_indices
+ .iter()
+ .map(|idx| &row[*idx]);
+ // All the partitions other than `last_sorted_cols` are done.
+ // We are sure that we will no longer receive values for these
+ // partitions (arrival of a new value would violate ordering).
+ partition_batch_state.is_end = !sorted_cols.eq(&last_sorted_cols);
+ }
+ }
+ }
+ }
+}
+
+impl LinearSearch {
+ /// Initialize a new [`LinearSearch`] partition searcher.
+ fn new(ordered_partition_by_indices: Vec<usize>) -> Self {
+ LinearSearch {
+ input_buffer_hashes: VecDeque::new(),
+ random_state: Default::default(),
+ ordered_partition_by_indices,
+ row_map_batch: RawTable::with_capacity(256),
+ row_map_out: RawTable::with_capacity(256),
+ }
+ }
+
+ /// Calculates partition by expression results for each window expression
+ /// on `record_batch`.
+ fn evaluate_partition_by_column_values(
+ &self,
+ record_batch: &RecordBatch,
+ window_expr: &[Arc<dyn WindowExpr>],
+ ) -> Result<Vec<ArrayRef>> {
+ window_expr[0]
+ .partition_by()
+ .iter()
+ .map(|item| match item.evaluate(record_batch)? {
+ ColumnarValue::Array(array) => Ok(array),
+ ColumnarValue::Scalar(scalar) => Err(DataFusionError::Plan(format!(
+ "Sort operation is not applicable to scalar value {scalar}"
+ ))),
+ })
+ .collect()
+ }
+
+ /// Calculate indices of each partition (according to PARTITION BY expression)
+ /// `columns` contain partition by expression results.
+ fn get_per_partition_indices(
+ &mut self,
+ columns: &[ArrayRef],
+ batch: &RecordBatch,
+ ) -> Result<Vec<(PartitionKey, Vec<u32>)>> {
+ let mut batch_hashes = vec![0; batch.num_rows()];
+ create_hashes(columns, &self.random_state, &mut batch_hashes)?;
+ self.input_buffer_hashes.extend(&batch_hashes);
+ // reset row_map for new calculation
+ self.row_map_batch.clear();
+ // res stores PartitionKey and row indices (indices where these partition occurs in the `batch`) for each partition.
+ let mut result: Vec<(PartitionKey, Vec<u32>)> = vec![];
+ for (hash, row_idx) in batch_hashes.into_iter().zip(0u32..) {
+ let entry = self.row_map_batch.get_mut(hash, |(_, group_idx)| {
+ // We can safely get the first index of the partition indices
+ // since partition indices has one element during initialization.
+ let row = get_row_at_idx(columns, row_idx as usize).unwrap();
+ // Handle hash collusions with an equality check:
+ row.eq(&result[*group_idx].0)
+ });
+ if let Some((_, group_idx)) = entry {
+ result[*group_idx].1.push(row_idx)
+ } else {
+ self.row_map_batch
+ .insert(hash, (hash, result.len()), |(hash, _)| *hash);
+ let row = get_row_at_idx(columns, row_idx as usize)?;
+ // This is a new partition its only index is row_idx for now.
+ result.push((row, vec![row_idx]));
+ }
+ }
+ Ok(result)
+ }
+
+ /// Calculates partition keys and result indices for each partition.
+ /// The return value is a vector of tuples where the first entry stores
+ /// the partition key (unique for each partition) and the second entry
+ /// stores indices of the rows for which the partition is constructed.
+ fn calc_partition_output_indices(
+ &mut self,
+ input_buffer: &RecordBatch,
+ window_agg_states: &[PartitionWindowAggStates],
+ window_expr: &[Arc<dyn WindowExpr>],
+ ) -> Result<Vec<(PartitionKey, Vec<u32>)>> {
+ let partition_by_columns =
+ self.evaluate_partition_by_column_values(input_buffer, window_expr)?;
+ // Reset the row_map state:
+ self.row_map_out.clear();
+ let mut partition_indices: Vec<(PartitionKey, Vec<u32>)> = vec![];
+ for (hash, row_idx) in self.input_buffer_hashes.iter().zip(0u32..) {
+ let entry = self.row_map_out.get_mut(*hash, |(_, group_idx, _)| {
+ let row =
+ get_row_at_idx(&partition_by_columns, row_idx as usize).unwrap();
+ row == partition_indices[*group_idx].0
+ });
+ if let Some((_, group_idx, n_out)) = entry {
+ let (_, indices) = &mut partition_indices[*group_idx];
+ if indices.len() >= *n_out {
+ break;
+ }
+ indices.push(row_idx);
+ } else {
+ let row = get_row_at_idx(&partition_by_columns, row_idx as usize)?;
+ let min_out = window_agg_states
+ .iter()
+ .map(|window_agg_state| {
+ window_agg_state
+ .get(&row)
+ .map(|partition| partition.state.out_col.len())
+ .unwrap_or(0)
+ })
+ .min()
+ .unwrap_or(0);
+ if min_out == 0 {
+ break;
+ }
+ self.row_map_out.insert(
+ *hash,
+ (*hash, partition_indices.len(), min_out),
+ |(hash, _, _)| *hash,
+ );
+ partition_indices.push((row, vec![row_idx]));
+ }
+ }
+ Ok(partition_indices)
+ }
+}
+
+/// This object encapsulates the algorithm state for sorted searching
+/// when computing partitions.
+pub struct SortedSearch {
+ /// Stores partition by columns and their ordering information
+ partition_by_sort_keys: Vec<PhysicalSortExpr>,
+ /// Input ordering and partition by key ordering need not be the same, so
+ /// this vector stores the mapping between them. For instance, if the input
+ /// is ordered by a, b and the window expression contains a PARTITION BY b, a
+ /// clause, this attribute stores [1, 0].
+ ordered_partition_by_indices: Vec<usize>,
+}
+
+impl PartitionSearcher for SortedSearch {
+ /// This method constructs new output columns using the result of each window expression.
+ fn calculate_out_columns(
+ &mut self,
+ _input_buffer: &RecordBatch,
+ window_agg_states: &[PartitionWindowAggStates],
+ partition_buffers: &mut PartitionBatches,
+ _window_expr: &[Arc<dyn WindowExpr>],
+ ) -> Result<Option<Vec<ArrayRef>>> {
+ let n_out = self.calculate_n_out_row(window_agg_states, partition_buffers);
+ if n_out == 0 {
+ Ok(None)
+ } else {
+ window_agg_states
+ .iter()
+ .map(|map| get_aggregate_result_out_column(map, n_out).map(Some))
+ .collect()
+ }
+ }
+
+ fn evaluate_partition_batches(
+ &mut self,
+ record_batch: &RecordBatch,
+ _window_expr: &[Arc<dyn WindowExpr>],
+ ) -> Result<Vec<(PartitionKey, RecordBatch)>> {
+ let num_rows = record_batch.num_rows();
+ // Calculate result of partition by column expressions
+ let partition_columns = self
+ .partition_by_sort_keys
+ .iter()
+ .map(|elem| elem.evaluate_to_sort_column(record_batch))
+ .collect::<Result<Vec<_>>>()?;
+ // Reorder `partition_columns` such that its ordering matches input ordering.
+ let partition_columns_ordered =
+ get_at_indices(&partition_columns, &self.ordered_partition_by_indices)?;
+ let partition_points =
+ evaluate_partition_ranges(num_rows, &partition_columns_ordered)?;
+ let partition_bys = partition_columns
+ .into_iter()
+ .map(|arr| arr.values)
+ .collect::<Vec<ArrayRef>>();
+
+ partition_points
+ .iter()
+ .map(|range| {
+ let row = get_row_at_idx(&partition_bys, range.start)?;
+ let len = range.end - range.start;
+ let slice = record_batch.slice(range.start, len);
+ Ok((row, slice))
+ })
+ .collect::<Result<Vec<_>>>()
+ }
+
+ fn mark_partition_end(&self, partition_buffers: &mut PartitionBatches) {
+ // In Sorted case. We can mark all partitions besides last partition as ended.
+ // We are sure that those partitions will never receive any values.
+ // (Otherwise ordering invariant is violated.)
+ let n_partitions = partition_buffers.len();
+ for (idx, (_, partition_batch_state)) in partition_buffers.iter_mut().enumerate()
+ {
+ partition_batch_state.is_end |= idx < n_partitions - 1;
+ }
+ }
+}
+
+impl SortedSearch {
+ /// Calculates how many rows we can output.
+ fn calculate_n_out_row(
+ &mut self,
+ window_agg_states: &[PartitionWindowAggStates],
+ partition_buffers: &mut PartitionBatches,
+ ) -> usize {
+ // Different window aggregators may produce results at different rates.
+ // We produce the overall batch result only as fast as the slowest one.
+ let mut counts = vec![];
+ let out_col_counts = window_agg_states.iter().map(|window_agg_state| {
+ // Store how many elements are generated for the current
+ // window expression:
+ let mut cur_window_expr_out_result_len = 0;
+ // We iterate over `window_agg_state`, which is an IndexMap.
+ // Iterations follow the insertion order, hence we preserve
+ // sorting when partition columns are sorted.
+ let mut per_partition_out_results = HashMap::new();
+ for (row, WindowState { state, .. }) in window_agg_state.iter() {
+ cur_window_expr_out_result_len += state.out_col.len();
+ let count = per_partition_out_results.entry(row).or_insert(0);
+ if *count < state.out_col.len() {
+ *count = state.out_col.len();
+ }
+ // If we do not generate all results for the current
+ // partition, we do not generate results for next
+ // partition -- otherwise we will lose input ordering.
+ if state.n_row_result_missing > 0 {
+ break;
+ }
+ }
+ counts.push(per_partition_out_results);
+ cur_window_expr_out_result_len
+ });
+ argmin(out_col_counts).map_or(0, |(min_idx, minima)| {
+ for (row, count) in counts.swap_remove(min_idx).into_iter() {
+ let partition_batch = &mut partition_buffers[row];
+ partition_batch.n_out_row = count;
+ }
+ minima
+ })
+ }
+}
+
fn create_schema(
input_schema: &Schema,
window_expr: &[Arc<dyn WindowExpr>],
@@ -286,29 +835,14 @@ fn create_schema(
Ok(builder.finish())
}
-/// This trait defines the interface for updating the state and calculating
-/// results for window functions. Depending on the partitioning scheme, one
-/// may have different implementations for the functions within.
-pub trait PartitionByHandler {
- /// Constructs output columns from window_expression results.
- fn calculate_out_columns(&self) -> Result<Option<Vec<ArrayRef>>>;
- /// Prunes the window state to remove any unnecessary information
- /// given how many rows we emitted so far.
- fn prune_state(&mut self, n_out: usize) -> Result<()>;
- /// Updates record batches for each partition when new batches are
- /// received.
- fn update_partition_batch(&mut self, record_batch: RecordBatch) -> Result<()>;
-}
-
-/// stream for window aggregation plan
-/// assuming partition by column is sorted (or without PARTITION BY expression)
-pub struct SortedPartitionByBoundedWindowStream {
+/// Stream for the bounded window aggregation plan.
+pub struct BoundedWindowAggStream {
schema: SchemaRef,
input: SendableRecordBatchStream,
/// The record batch executor receives as input (i.e. the columns needed
/// while calculating aggregation results).
input_buffer: RecordBatch,
- /// We separate `input_buffer_record_batch` based on partitions (as
+ /// We separate `input_buffer` based on partitions (as
/// determined by PARTITION BY columns) and store them per partition
/// in `partition_batches`. We use this variable when calculating results
/// for each window expression. This enables us to use the same batch for
@@ -323,100 +857,34 @@ pub struct SortedPartitionByBoundedWindowStream {
window_agg_states: Vec<PartitionWindowAggStates>,
finished: bool,
window_expr: Vec<Arc<dyn WindowExpr>>,
- partition_by_sort_keys: Vec<PhysicalSortExpr>,
baseline_metrics: BaselineMetrics,
- ordered_partition_by_indices: Vec<usize>,
+ /// Search mode for partition columns. This determines the algorithm with
+ /// which we group each partition.
+ search_mode: Box<dyn PartitionSearcher>,
}
-impl PartitionByHandler for SortedPartitionByBoundedWindowStream {
- /// This method constructs output columns using the result of each window expression
- fn calculate_out_columns(&self) -> Result<Option<Vec<ArrayRef>>> {
- let n_out = self.calculate_n_out_row();
- if n_out == 0 {
- Ok(None)
- } else {
- self.input_buffer
- .columns()
- .iter()
- .map(|elem| Ok(elem.slice(0, n_out)))
- .chain(
- self.window_agg_states
- .iter()
- .map(|elem| get_aggregate_result_out_column(elem, n_out)),
- )
- .collect::<Result<Vec<_>>>()
- .map(Some)
- }
- }
-
+impl BoundedWindowAggStream {
/// Prunes sections of the state that are no longer needed when calculating
/// results (as determined by window frame boundaries and number of results generated).
// For instance, if first `n` (not necessarily same with `n_out`) elements are no longer needed to
// calculate window expression result (outside the window frame boundary) we retract first `n` elements
// from `self.partition_batches` in corresponding partition.
// For instance, if `n_out` number of rows are calculated, we can remove
- // first `n_out` rows from `self.input_buffer_record_batch`.
+ // first `n_out` rows from `self.input_buffer`.
fn prune_state(&mut self, n_out: usize) -> Result<()> {
// Prune `self.window_agg_states`:
- self.prune_out_columns(n_out)?;
+ self.prune_out_columns();
// Prune `self.partition_batches`:
- self.prune_partition_batches()?;
- // Prune `self.input_buffer_record_batch`:
+ self.prune_partition_batches();
+ // Prune `self.input_buffer`:
self.prune_input_batch(n_out)?;
- Ok(())
- }
-
- fn update_partition_batch(&mut self, record_batch: RecordBatch) -> Result<()> {
- let partition_columns = self.partition_columns(&record_batch)?;
- let num_rows = record_batch.num_rows();
- if num_rows > 0 {
- let partition_points =
- evaluate_partition_ranges(num_rows, &partition_columns)?;
- for partition_range in partition_points {
- let partition_row = partition_columns
- .iter()
- .map(|arr| {
- ScalarValue::try_from_array(&arr.values, partition_range.start)
- })
- .collect::<Result<PartitionKey>>()?;
- let partition_batch = record_batch.slice(
- partition_range.start,
- partition_range.end - partition_range.start,
- );
- if let Some(partition_batch_state) =
- self.partition_buffers.get_mut(&partition_row)
- {
- partition_batch_state.record_batch = concat_batches(
- &self.input.schema(),
- [&partition_batch_state.record_batch, &partition_batch],
- )?;
- } else {
- let partition_batch_state = PartitionBatchState {
- record_batch: partition_batch,
- is_end: false,
- };
- self.partition_buffers
- .insert(partition_row, partition_batch_state);
- };
- }
- }
- let n_partitions = self.partition_buffers.len();
- for (idx, (_, partition_batch_state)) in
- self.partition_buffers.iter_mut().enumerate()
- {
- partition_batch_state.is_end |= idx < n_partitions - 1;
- }
- self.input_buffer = if self.input_buffer.num_rows() == 0 {
- record_batch
- } else {
- concat_batches(&self.input.schema(), [&self.input_buffer, &record_batch])?
- };
-
+ // Prune internal state of search algorithm.
+ self.search_mode.prune(n_out);
Ok(())
}
}
-impl Stream for SortedPartitionByBoundedWindowStream {
+impl Stream for BoundedWindowAggStream {
type Item = Result<RecordBatch>;
fn poll_next(
@@ -428,26 +896,17 @@ impl Stream for SortedPartitionByBoundedWindowStream {
}
}
-impl SortedPartitionByBoundedWindowStream {
+impl BoundedWindowAggStream {
/// Create a new BoundedWindowAggStream
- pub fn new(
+ fn new(
schema: SchemaRef,
window_expr: Vec<Arc<dyn WindowExpr>>,
input: SendableRecordBatchStream,
baseline_metrics: BaselineMetrics,
- partition_by_sort_keys: Vec<PhysicalSortExpr>,
- ordered_partition_by_indices: Vec<usize>,
+ search_mode: Box<dyn PartitionSearcher>,
) -> Result<Self> {
let state = window_expr.iter().map(|_| IndexMap::new()).collect();
let empty_batch = RecordBatch::new_empty(schema.clone());
-
- // In BoundedWindowAggExec all partition by columns should be ordered.
- if window_expr[0].partition_by().len() != ordered_partition_by_indices.len() {
- return Err(DataFusionError::Internal(
- "All partition by columns should have an ordering".to_string(),
- ));
- }
-
Ok(Self {
schema,
input,
@@ -457,8 +916,7 @@ impl SortedPartitionByBoundedWindowStream {
finished: false,
window_expr,
baseline_metrics,
- partition_by_sort_keys,
- ordered_partition_by_indices,
+ search_mode,
})
}
@@ -471,8 +929,22 @@ impl SortedPartitionByBoundedWindowStream {
}
let schema = self.schema.clone();
- let columns_to_show = self.calculate_out_columns()?;
- if let Some(columns_to_show) = columns_to_show {
+ let window_expr_out = self.search_mode.calculate_out_columns(
+ &self.input_buffer,
+ &self.window_agg_states,
+ &mut self.partition_buffers,
+ &self.window_expr,
+ )?;
+ if let Some(window_expr_out) = window_expr_out {
+ let n_out = window_expr_out[0].len();
+ // right append new columns to corresponding section in the original input buffer.
+ let columns_to_show = self
+ .input_buffer
+ .columns()
+ .iter()
+ .map(|elem| elem.slice(0, n_out))
+ .chain(window_expr_out.into_iter())
+ .collect::<Vec<_>>();
let n_generated = columns_to_show[0].len();
self.prune_state(n_generated)?;
Ok(RecordBatch::try_new(schema, columns_to_show)?)
@@ -492,7 +964,12 @@ impl SortedPartitionByBoundedWindowStream {
let result = match ready!(self.input.poll_next_unpin(cx)) {
Some(Ok(batch)) => {
- self.update_partition_batch(batch)?;
+ self.search_mode.update_partition_batch(
+ &mut self.input_buffer,
+ batch,
+ &self.window_expr,
+ &mut self.partition_buffers,
+ )?;
self.compute_aggregates()
}
Some(Err(e)) => Err(e),
@@ -507,38 +984,9 @@ impl SortedPartitionByBoundedWindowStream {
Poll::Ready(Some(result))
}
- /// Calculates how many rows [SortedPartitionByBoundedWindowStream]
- /// can produce as output.
- fn calculate_n_out_row(&self) -> usize {
- // Different window aggregators may produce results with different rates.
- // We produce the overall batch result with the same speed as slowest one.
- self.window_agg_states
- .iter()
- .map(|window_agg_state| {
- // Store how many elements are generated for the current
- // window expression:
- let mut cur_window_expr_out_result_len = 0;
- // We iterate over `window_agg_state`, which is an IndexMap.
- // Iterations follow the insertion order, hence we preserve
- // sorting when partition columns are sorted.
- for (_, WindowState { state, .. }) in window_agg_state.iter() {
- cur_window_expr_out_result_len += state.out_col.len();
- // If we do not generate all results for the current
- // partition, we do not generate results for next
- // partition -- otherwise we will lose input ordering.
- if state.n_row_result_missing > 0 {
- break;
- }
- }
- cur_window_expr_out_result_len
- })
- .min()
- .unwrap_or(0)
- }
-
/// Prunes the sections of the record batch (for each partition)
/// that we no longer need to calculate the window function result.
- fn prune_partition_batches(&mut self) -> Result<()> {
+ fn prune_partition_batches(&mut self) {
// Remove partitions which we know already ended (is_end flag is true).
// Since the retain method preserves insertion order, we still have
// ordering in between partitions after removal.
@@ -556,7 +1004,7 @@ impl SortedPartitionByBoundedWindowStream {
// batch in `self.partition_batches`.
// Calculate how many elements to prune for each partition batch
- let mut n_prune_each_partition: HashMap<PartitionKey, usize> = HashMap::new();
+ let mut n_prune_each_partition = HashMap::new();
for window_agg_state in self.window_agg_states.iter_mut() {
window_agg_state.retain(|_, WindowState { state, .. }| !state.is_end);
for (partition_row, WindowState { state: value, .. }) in window_agg_state {
@@ -572,28 +1020,25 @@ impl SortedPartitionByBoundedWindowStream {
}
}
- let err = || DataFusionError::Execution("Expects to have partition".to_string());
// Retract no longer needed parts during window calculations from partition batch:
for (partition_row, n_prune) in n_prune_each_partition.iter() {
- let partition_batch_state = self
- .partition_buffers
- .get_mut(partition_row)
- .ok_or_else(err)?;
- let batch = &partition_batch_state.record_batch;
- partition_batch_state.record_batch =
- batch.slice(*n_prune, batch.num_rows() - n_prune);
+ let pb_state = &mut self.partition_buffers[partition_row];
+
+ let batch = &pb_state.record_batch;
+ pb_state.record_batch = batch.slice(*n_prune, batch.num_rows() - n_prune);
+ pb_state.n_out_row = 0;
// Update state indices since we have pruned some rows from the beginning:
for window_agg_state in self.window_agg_states.iter_mut() {
window_agg_state[partition_row].state.prune_state(*n_prune);
}
}
- Ok(())
}
/// Prunes the section of the input batch whose aggregate results
/// are calculated and emitted.
fn prune_input_batch(&mut self, n_out: usize) -> Result<()> {
+ // Prune first n_out rows from the input_buffer
let n_to_keep = self.input_buffer.num_rows() - n_out;
let batch_to_keep = self
.input_buffer
@@ -607,51 +1052,46 @@ impl SortedPartitionByBoundedWindowStream {
}
/// Prunes emitted parts from WindowAggState `out_col` field.
- fn prune_out_columns(&mut self, n_out: usize) -> Result<()> {
+ fn prune_out_columns(&mut self) {
// We store generated columns for each window expression in the `out_col`
// field of `WindowAggState`. Given how many rows are emitted, we remove
// these sections from state.
for partition_window_agg_states in self.window_agg_states.iter_mut() {
- let mut running_length = 0;
// Remove `n_out` entries from the `out_col` field of `WindowAggState`.
- // Preserve per partition ordering by iterating in the order of insertion.
- // Do not generate a result for a new partition without emitting all results
- // for the current partition.
+ // `n_out` is stored in `self.partition_buffers` for each partition.
+ // If `is_end` is set, directly remove them; this shrinks the hash map.
+ partition_window_agg_states
+ .retain(|_, partition_batch_state| !partition_batch_state.state.is_end);
for (
- _,
+ partition_key,
WindowState {
state: WindowAggState { out_col, .. },
..
},
) in partition_window_agg_states
{
- if running_length < n_out {
- let n_to_del = min(out_col.len(), n_out - running_length);
- let n_to_keep = out_col.len() - n_to_del;
- *out_col = out_col.slice(n_to_del, n_to_keep);
- running_length += n_to_del;
- }
+ let partition_batch = &mut self.partition_buffers[partition_key];
+ let n_to_del = partition_batch.n_out_row;
+ let n_to_keep = out_col.len() - n_to_del;
+ *out_col = out_col.slice(n_to_del, n_to_keep);
}
}
- Ok(())
- }
-
- /// Get Partition Columns
- pub fn partition_columns(&self, batch: &RecordBatch) -> Result<Vec<SortColumn>> {
- self.ordered_partition_by_indices
- .iter()
- .map(|idx| self.partition_by_sort_keys[*idx].evaluate_to_sort_column(batch))
- .collect()
}
}
-impl RecordBatchStream for SortedPartitionByBoundedWindowStream {
+impl RecordBatchStream for BoundedWindowAggStream {
/// Get the schema
fn schema(&self) -> SchemaRef {
self.schema.clone()
}
}
+// Gets the index of minimum entry, returns None if empty.
+fn argmin<T: PartialOrd>(data: impl Iterator<Item = T>) -> Option<(usize, T)> {
+ data.enumerate()
+ .min_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap_or(Ordering::Equal))
+}
+
/// Calculates the section we can show results for expression
fn get_aggregate_result_out_column(
partition_window_agg_states: &PartitionWindowAggStates,
diff --git a/datafusion/core/src/physical_plan/windows/mod.rs b/datafusion/core/src/physical_plan/windows/mod.rs
index eea0749e94..65d7729e18 100644
--- a/datafusion/core/src/physical_plan/windows/mod.rs
+++ b/datafusion/core/src/physical_plan/windows/mod.rs
@@ -44,6 +44,7 @@ mod bounded_window_agg_exec;
mod window_agg_exec;
pub use bounded_window_agg_exec::BoundedWindowAggExec;
+pub use bounded_window_agg_exec::PartitionSearchMode;
use datafusion_common::utils::longest_consecutive_prefix;
use datafusion_physical_expr::utils::{convert_to_expr, get_indices_of_matching_exprs};
pub use datafusion_physical_expr::window::{
diff --git a/datafusion/core/src/test_util/mod.rs b/datafusion/core/src/test_util/mod.rs
index 96e76bd2c1..5ac602a085 100644
--- a/datafusion/core/src/test_util/mod.rs
+++ b/datafusion/core/src/test_util/mod.rs
@@ -337,6 +337,57 @@ fn get_test_data() -> Result<(RecordBatch, Vec<Expr>)> {
Ok((batch, file_sort_order))
}
+// Return a static RecordBatch and its ordering for tests. RecordBatch is ordered by a, b, c
+fn get_test_data2() -> Result<(RecordBatch, Vec<Expr>)> {
+ let a = Field::new("a", DataType::Int32, false);
+ let b = Field::new("b", DataType::Int32, false);
+ let c = Field::new("c", DataType::Int32, false);
+ let d = Field::new("d", DataType::Int32, false);
+
+ let schema = Arc::new(Schema::new(vec![a, b, c, d]));
+
+ let batch = RecordBatch::try_new(
+ schema,
+ vec![
+ Arc::new(Int32Array::from_slice([
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+ 1, 1, 1, 1,
+ ])),
+ Arc::new(Int32Array::from_slice([
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+ 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+ 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
+ 3, 3, 3, 3,
+ ])),
+ Arc::new(Int32Array::from_slice([
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
+ 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,
+ 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56,
+ 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74,
+ 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92,
+ 93, 94, 95, 96, 97, 98, 99,
+ ])),
+ Arc::new(Int32Array::from_slice([
+ 0, 2, 0, 0, 1, 1, 0, 2, 1, 4, 4, 2, 2, 1, 2, 3, 3, 2, 1, 4, 0, 3, 0, 0,
+ 4, 0, 2, 0, 1, 1, 3, 4, 2, 2, 4, 0, 1, 4, 0, 1, 1, 3, 3, 2, 3, 0, 0, 1,
+ 1, 3, 0, 3, 1, 1, 4, 2, 1, 1, 1, 2, 4, 3, 1, 4, 4, 0, 2, 4, 1, 1, 0, 2,
+ 1, 1, 4, 2, 0, 2, 1, 4, 2, 0, 4, 2, 1, 1, 1, 4, 3, 4, 1, 2, 0, 0, 2, 0,
+ 4, 2, 4, 3,
+ ])),
+ ],
+ )?;
+ let file_sort_order = vec![
+ col("a").sort(true, false),
+ col("b").sort(true, false),
+ col("c").sort(true, false),
+ ];
+ Ok((batch, file_sort_order))
+}
+
/// Creates a test_context with table name `annotated_data` which has 100 rows.
// Columns in the table are ts, inc_col, desc_col. Source is CsvExec which is ordered by
// ts column.
@@ -348,6 +399,18 @@ pub async fn get_test_context(
get_test_context_helper(tmpdir, infinite_source, session_config, get_test_data).await
}
+/// Creates a test_context with table name `annotated_data`, which has 100 rows.
+// Columns in the table are a,b,c,d. Source is CsvExec which is ordered by
+// a,b,c column. Column a has cardinality 2, column b has cardinality 4.
+// Column c has cardinality 100 (unique entries). Column d has cardinality 5.
+pub async fn get_test_context2(
+ tmpdir: &TempDir,
+ infinite_source: bool,
+ session_config: SessionConfig,
+) -> Result<SessionContext> {
+ get_test_context_helper(tmpdir, infinite_source, session_config, get_test_data2).await
+}
+
async fn get_test_context_helper(
tmpdir: &TempDir,
infinite_source: bool,
diff --git a/datafusion/core/tests/sql/window.rs b/datafusion/core/tests/sql/window.rs
index 5d0fb37991..7e7ed031f1 100644
--- a/datafusion/core/tests/sql/window.rs
+++ b/datafusion/core/tests/sql/window.rs
@@ -62,7 +62,7 @@ async fn window_frame_creation_type_checking() -> Result<()> {
mod tests {
use super::*;
- use datafusion::test_util::get_test_context;
+ use datafusion::test_util::{get_test_context, get_test_context2};
#[tokio::test]
async fn test_source_sorted_aggregate() -> Result<()> {
@@ -110,10 +110,11 @@ mod tests {
" GlobalLimitExec: skip=0, fetch=5",
" SortExec: fetch=5, expr=[inc_col@24 DESC]",
" ProjectionExec: expr=[SUM(annotated_data.inc_col) ORDER BY [annotated_data.ts ASC NULLS LAST] RANGE BETWEEN 10 PRECEDING AND 1 FOLLOWING@13 as sum1, SUM(annotated_data.desc_col) ORDER BY [annotated_data.ts ASC NULLS LAST] RANGE BETWEEN 5 PRECEDING AND 1 FOLLOWING@14 as sum2, SUM(annotated_data.inc_col) ORDER BY [annotated_data.ts ASC NULLS LAST] ROWS BETWEEN 1 PRECEDING AND 10 FOLLOWING@15 as sum3, MIN(annotated_data.inc_col) ORDER BY [annotated_data.ts ASC NULLS LAST] RANGE BETWEEN 10 PRECEDING AND 1 FOLLOWING@16 as min1, MIN(annotated_data.desc_col) ORDER BY [annotated_data.ts ASC NULLS LAST] RANGE BETWEEN 5 PRECEDING AND 1 FOLLOWING@17 as min2, MIN(annotated_data.inc_col) ORDER BY [annotated_data.ts ASC NULLS LAST] ROWS BETWEEN 1 PRECEDING AND 10 FOLLOWING@18 as min3, MAX(annotated_data.inc_col) ORDER BY [annotated_data.ts ASC NULLS LAST] RANGE BETWEEN 10 PRECEDING AND 1 FOLLOWING@19 as max1, MAX(annotated_data.desc_col) ORDER BY [annotated_data.ts ASC NULLS LAST] RANGE BETWEEN 5 PRECEDING AND 1 FOLLOWING@20 as max2, MAX(annotated_data.inc_col) ORDER BY [annotated_data.ts ASC NULLS LAST] ROWS BETWEEN 1 PRECEDING AND 10 FOLLOWING@21 as max3, COUNT(UInt8(1)) ORDER BY [annotated_data.ts ASC NULLS LAST] RANGE BETWEEN 4 PRECEDING AND 8 FOLLOWING@22 as cnt1, COUNT(UInt8(1)) ORDER BY [annotated_data.ts ASC NULLS LAST] ROWS BETWEEN 8 PRECEDING AND 1 FOLLOWING@23 as cnt2, SUM(annotated_data.inc_col) ORDER BY [annotated_data.ts DESC NULLS FIRST] RANGE BETWEEN 1 PRECEDING AND 4 FOLLOWING@2 as sumr1, SUM(annotated_data.desc_col) ORDER BY [annotated_data.ts DESC NULLS FIRST] RANGE BETWEEN 1 PRECEDING AND 8 FOLLOWING@3 as sumr2, SUM(annotated_data.desc_col) ORDER BY [annotated_data.ts DESC NULLS FIRST] ROWS BETWEEN 1 PRECEDING AND 5 FOLLOWING@4 as sumr3, MIN(annotated_data.inc_col) ORDER BY [annotated_data.ts DESC NULLS FIRST] RANGE BETWEEN 10 PRECEDING AND 1 FOLLOWING@5 as minr1, MIN(annotated_data.desc_col) ORDER BY [annotated_data.ts DESC NULLS FIRST] RANGE BETWEEN 5 PRECEDING AND 1 FOLLOWING@6 as minr2, MIN(annotated_data.inc_col) ORDER BY [annotated_data.ts DESC NULLS FIRST] ROWS BETWEEN 1 PRECEDING AND 10 FOLLOWING@7 as minr3, MAX(annotated_data.inc_col) ORDER BY [annotated_data.ts DESC NULLS FIRST] RANGE BETWEEN 10 PRECEDING AND 1 FOLLOWING@8 as maxr1, MAX(annotated_data.desc_col) ORDER BY [annotated_data.ts DESC NULLS FIRST] RANGE BETWEEN 5 PRECEDING AND 1 FOLLOWING@9 as maxr2, MAX(annotated_data.inc_col) ORDER BY [annotated_data.ts DESC NULLS FIRST] ROWS BETWEEN 1 PRECEDING AND 10 FOLLOWING@10 as maxr3, COUNT(UInt8(1)) ORDER BY [annotated_data.ts DESC NULLS FIRST] RANGE BETWEEN 6 PRECEDING AND 2 FOLLOWING@11 as cntr1, COUNT(UInt8(1)) ORDER BY [annotated_data.ts DESC NULLS FIRST] ROWS BETWEEN 8 PRECEDING AND 1 FOLLOWING@12 as cntr2, SUM(annotated_data.desc_col) ROWS BETWEEN 8 PRECEDING AND 1 FOLLOWING@24 as sum4, COUNT(UInt8(1)) ROWS BETWEEN 8 PRECEDING AND 1 FOLLOWING@25 as cnt3, inc_col@0 as inc_col]",
- " BoundedWindowAggExec: wdw=[SUM(annotated_data.desc_col): Ok(Field { name: \"SUM(annotated_data.desc_col)\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(8)), end_bound: Following(UInt64(1)) }, COUNT(UInt8(1)): Ok(Field { name: \"COUNT(UInt8(1))\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(8)), end_bound: Following(UInt64(1)) }]",
+ " BoundedWindowAggExec: wdw=[SUM(annotated_data.desc_col): Ok(Field { name: \"SUM(annotated_data.desc_col)\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(8)), end_bound: Following(UInt64(1)) }, COUNT(UInt8(1)): Ok(Field { name: \"COUNT(UInt8(1))\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(8)), end_bound: Following(UInt64(1)) }], mode=[Sorted]",
" ProjectionExec: expr=[inc_col@1 as inc_col, desc_col@2 as desc_col, SUM(annotated_data.inc_col) ORDER BY [annotated_data.ts DESC NULLS FIRST] RANGE BETWEEN 1 PRECEDING AND 4 FOLLOWING@3 as SUM(annotated_data.inc_col), SUM(annotated_data.desc_col) ORDER BY [annotated_data.ts DESC NULLS FIRST] RANGE BETWEEN 1 PRECEDING AND 8 FOLLOWING@4 as SUM(annotated_data.desc_col), SUM(annotated_data.desc_col) ORDER BY [annotated_data.ts DESC NULLS FIRST] ROWS BETWEEN 1 PRECEDING AND 5 FOLLOWING@5 as SUM(annotated_data.desc_col), MIN(annotated_data.inc_col) ORDER BY [annotated_data.ts DESC NULLS FIRST] RANGE BETWEEN 10 PRECEDING AND 1 FOLLOWING@6 as MIN(annotated_data.inc_col), MIN(annotated_data.desc_col) ORDER BY [annotated_data.ts DESC NULLS FIRST] RANGE BETWEEN 5 PRECEDING AND 1 FOLLOWING@7 as MIN(annotated_data.desc_col), MIN(annotated_data.inc_col) ORDER BY [annotated_data.ts DESC NULLS FIRST] ROWS BETWEEN 1 PRECEDING AND 10 FOLLOWING@8 as MIN(annotated_data.inc_col), MAX(annotated_data.inc_col) ORDER BY [annotated_data.ts DESC NULLS FIRST] RANGE BETWEEN 10 PRECEDING AND 1 FOLLOWING@9 as MAX(annotated_data.inc_col), MAX(annotated_data.desc_col) ORDER BY [annotated_data.ts DESC NULLS FIRST] RANGE BETWEEN 5 PRECEDING AND 1 FOLLOWING@10 as MAX(annotated_data.desc_col), MAX(annotated_data.inc_col) ORDER BY [annotated_data.ts DESC NULLS FIRST] ROWS BETWEEN 1 PRECEDING AND 10 FOLLOWING@11 as MAX(annotated_data.inc_col), COUNT(UInt8(1)) ORDER BY [annotated_data.ts DESC NULLS FIRST] RANGE BETWEEN 6 PRECEDING AND 2 FOLLOWING@12 as COUNT(UInt8(1)), COUNT(UInt8(1)) ORDER BY [annotated_data.ts DESC NULLS FIRST] ROWS BETWEEN 8 PRECEDING AND 1 FOLLOWING@13 as COUNT(UInt8(1)), SUM(annotated_data.inc_col) ORDER BY [annotated_data.ts ASC NULLS LAST] RANGE BETWEEN 10 PRECEDING AND 1 FOLLOWING@14 as SUM(annotated_data.inc_col), SUM(annotated_data.desc_col) ORDER BY [annotated_data.ts ASC NULLS LAST] RANGE BETWEEN 5 PRECEDING AND 1 FOLLOWING@15 as SUM(annotated_data.desc_col), SUM(annotated_data.inc_col) ORDER BY [annotated_data.ts ASC NULLS LAST] ROWS BETWEEN 1 PRECEDING AND 10 FOLLOWING@16 as SUM(annotated_data.inc_col), MIN(annotated_data.inc_col) ORDER BY [annotated_data.ts ASC NULLS LAST] RANGE BETWEEN 10 PRECEDING AND 1 FOLLOWING@17 as MIN(annotated_data.inc_col), MIN(annotated_data.desc_col) ORDER BY [annotated_data.ts ASC NULLS LAST] RANGE BETWEEN 5 PRECEDING AND 1 FOLLOWING@18 as MIN(annotated_data.desc_col), MIN(annotated_data.inc_col) ORDER BY [annotated_data.ts ASC NULLS LAST] ROWS BETWEEN 1 PRECEDING AND 10 FOLLOWING@19 as MIN(annotated_data.inc_col), MAX(annotated_data.inc_col) ORDER BY [annotated_data.ts ASC NULLS LAST] RANGE BETWEEN 10 PRECEDING AND 1 FOLLOWING@20 as MAX(annotated_data.inc_col), MAX(annotated_data.desc_col) ORDER BY [annotated_data.ts ASC NULLS LAST] RANGE BETWEEN 5 PRECEDING AND 1 FOLLOWING@21 as MAX(annotated_data.desc_col), MAX(annotated_data.inc_col) ORDER BY [annotated_data.ts ASC NULLS LAST] ROWS BETWEEN 1 PRECEDING AND 10 FOLLOWING@22 as MAX(annotated_data.inc_col), COUNT(UInt8(1)) ORDER BY [annotated_data.ts ASC NULLS LAST] RANGE BETWEEN 4 PRECEDING AND 8 FOLLOWING@23 as COUNT(UInt8(1)), COUNT(UInt8(1)) ORDER BY [annotated_data.ts ASC NULLS LAST] ROWS BETWEEN 8 PRECEDING AND 1 FOLLOWING@24 as COUNT(UInt8(1))]",
- " BoundedWindowAggExec: wdw=[SUM(annotated_data.inc_col): Ok(Field { name: \"SUM(annotated_data.inc_col)\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(10)), end_bound: Following(Int32(1)) }, SUM(annotated_data.desc_col): Ok(Field { name: \"SUM(annotated_data.desc_col)\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(5)), end_bound: Following(Int32(1)) }, SUM(annotated_data.inc_col): Ok(Field { name: \"SUM(annotated_data.inc_col)\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(1)), end_bound: Following(UInt64(10)) }, MIN(annotated_data.inc_col): Ok(Field { name: \"MIN(annotated_data.inc_col)\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(10)), end_bound: Following(Int32(1)) }, MIN(annotated_data.desc_col): Ok(Field { name: \"MIN(annotated_data.desc_col)\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(5)), end_bound: Following(Int32(1)) }, MIN(annotated_data.inc_col): Ok(Field { name: \"MIN(annotated_data.inc_col)\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(1)), end_bound: Following(UInt64(10)) }, MAX(annotated_data.inc_col): Ok(Field { name: \"MAX(annotated_data.inc_col)\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(10)), end_bound: Following(Int32(1)) }, MAX(annotated_data.desc_col): Ok(Field { name: \"MAX(annotated_data.desc_col)\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(5)), end_bound: Following(Int32(1)) }, MAX(annotated_data.inc_col): Ok(Field { name: \"MAX(annotated_data.inc_col)\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(1)), end_bound: Following(UInt64(10)) }, COUNT(UInt8(1)): Ok(Field { name: \"COUNT(UInt8(1))\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(4)), end_bound: Following(Int32(8)) }, COUNT(UInt8(1)): Ok(Field { name: \"COUNT(UInt8(1))\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(8)), end_bound: Following(UInt64(1)) }]",
- " BoundedWindowAggExec: wdw=[SUM(annotated_data.inc_col): Ok(Field { name: \"SUM(annotated_data.inc_col)\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(4)), end_bound: Following(Int32(1)) }, SUM(annotated_data.desc_col): Ok(Field { name: \"SUM(annotated_data.desc_col)\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(8)), end_bound: Following(Int32(1)) }, SUM(annotated_data.desc_col): Ok(Field { name: \"SUM(annotated_data.desc_col)\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(5)), end_bound: Following(UInt64(1)) }, MIN(annotated_data.inc_col): Ok(Field { name: \"MIN(annotated_data.inc_col)\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(1)), end_bound: Following(Int32(10)) }, MIN(annotated_data.desc_col): Ok(Field { name: \"MIN(annotated_data.desc_col)\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(1)), end_bound: Following(Int32(5)) }, MIN(annotated_data.inc_col): Ok(Field { name: \"MIN(annotated_data.inc_col)\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(10)), end_bound: Following(UInt64(1)) }, MAX(annotated_data.inc_col): Ok(Field { name: \"MAX(annotated_data.inc_col)\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(1)), end_bound: Following(Int32(10)) }, MAX(annotated_data.desc_col): Ok(Field { name: \"MAX(annotated_data.desc_col)\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(1)), end_bound: Following(Int32(5)) }, MAX(annotated_data.inc_col): Ok(Field { name: \"MAX(annotated_data.inc_col)\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(10)), end_bound: Following(UInt64(1)) }, COUNT(UInt8(1)): Ok(Field { name: \"COUNT(UInt8(1))\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(2)), end_bound: Following(Int32(6)) }, COUNT(UInt8(1)): Ok(Field { name: \"COUNT(UInt8(1))\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(1)), end_bound: Following(UInt64(8)) }]"]
+ " BoundedWindowAggExec: wdw=[SUM(annotated_data.inc_col): Ok(Field { name: \"SUM(annotated_data.inc_col)\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(10)), end_bound: Following(Int32(1)) }, SUM(annotated_data.desc_col): Ok(Field { name: \"SUM(annotated_data.desc_col)\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(5)), end_bound: Following(Int32(1)) }, SUM(annotated_data.inc_col): Ok(Field { name: \"SUM(annotated_data.inc_col)\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(1)), end_bound: Following(UInt64(10)) }, MIN(annotated_data.inc_col): Ok(Field { name: \"MIN(annotated_data.inc_col)\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(10)), end_bound: Following(Int32(1)) }, MIN(annotated_data.desc_col): Ok(Field { name: \"MIN(annotated_data.desc_col)\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(5)), end_bound: Following(Int32(1)) }, MIN(annotated_data.inc_col): Ok(Field { name: \"MIN(annotated_data.inc_col)\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(1)), end_bound: Following(UInt64(10)) }, MAX(annotated_data.inc_col): Ok(Field { name: \"MAX(annotated_data.inc_col)\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(10)), end_bound: Following(Int32(1)) }, MAX(annotated_data.desc_col): Ok(Field { name: \"MAX(annotated_data.desc_col)\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(5)), end_bound: Following(Int32(1)) }, MAX(annotated_data.inc_col): Ok(Field { name: \"MAX(annotated_data.inc_col)\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(1)), end_bound: Following(UInt64(10)) }, COUNT(UInt8(1)): Ok(Field { name: \"COUNT(UInt8(1))\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(4)), end_bound: Following(Int32(8)) }, COUNT(UInt8(1)): Ok(Field { name: \"COUNT(UInt8(1))\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(8)), end_bound: Following(UInt64(1)) }], mode=[Sorted]",
+ " BoundedWindowAggExec: wdw=[SUM(annotated_data.inc_col): Ok(Field { name: \"SUM(annotated_data.inc_col)\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(4)), end_bound: Following(Int32(1)) }, SUM(annotated_data.desc_col): Ok(Field { name: \"SUM(annotated_data.desc_col)\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(8)), end_bound: Following(Int32(1)) }, SUM(annotated_data.desc_col): Ok(Field { name: \"SUM(annotated_data.desc_col)\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(5)), end_bound: Following(UInt64(1)) }, MIN(annotated_data.inc_col): Ok(Field { name: \"MIN(annotated_data.inc_col)\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(1)), end_bound: Following(Int32(10)) }, MIN(annotated_data.desc_col): Ok(Field { name: \"MIN(annotated_data.desc_col)\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(1)), end_bound: Following(Int32(5)) }, MIN(annotated_data.inc_col): Ok(Field { name: \"MIN(annotated_data.inc_col)\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(10)), end_bound: Following(UInt64(1)) }, MAX(annotated_data.inc_col): Ok(Field { name: \"MAX(annotated_data.inc_col)\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(1)), end_bound: Following(Int32(10)) }, MAX(annotated_data.desc_col): Ok(Field { name: \"MAX(annotated_data.desc_col)\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(1)), end_bound: Following(Int32(5)) }, MAX(annotated_data.inc_col): Ok(Field { name: \"MAX(annotated_data.inc_col)\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(10)), end_bound: Following(UInt64(1)) }, COUNT(UInt8(1)): Ok(Field { name: \"COUNT(UInt8(1))\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(2)), end_bound: Following(Int32(6)) }, COUNT(UInt8(1)): Ok(Field { name: \"COUNT(UInt8(1))\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(1)), end_bound: Following(UInt64(8)) }], mode=[Sorted]",
+ ]
};
let actual: Vec<&str> = formatted.trim().lines().collect();
@@ -186,8 +187,8 @@ mod tests {
" GlobalLimitExec: skip=0, fetch=5",
" SortExec: fetch=5, expr=[ts@24 DESC]",
" ProjectionExec: expr=[FIRST_VALUE(annotated_data.inc_col) ORDER BY [annotated_data.ts ASC NULLS LAST] RANGE BETWEEN 10 PRECEDING AND 1 FOLLOWING@10 as fv1, FIRST_VALUE(annotated_data.inc_col) ORDER BY [annotated_data.ts ASC NULLS LAST] ROWS BETWEEN 10 PRECEDING AND 1 FOLLOWING@11 as fv2, LAST_VALUE(annotated_data.inc_col) ORDER BY [annotated_data.ts ASC NULLS LAST] RANGE BETWEEN 10 PRECEDING AND 1 FOLLOWING@12 as lv1, LAST_VALUE(annotated_data.inc_col) ORDER BY [annotated_data.ts ASC NULLS LAST] ROWS BETWEEN 10 PRECEDING AND 1 FOLLOWING@13 as lv2, NTH_VALUE(annotated_data.inc_col,Int64(5)) ORDER BY [annotated_data.ts ASC NULLS LAST] RANGE BETWEEN 10 PRECEDING AND 1 FOLLOWING@14 as nv1, NTH_VALUE(annotated_data.inc_col,Int64(5)) ORDER BY [annotated_data.ts ASC NULLS LAST] ROWS BETWEEN 10 PRECEDING AND 1 FOLLOWING@15 as nv2, ROW_NUMBER() ORDER BY [annotated_data.ts ASC NULLS LAST] RANGE BETWEEN 1 PRECEDING AND 10 FOLLOWING@16 as rn1, ROW_NUMBER() ORDER BY [annotated_data.ts ASC NULLS LAST] ROWS BETWEEN 10 PRECEDING AND 1 FOLLOWING@17 as rn2, RANK() ORDER BY [annotated_data.ts ASC NULLS LAST] RANGE BETWEEN 1 PRECEDING AND 10 FOLLOWING@18 as rank1, RANK() ORDER BY [annotated_data.ts ASC NULLS LAST] ROWS BETWEEN 10 PRECEDING AND 1 FOLLOWING@19 as rank2, DENSE_RANK() ORDER BY [annotated_data.ts ASC NULLS LAST] RANGE BETWEEN 1 PRECEDING AND 10 FOLLOWING@20 as dense_rank1, DENSE_RANK() ORDER BY [annotated_data.ts ASC NULLS LAST] ROWS BETWEEN 10 PRECEDING AND 1 FOLLOWING@21 as dense_rank2, LAG(annotated_data.inc_col,Int64(1),Int64(1001)) ORDER BY [annotated_data.ts ASC NULLS LAST] RANGE BETWEEN 1 PRECEDING AND 10 FOLLOWING@22 as lag1, LAG(annotated_data.inc_col,Int64(2),Int64(1002)) ORDER BY [annotated_data.ts ASC NULLS LAST] ROWS BETWEEN 10 PRECEDING AND 1 FOLLOWING@23 as lag2, LEAD(annotated_data.inc_col,Int64(-1),Int64(1001)) ORDER BY [annotated_data.ts ASC NULLS LAST] RANGE BETWEEN 1 PRECEDING AND 10 FOLLOWING@24 as lead1, LEAD(annotated_data.inc_col,Int64(4),Int64(1004)) ORDER BY [annotated_data.ts ASC NULLS LAST] ROWS BETWEEN 10 PRECEDING AND 1 FOLLOWING@25 as lead2, FIRST_VALUE(annotated_data.inc_col) ORDER BY [annotated_data.ts DESC NULLS FIRST] RANGE BETWEEN 10 PRECEDING AND 1 FOLLOWING@2 as fvr1, FIRST_VALUE(annotated_data.inc_col) ORDER BY [annotated_data.ts DESC NULLS FIRST] ROWS BETWEEN 10 PRECEDING AND 1 FOLLOWING@3 as fvr2, LAST_VALUE(annotated_data.inc_col) ORDER BY [annotated_data.ts DESC NULLS FIRST] RANGE BETWEEN 10 PRECEDING AND 1 FOLLOWING@4 as lvr1, LAST_VALUE(annotated_data.inc_col) ORDER BY [annotated_data.ts DESC NULLS FIRST] ROWS BETWEEN 10 PRECEDING AND 1 FOLLOWING@5 as lvr2, LAG(annotated_data.inc_col,Int64(1),Int64(1001)) ORDER BY [annotated_data.ts DESC NULLS FIRST] RANGE BETWEEN 1 PRECEDING AND 10 FOLLOWING@6 as lagr1, LAG(annotated_data.inc_col,Int64(2),Int64(1002)) ORDER BY [annotated_data.ts DESC NULLS FIRST] ROWS BETWEEN 10 PRECEDING AND 1 FOLLOWING@7 as lagr2, LEAD(annotated_data.inc_col,Int64(-1),Int64(1001)) ORDER BY [annotated_data.ts DESC NULLS FIRST] RANGE BETWEEN 1 PRECEDING AND 10 FOLLOWING@8 as leadr1, LEAD(annotated_data.inc_col,Int64(4),Int64(1004)) ORDER BY [annotated_data.ts DESC NULLS FIRST] ROWS BETWEEN 10 PRECEDING AND 1 FOLLOWING@9 as leadr2, ts@0 as ts]",
- " BoundedWindowAggExec: wdw=[FIRST_VALUE(annotated_data.inc_col): Ok(Field { name: \"FIRST_VALUE(annotated_data.inc_col)\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(10)), end_bound: Following(Int32(1)) }, FIRST_VALUE(annotated_data.inc_col): Ok(Field { name: \"FIRST_VALUE(annotated_data.inc_col)\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(10)), end_bound: Following(UInt64(1)) }, LAST_VALUE(annotated_data.inc_col): Ok(Field { name: \"LAST_VALUE(annotated_data.inc_col)\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(10)), end_bound: Following(Int32(1)) }, LAST_VALUE(annotated_data.inc_col): Ok(Field { name: \"LAST_VALUE(annotated_data.inc_col)\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(10)), end_bound: Following(UInt64(1)) }, NTH_VALUE(annotated_data.inc_col,Int64(5)): Ok(Field { name: \"NTH_VALUE(annotated_data.inc_col,Int64(5))\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(10)), end_bound: Following(Int32(1)) }, NTH_VALUE(annotated_data.inc_col,Int64(5)): Ok(Field { name: \"NTH_VALUE(annotated_data.inc_col,Int64(5))\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(10)), end_bound: Following(UInt64(1)) }, ROW_NUMBER(): Ok(Field { name: \"ROW_NUMBER()\", data_type: UInt64, nullable: false, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(1)), end_bound: Following(Int32(10)) }, ROW_NUMBER(): Ok(Field { name: \"ROW_NUMBER()\", data_type: UInt64, nullable: false, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(10)), end_bound: Following(UInt64(1)) }, RANK(): Ok(Field { name: \"RANK()\", data_type: UInt64, nullable: false, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(1)), end_bound: Following(Int32(10)) }, RANK(): Ok(Field { name: \"RANK()\", data_type: UInt64, nullable: false, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(10)), end_bound: Following(UInt64(1)) }, DENSE_RANK(): Ok(Field { name: \"DENSE_RANK()\", data_type: UInt64, nullable: false, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(1)), end_bound: Following(Int32(10)) }, DENSE_RANK(): Ok(Field { name: \"DENSE_RANK()\", data_type: UInt64, nullable: false, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(10)), end_bound: Following(UInt64(1)) }, LAG(annotated_data.inc_col,Int64(1),Int64(1001)): Ok(Field { name: \"LAG(annotated_data.inc_col,Int64(1),Int64(1001))\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(1)), end_bound: Following(Int32(10)) }, LAG(annotated_data.inc_col,Int64(2),Int64(1002)): Ok(Field { name: \"LAG(annotated_data.inc_col,Int64(2),Int64(1002))\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(10)), end_bound: Following(UInt64(1)) }, LEAD(annotated_data.inc_col,Int64(-1),Int64(1001)): Ok(Field { name: \"LEAD(annotated_data.inc_col,Int64(-1),Int64(1001))\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(1)), end_bound: Following(Int32(10)) }, LEAD(annotated_data.inc_col,Int64(4),Int64(1004)): Ok(Field { name: \"LEAD(annotated_data.inc_col,Int64(4),Int64(1004))\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(10)), end_bound: Following(UInt64(1)) }]",
- " BoundedWindowAggExec: wdw=[FIRST_VALUE(annotated_data.inc_col): Ok(Field { name: \"FIRST_VALUE(annotated_data.inc_col)\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(1)), end_bound: Following(Int32(10)) }, FIRST_VALUE(annotated_data.inc_col): Ok(Field { name: \"FIRST_VALUE(annotated_data.inc_col)\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(1)), end_bound: Following(UInt64(10)) }, LAST_VALUE(annotated_data.inc_col): Ok(Field { name: \"LAST_VALUE(annotated_data.inc_col)\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(1)), end_bound: Following(Int32(10)) }, LAST_VALUE(annotated_data.inc_col): Ok(Field { name: \"LAST_VALUE(annotated_data.inc_col)\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(1)), end_bound: Following(UInt64(10)) }, LAG(annotated_data.inc_col,Int64(1),Int64(1001)): Ok(Field { name: \"LAG(annotated_data.inc_col,Int64(1),Int64(1001))\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(10)), end_bound: Following(Int32(1)) }, LAG(annotated_data.inc_col,Int64(2),Int64(1002)): Ok(Field { name: \"LAG(annotated_data.inc_col,Int64(2),Int64(1002))\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(1)), end_bound: Following(UInt64(10)) }, LEAD(annotated_data.inc_col,Int64(-1),Int64(1001)): Ok(Field { name: \"LEAD(annotated_data.inc_col,Int64(-1),Int64(1001))\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(10)), end_bound: Following(Int32(1)) }, LEAD(annotated_data.inc_col,Int64(4),Int64(1004)): Ok(Field { name: \"LEAD(annotated_data.inc_col,Int64(4),Int64(1004))\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(1)), end_bound: Following(UInt64(10)) }]",
+ " BoundedWindowAggExec: wdw=[FIRST_VALUE(annotated_data.inc_col): Ok(Field { name: \"FIRST_VALUE(annotated_data.inc_col)\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(10)), end_bound: Following(Int32(1)) }, FIRST_VALUE(annotated_data.inc_col): Ok(Field { name: \"FIRST_VALUE(annotated_data.inc_col)\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(10)), end_bound: Following(UInt64(1)) }, LAST_VALUE(annotated_data.inc_col): Ok(Field { name: \"LAST_VALUE(annotated_data.inc_col)\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(10)), end_bound: Following(Int32(1)) }, LAST_VALUE(annotated_data.inc_col): Ok(Field { name: \"LAST_VALUE(annotated_data.inc_col)\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(10)), end_bound: Following(UInt64(1)) }, NTH_VALUE(annotated_data.inc_col,Int64(5)): Ok(Field { name: \"NTH_VALUE(annotated_data.inc_col,Int64(5))\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(10)), end_bound: Following(Int32(1)) }, NTH_VALUE(annotated_data.inc_col,Int64(5)): Ok(Field { name: \"NTH_VALUE(annotated_data.inc_col,Int64(5))\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(10)), end_bound: Following(UInt64(1)) }, ROW_NUMBER(): Ok(Field { name: \"ROW_NUMBER()\", data_type: UInt64, nullable: false, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(1)), end_bound: Following(Int32(10)) }, ROW_NUMBER(): Ok(Field { name: \"ROW_NUMBER()\", data_type: UInt64, nullable: false, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(10)), end_bound: Following(UInt64(1)) }, RANK(): Ok(Field { name: \"RANK()\", data_type: UInt64, nullable: false, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(1)), end_bound: Following(Int32(10)) }, RANK(): Ok(Field { name: \"RANK()\", data_type: UInt64, nullable: false, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(10)), end_bound: Following(UInt64(1)) }, DENSE_RANK(): Ok(Field { name: \"DENSE_RANK()\", data_type: UInt64, nullable: false, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(1)), end_bound: Following(Int32(10)) }, DENSE_RANK(): Ok(Field { name: \"DENSE_RANK()\", data_type: UInt64, nullable: false, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(10)), end_bound: Following(UInt64(1)) }, LAG(annotated_data.inc_col,Int64(1),Int64(1001)): Ok(Field { name: \"LAG(annotated_data.inc_col,Int64(1),Int64(1001))\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(1)), end_bound: Following(Int32(10)) }, LAG(annotated_data.inc_col,Int64(2),Int64(1002)): Ok(Field { name: \"LAG(annotated_data.inc_col,Int64(2),Int64(1002))\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(10)), end_bound: Following(UInt64(1)) }, LEAD(annotated_data.inc_col,Int64(-1),Int64(1001)): Ok(Field { name: \"LEAD(annotated_data.inc_col,Int64(-1),Int64(1001))\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(1)), end_bound: Following(Int32(10)) }, LEAD(annotated_data.inc_col,Int64(4),Int64(1004)): Ok(Field { name: \"LEAD(annotated_data.inc_col,Int64(4),Int64(1004))\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(10)), end_bound: Following(UInt64(1)) }], mode=[Sorted]",
+ " BoundedWindowAggExec: wdw=[FIRST_VALUE(annotated_data.inc_col): Ok(Field { name: \"FIRST_VALUE(annotated_data.inc_col)\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(1)), end_bound: Following(Int32(10)) }, FIRST_VALUE(annotated_data.inc_col): Ok(Field { name: \"FIRST_VALUE(annotated_data.inc_col)\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(1)), end_bound: Following(UInt64(10)) }, LAST_VALUE(annotated_data.inc_col): Ok(Field { name: \"LAST_VALUE(annotated_data.inc_col)\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(1)), end_bound: Following(Int32(10)) }, LAST_VALUE(annotated_data.inc_col): Ok(Field { name: \"LAST_VALUE(annotated_data.inc_col)\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(1)), end_bound: Following(UInt64(10)) }, LAG(annotated_data.inc_col,Int64(1),Int64(1001)): Ok(Field { name: \"LAG(annotated_data.inc_col,Int64(1),Int64(1001))\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(10)), end_bound: Following(Int32(1)) }, LAG(annotated_data.inc_col,Int64(2),Int64(1002)): Ok(Field { name: \"LAG(annotated_data.inc_col,Int64(2),Int64(1002))\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(1)), end_bound: Following(UInt64(10)) }, LEAD(annotated_data.inc_col,Int64(-1),Int64(1001)): Ok(Field { name: \"LEAD(annotated_data.inc_col,Int64(-1),Int64(1001))\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(10)), end_bound: Following(Int32(1)) }, LEAD(annotated_data.inc_col,Int64(4),Int64(1004)): Ok(Field { name: \"LEAD(annotated_data.inc_col,Int64(4),Int64(1004))\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(1)), end_bound: Following(UInt64(10)) }], mode=[Sorted]",
]
};
@@ -246,8 +247,8 @@ mod tests {
" GlobalLimitExec: skip=0, fetch=5",
" SortExec: fetch=5, expr=[inc_col@10 ASC NULLS LAST]",
" ProjectionExec: expr=[SUM(annotated_data.inc_col) ORDER BY [annotated_data.ts ASC NULLS LAST] RANGE BETWEEN UNBOUNDED PRECEDING AND 5 FOLLOWING@7 as sum1, SUM(annotated_data.inc_col) ORDER BY [annotated_data.ts DESC NULLS FIRST] RANGE BETWEEN 3 PRECEDING AND UNBOUNDED FOLLOWING@2 as sum2, MIN(annotated_data.inc_col) ORDER BY [annotated_data.ts ASC NULLS LAST] RANGE BETWEEN UNBOUNDED PRECEDING AND 5 FOLLOWING@8 as min1, MIN(annotated_data.inc_col) ORDER BY [annotated_data.ts DESC NULLS FIRST] RANGE BETWEEN 3 PRECEDING AND UNBOUNDED FOLLOWING@3 as min2, MAX(annotated_data.inc_col) ORDER BY [annotated_data.ts ASC NULLS LAST] RANGE BETWEEN UNBOUNDED PRECEDING AND 5 FOLLOWING@9 as max1, MAX(annotated_data.inc_col) ORDER BY [annotated_data.ts DESC NULLS FIRST] RANGE BETWEEN 3 PRECEDING AND UNBOUNDED FOLLOWING@4 as max2, COUNT(annotated_data.inc_col) ORDER BY [annotated_data.ts ASC NULLS LAST] RANGE BETWEEN UNBOUNDED PRECEDING AND 5 FOLLOWING@10 as count1, COUNT(annotated_data.inc_col) ORDER BY [annotated_data.ts DESC NULLS FIRST] RANGE BETWEEN 3 PRECEDING AND UNBOUNDED FOLLOWING@5 as count2, AVG(annotated_data.inc_col) ORDER BY [annotated_data.ts ASC NULLS LAST] RANGE BETWEEN UNBOUNDED PRECEDING AND 5 FOLLOWING@11 as avg1, AVG(annotated_data.inc_col) ORDER BY [annotated_data.ts DESC NULLS FIRST] RANGE BETWEEN 3 PRECEDING AND UNBOUNDED FOLLOWING@6 as avg2, inc_col@1 as inc_col]",
- " BoundedWindowAggExec: wdw=[SUM(annotated_data.inc_col): Ok(Field { name: \"SUM(annotated_data.inc_col)\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(NULL)), end_bound: Following(Int32(5)) }, MIN(annotated_data.inc_col): Ok(Field { name: \"MIN(annotated_data.inc_col)\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(NULL)), end_bound: Following(Int32(5)) }, MAX(annotated_data.inc_col): Ok(Field { name: \"MAX(annotated_data.inc_col)\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(NULL)), end_bound: Following(Int32(5)) }, COUNT(annotated_data.inc_col): Ok(Field { name: \"COUNT(annotated_data.inc_col)\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(NULL)), end_bound: Following(Int32(5)) }, AVG(annotated_data.inc_col): Ok(Field { name: \"AVG(annotated_data.inc_col)\", data_type: Float64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(NULL)), end_bound: Following(Int32(5)) }]",
- " BoundedWindowAggExec: wdw=[SUM(annotated_data.inc_col): Ok(Field { name: \"SUM(annotated_data.inc_col)\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(NULL)), end_bound: Following(Int32(3)) }, MIN(annotated_data.inc_col): Ok(Field { name: \"MIN(annotated_data.inc_col)\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(NULL)), end_bound: Following(Int32(3)) }, MAX(annotated_data.inc_col): Ok(Field { name: \"MAX(annotated_data.inc_col)\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(NULL)), end_bound: Following(Int32(3)) }, COUNT(annotated_data.inc_col): Ok(Field { name: \"COUNT(annotated_data.inc_col)\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(NULL)), end_bound: Following(Int32(3)) }, AVG(annotated_data.inc_col): Ok(Field { name: \"AVG(annotated_data.inc_col)\", data_type: Float64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(NULL)), end_bound: Following(Int32(3)) }]",
+ " BoundedWindowAggExec: wdw=[SUM(annotated_data.inc_col): Ok(Field { name: \"SUM(annotated_data.inc_col)\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(NULL)), end_bound: Following(Int32(5)) }, MIN(annotated_data.inc_col): Ok(Field { name: \"MIN(annotated_data.inc_col)\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(NULL)), end_bound: Following(Int32(5)) }, MAX(annotated_data.inc_col): Ok(Field { name: \"MAX(annotated_data.inc_col)\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(NULL)), end_bound: Following(Int32(5)) }, COUNT(annotated_data.inc_col): Ok(Field { name: \"COUNT(annotated_data.inc_col)\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(NULL)), end_bound: Following(Int32(5)) }, AVG(annotated_data.inc_col): Ok(Field { name: \"AVG(annotated_data.inc_col)\", data_type: Float64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(NULL)), end_bound: Following(Int32(5)) }], mode=[Sorted]",
+ " BoundedWindowAggExec: wdw=[SUM(annotated_data.inc_col): Ok(Field { name: \"SUM(annotated_data.inc_col)\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(NULL)), end_bound: Following(Int32(3)) }, MIN(annotated_data.inc_col): Ok(Field { name: \"MIN(annotated_data.inc_col)\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(NULL)), end_bound: Following(Int32(3)) }, MAX(annotated_data.inc_col): Ok(Field { name: \"MAX(annotated_data.inc_col)\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(NULL)), end_bound: Following(Int32(3)) }, COUNT(annotated_data.inc_col): Ok(Field { name: \"COUNT(annotated_data.inc_col)\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(NULL)), end_bound: Following(Int32(3)) }, AVG(annotated_data.inc_col): Ok(Field { name: \"AVG(annotated_data.inc_col)\", data_type: Float64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(NULL)), end_bound: Following(Int32(3)) }], mode=[Sorted]",
]
};
@@ -301,8 +302,8 @@ mod tests {
" GlobalLimitExec: skip=0, fetch=5",
" SortExec: fetch=5, expr=[inc_col@5 ASC NULLS LAST]",
" ProjectionExec: expr=[FIRST_VALUE(annotated_data.inc_col) ORDER BY [annotated_data.ts ASC NULLS LAST] ROWS BETWEEN UNBOUNDED PRECEDING AND 1 FOLLOWING@4 as first_value1, FIRST_VALUE(annotated_data.inc_col) ORDER BY [annotated_data.ts DESC NULLS FIRST] ROWS BETWEEN 3 PRECEDING AND UNBOUNDED FOLLOWING@2 as first_value2, LAST_VALUE(annotated_data.inc_col) ORDER BY [annotated_data.ts ASC NULLS LAST] ROWS BETWEEN UNBOUNDED PRECEDING AND 1 FOLLOWING@5 as last_value1, LAST_VALUE(annotated_data.inc_col) ORDER BY [annotated_data.ts DESC NULLS FIRST] ROWS BETWEEN 3 PRECEDING AND UNBOUNDED FOLLOWING@3 as last_value2, NTH_VALUE(annotated_data.inc_col,Int64(2)) ORDER BY [annotated_data.ts ASC NULLS LAST] ROWS BETWEEN UNBOUNDED PRECEDING AND 1 FOLLOWING@6 as nth_value1, inc_col@1 as inc_col]",
- " BoundedWindowAggExec: wdw=[FIRST_VALUE(annotated_data.inc_col): Ok(Field { name: \"FIRST_VALUE(annotated_data.inc_col)\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(NULL)), end_bound: Following(UInt64(1)) }, LAST_VALUE(annotated_data.inc_col): Ok(Field { name: \"LAST_VALUE(annotated_data.inc_col)\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(NULL)), end_bound: Following(UInt64(1)) }, NTH_VALUE(annotated_data.inc_col,Int64(2)): Ok(Field { name: \"NTH_VALUE(annotated_data.inc_col,Int64(2))\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(NULL)), end_bound: Following(UInt64(1)) }]",
- " BoundedWindowAggExec: wdw=[FIRST_VALUE(annotated_data.inc_col): Ok(Field { name: \"FIRST_VALUE(annotated_data.inc_col)\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(NULL)), end_bound: Following(UInt64(3)) }, LAST_VALUE(annotated_data.inc_col): Ok(Field { name: \"LAST_VALUE(annotated_data.inc_col)\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(NULL)), end_bound: Following(UInt64(3)) }]",
+ " BoundedWindowAggExec: wdw=[FIRST_VALUE(annotated_data.inc_col): Ok(Field { name: \"FIRST_VALUE(annotated_data.inc_col)\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(NULL)), end_bound: Following(UInt64(1)) }, LAST_VALUE(annotated_data.inc_col): Ok(Field { name: \"LAST_VALUE(annotated_data.inc_col)\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(NULL)), end_bound: Following(UInt64(1)) }, NTH_VALUE(annotated_data.inc_col,Int64(2)): Ok(Field { name: \"NTH_VALUE(annotated_data.inc_col,Int64(2))\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(NULL)), end_bound: Following(UInt64(1)) }], mode=[Sorted]",
+ " BoundedWindowAggExec: wdw=[FIRST_VALUE(annotated_data.inc_col): Ok(Field { name: \"FIRST_VALUE(annotated_data.inc_col)\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(NULL)), end_bound: Following(UInt64(3)) }, LAST_VALUE(annotated_data.inc_col): Ok(Field { name: \"LAST_VALUE(annotated_data.inc_col)\", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(NULL)), end_bound: Following(UInt64(3)) }], mode=[Sorted]",
]
};
@@ -355,8 +356,8 @@ mod tests {
"ProjectionExec: expr=[sum1@0 as sum1, sum2@1 as sum2, count1@2 as count1, count2@3 as count2]",
" GlobalLimitExec: skip=0, fetch=5",
" ProjectionExec: expr=[SUM(annotated_data.inc_col) ORDER BY [annotated_data.ts ASC NULLS LAST] ROWS BETWEEN UNBOUNDED PRECEDING AND 1 FOLLOWING@4 as sum1, SUM(annotated_data.inc_col) ORDER BY [annotated_data.ts DESC NULLS FIRST] ROWS BETWEEN 3 PRECEDING AND UNBOUNDED FOLLOWING@2 as sum2, COUNT(annotated_data.inc_col) ORDER BY [annotated_data.ts ASC NULLS LAST] ROWS BETWEEN UNBOUNDED PRECEDING AND 1 FOLLOWING@5 as count1, COUNT(annotated_data.inc_col) ORDER BY [annotated_data.ts DESC NULLS FIRST] ROWS BETWEEN 3 PRECEDING AND UNBOUNDED FOLLOWING@3 as count2, ts@0 as ts]",
- " BoundedWindowAggExec: wdw=[SUM(annotated_data.inc_col): Ok(Field { name: \"SUM(annotated_data.inc_col)\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(NULL)), end_bound: Following(UInt64(1)) }, COUNT(annotated_data.inc_col): Ok(Field { name: \"COUNT(annotated_data.inc_col)\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(NULL)), end_bound: Following(UInt64(1)) }]",
- " BoundedWindowAggExec: wdw=[SUM(annotated_data.inc_col): Ok(Field { name: \"SUM(annotated_data.inc_col)\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(NULL)), end_bound: Following(UInt64(3)) }, COUNT(annotated_data.inc_col): Ok(Field { name: \"COUNT(annotated_data.inc_col)\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(NULL)), end_bound: Following(UInt64(3)) }]",
+ " BoundedWindowAggExec: wdw=[SUM(annotated_data.inc_col): Ok(Field { name: \"SUM(annotated_data.inc_col)\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(NULL)), end_bound: Following(UInt64(1)) }, COUNT(annotated_data.inc_col): Ok(Field { name: \"COUNT(annotated_data.inc_col)\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(NULL)), end_bound: Following(UInt64(1)) }], mode=[Sorted]",
+ " BoundedWindowAggExec: wdw=[SUM(annotated_data.inc_col): Ok(Field { name: \"SUM(annotated_data.inc_col)\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(NULL)), end_bound: Following(UInt64(3)) }, COUNT(annotated_data.inc_col): Ok(Field { name: \"COUNT(annotated_data.inc_col)\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(NULL)), end_bound: Following(UInt64(3)) }], mode=[Sorted]",
]
};
@@ -383,4 +384,142 @@ mod tests {
assert_batches_eq!(expected, &actual);
Ok(())
}
+
+ #[tokio::test]
+ async fn test_infinite_source_partition_by() -> Result<()> {
+ let tmpdir = TempDir::new()?;
+ let session_config = SessionConfig::new().with_target_partitions(1);
+ // Source is ordered by a, b, c
+ let ctx = get_test_context2(&tmpdir, true, session_config).await?;
+
+ let sql = "SELECT a, b, c,
+ SUM(c) OVER(PARTITION BY a, d ORDER BY b, c ASC ROWS BETWEEN 2 PRECEDING AND 1 FOLLOWING) as sum1,
+ SUM(c) OVER(PARTITION BY a, d ORDER BY b, c ASC ROWS BETWEEN 1 FOLLOWING AND 5 FOLLOWING) as sum2,
+ SUM(c) OVER(PARTITION BY d ORDER BY a, b, c ASC ROWS BETWEEN 2 PRECEDING AND 1 FOLLOWING) as sum3,
+ SUM(c) OVER(PARTITION BY d ORDER BY a, b, c ASC ROWS BETWEEN 5 PRECEDING AND 1 PRECEDING) as sum4,
+ SUM(c) OVER(PARTITION BY a, b ORDER BY c ASC ROWS BETWEEN 2 PRECEDING AND 1 FOLLOWING) as sum5,
+ SUM(c) OVER(PARTITION BY a, b ORDER BY c ASC ROWS BETWEEN 5 PRECEDING AND 5 FOLLOWING) as sum6,
+ SUM(c) OVER(PARTITION BY b, a ORDER BY c ASC ROWS BETWEEN 2 PRECEDING AND 1 FOLLOWING) as sum7,
+ SUM(c) OVER(PARTITION BY b, a ORDER BY c ASC ROWS BETWEEN 5 PRECEDING AND 5 FOLLOWING) as sum8,
+ SUM(c) OVER(PARTITION BY a, b, d ORDER BY c ASC ROWS BETWEEN 2 PRECEDING AND 1 FOLLOWING) as sum9,
+ SUM(c) OVER(PARTITION BY a, b, d ORDER BY c ASC ROWS BETWEEN 5 PRECEDING AND CURRENT ROW) as sum10,
+ SUM(c) OVER(PARTITION BY b, a, d ORDER BY c ASC ROWS BETWEEN 2 PRECEDING AND 1 FOLLOWING) as sum11,
+ SUM(c) OVER(PARTITION BY b, a, d ORDER BY c ASC ROWS BETWEEN CURRENT ROW AND 1 FOLLOWING) as sum12
+ FROM annotated_data
+ LIMIT 5";
+
+ let msg = format!("Creating logical plan for '{sql}'");
+ let dataframe = ctx.sql(sql).await.expect(&msg);
+ let physical_plan = dataframe.create_physical_plan().await?;
+ let formatted = displayable(physical_plan.as_ref()).indent().to_string();
+ let expected = {
+ vec![
+ "ProjectionExec: expr=[a@0 as a, b@1 as b, c@2 as c, SUM(annotated_data.c) PARTITION BY [annotated_data.a, annotated_data.d] ORDER BY [annotated_data.b ASC NULLS LAST, annotated_data.c ASC NULLS LAST] ROWS BETWEEN 2 PRECEDING AND 1 FOLLOWING@8 as sum1, SUM(annotated_data.c) PARTITION BY [annotated_data.a, annotated_data.d] ORDER BY [annotated_data.b ASC NULLS LAST, annotated_data.c ASC NULLS LAST] ROWS BETWEEN 1 FOLLOWING AND 5 FOLLOWING@9 as sum2, SUM(annotated_data.c) PARTITION BY [annotated_data.d] ORDER BY [annotated_data.a ASC NULLS LAST, annotated_data.b ASC NULLS LAST, annotated_data.c ASC NULLS LAST] ROWS BETWEEN 2 PRECEDING AND 1 FOLLOWING@14 as sum3, SUM(annotated_data.c) PARTITION BY [annotated_data.d] ORDER BY [annotated_data.a ASC NULLS LAST, annotated_data.b ASC NULLS LAST, annotated_data.c ASC NULLS LAST] ROWS BETWEEN 5 PRECEDING AND 1 PRECEDING@15 as sum4, SUM(annotated_data.c) PARTITION BY [annotated_data.a, annotated_data.b] ORDER BY [annotated_data.c ASC NULLS LAST] ROWS BETWEEN 2 PRECEDING AND 1 FOLLOWING@4 as sum5, SUM(annotated_data.c) PARTITION BY [annotated_data.a, annotated_data.b] ORDER BY [annotated_data.c ASC NULLS LAST] ROWS BETWEEN 5 PRECEDING AND 5 FOLLOWING@5 as sum6, SUM(annotated_data.c) PARTITION BY [annotated_data.b, annotated_data.a] ORDER BY [annotated_data.c ASC NULLS LAST] ROWS BETWEEN 2 PRECEDING AND 1 FOLLOWING@10 as sum7, SUM(annotated_data.c) PARTITION BY [annotated_data.b, annotated_data.a] ORDER BY [annotated_data.c ASC NULLS LAST] ROWS BETWEEN 5 PRECEDING AND 5 FOLLOWING@11 as sum8, SUM(annotated_data.c) PARTITION BY [annotated_data.a, annotated_data.b, annotated_data.d] ORDER BY [annotated_data.c ASC NULLS LAST] ROWS BETWEEN 2 PRECEDING AND 1 FOLLOWING@6 as sum9, SUM(annotated_data.c) PARTITION BY [annotated_data.a, annotated_data.b, annotated_data.d] ORDER BY [annotated_data.c ASC NULLS LAST] ROWS BETWEEN 5 PRECEDING AND CURRENT ROW@7 as sum10, SUM(annotated_data.c) PARTITION BY [annotated_data.b, annotated_data.a, annotated_data.d] ORDER BY [annotated_data.c ASC NULLS LAST] ROWS BETWEEN 2 PRECEDING AND 1 FOLLOWING@12 as sum11, SUM(annotated_data.c) PARTITION BY [annotated_data.b, annotated_data.a, annotated_data.d] ORDER BY [annotated_data.c ASC NULLS LAST] ROWS BETWEEN CURRENT ROW AND 1 FOLLOWING@13 as sum12]",
+ " GlobalLimitExec: skip=0, fetch=5",
+ " BoundedWindowAggExec: wdw=[SUM(annotated_data.c): Ok(Field { name: \"SUM(annotated_data.c)\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(2)), end_bound: Following(UInt64(1)) }, SUM(annotated_data.c): Ok(Field { name: \"SUM(annotated_data.c)\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(5)), end_bound: Preceding(UInt64(1)) }], mode=[Linear]",
+ " BoundedWindowAggExec: wdw=[SUM(annotated_data.c): Ok(Field { name: \"SUM(annotated_data.c)\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(2)), end_bound: Following(UInt64(1)) }, SUM(annotated_data.c): Ok(Field { name: \"SUM(annotated_data.c)\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: CurrentRow, end_bound: Following(UInt64(1)) }], mode=[PartiallySorted([1, 0])]",
+ " BoundedWindowAggExec: wdw=[SUM(annotated_data.c): Ok(Field { name: \"SUM(annotated_data.c)\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(2)), end_bound: Following(UInt64(1)) }, SUM(annotated_data.c): Ok(Field { name: \"SUM(annotated_data.c)\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(5)), end_bound: Following(UInt64(5)) }], mode=[Sorted]",
+ " BoundedWindowAggExec: wdw=[SUM(annotated_data.c): Ok(Field { name: \"SUM(annotated_data.c)\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(2)), end_bound: Following(UInt64(1)) }, SUM(annotated_data.c): Ok(Field { name: \"SUM(annotated_data.c)\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Following(UInt64(1)), end_bound: Following(UInt64(5)) }], mode=[PartiallySorted([0])]",
+ " BoundedWindowAggExec: wdw=[SUM(annotated_data.c): Ok(Field { name: \"SUM(annotated_data.c)\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(2)), end_bound: Following(UInt64(1)) }, SUM(annotated_data.c): Ok(Field { name: \"SUM(annotated_data.c)\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(5)), end_bound: CurrentRow }], mode=[PartiallySorted([0, 1])]",
+ " BoundedWindowAggExec: wdw=[SUM(annotated_data.c): Ok(Field { name: \"SUM(annotated_data.c)\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(2)), end_bound: Following(UInt64(1)) }, SUM(annotated_data.c): Ok(Field { name: \"SUM(annotated_data.c)\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(5)), end_bound: Following(UInt64(5)) }], mode=[Sorted]",
+ ]
+ };
+
+ let actual: Vec<&str> = formatted.trim().lines().collect();
+ let actual_len = actual.len();
+ let actual_trim_last = &actual[..actual_len - 1];
+ assert_eq!(
+ expected, actual_trim_last,
+ "\n\nexpected:\n\n{expected:#?}\nactual:\n\n{actual:#?}\n\n"
+ );
+ let actual = execute_to_batches(&ctx, sql).await;
+
+ let expected = vec![
+ "+---+---+---+------+------+------+------+------+------+------+------+------+-------+-------+-------+",
+ "| a | b | c | sum1 | sum2 | sum3 | sum4 | sum5 | sum6 | sum7 | sum8 | sum9 | sum10 | sum11 | sum12 |",
+ "+---+---+---+------+------+------+------+------+------+------+------+------+-------+-------+-------+",
+ "| 0 | 0 | 0 | 2 | 53 | 2 | | 1 | 15 | 1 | 15 | 2 | 0 | 2 | 2 |",
+ "| 0 | 0 | 1 | 8 | 61 | 8 | | 3 | 21 | 3 | 21 | 8 | 1 | 8 | 8 |",
+ "| 0 | 0 | 2 | 5 | 74 | 5 | 0 | 6 | 28 | 6 | 28 | 5 | 2 | 5 | 5 |",
+ "| 0 | 0 | 3 | 11 | 96 | 11 | 2 | 10 | 36 | 10 | 36 | 11 | 5 | 11 | 9 |",
+ "| 0 | 0 | 4 | 9 | 72 | 9 | | 14 | 45 | 14 | 45 | 9 | 4 | 9 | 9 |",
+ "+---+---+---+------+------+------+------+------+------+------+------+------+-------+-------+-------+",
+ ];
+ assert_batches_eq!(expected, &actual);
+ Ok(())
+ }
+
+ #[tokio::test]
+ async fn test_finite_source_partition_by() -> Result<()> {
+ let tmpdir = TempDir::new()?;
+ let session_config = SessionConfig::new().with_target_partitions(1);
+ // Source is ordered by a, b, c
+ // Source is finite.
+ let ctx = get_test_context2(&tmpdir, false, session_config).await?;
+
+ let sql = "SELECT a, b, c,
+ SUM(c) OVER(PARTITION BY a, d ORDER BY b, c ASC ROWS BETWEEN 2 PRECEDING AND 1 FOLLOWING) as sum1,
+ SUM(c) OVER(PARTITION BY a, d ORDER BY b, c ASC ROWS BETWEEN 1 FOLLOWING AND 5 FOLLOWING) as sum2,
+ SUM(c) OVER(PARTITION BY d ORDER BY a, b, c ASC ROWS BETWEEN 2 PRECEDING AND 1 FOLLOWING) as sum3,
+ SUM(c) OVER(PARTITION BY d ORDER BY a, b, c ASC ROWS BETWEEN 5 PRECEDING AND 1 PRECEDING) as sum4,
+ SUM(c) OVER(PARTITION BY a, b ORDER BY c ASC ROWS BETWEEN 2 PRECEDING AND 1 FOLLOWING) as sum5,
+ SUM(c) OVER(PARTITION BY a, b ORDER BY c ASC ROWS BETWEEN 5 PRECEDING AND 5 FOLLOWING) as sum6,
+ SUM(c) OVER(PARTITION BY b, a ORDER BY c ASC ROWS BETWEEN 2 PRECEDING AND 1 FOLLOWING) as sum7,
+ SUM(c) OVER(PARTITION BY b, a ORDER BY c ASC ROWS BETWEEN 5 PRECEDING AND 5 FOLLOWING) as sum8,
+ SUM(c) OVER(PARTITION BY a, b, d ORDER BY c ASC ROWS BETWEEN 2 PRECEDING AND 1 FOLLOWING) as sum9,
+ SUM(c) OVER(PARTITION BY a, b, d ORDER BY c ASC ROWS BETWEEN 5 PRECEDING AND CURRENT ROW) as sum10,
+ SUM(c) OVER(PARTITION BY b, a, d ORDER BY c ASC ROWS BETWEEN 2 PRECEDING AND 1 FOLLOWING) as sum11,
+ SUM(c) OVER(PARTITION BY b, a, d ORDER BY c ASC ROWS BETWEEN CURRENT ROW AND 1 FOLLOWING) as sum12
+ FROM annotated_data
+ ORDER BY c
+ LIMIT 5";
+
+ let msg = format!("Creating logical plan for '{sql}'");
+ let dataframe = ctx.sql(sql).await.expect(&msg);
+ let physical_plan = dataframe.create_physical_plan().await?;
+ let formatted = displayable(physical_plan.as_ref()).indent().to_string();
+ // We should produce `BoundedWindowAggExec`s that only works in Sorted mode, since source is finite.
+ // To satisfy, requirements for Sorted mode. We should introduce `SortExec`s through physical plan.
+ let expected = {
+ vec![
+ "GlobalLimitExec: skip=0, fetch=5",
+ " SortExec: fetch=5, expr=[c@2 ASC NULLS LAST]",
+ " ProjectionExec: expr=[a@0 as a, b@1 as b, c@2 as c, SUM(annotated_data.c) PARTITION BY [annotated_data.a, annotated_data.d] ORDER BY [annotated_data.b ASC NULLS LAST, annotated_data.c ASC NULLS LAST] ROWS BETWEEN 2 PRECEDING AND 1 FOLLOWING@8 as sum1, SUM(annotated_data.c) PARTITION BY [annotated_data.a, annotated_data.d] ORDER BY [annotated_data.b ASC NULLS LAST, annotated_data.c ASC NULLS LAST] ROWS BETWEEN 1 FOLLOWING AND 5 FOLLOWING@9 as sum2, SUM(annotated_data.c) PARTITION BY [annotated_data.d] ORDER BY [annotated_data.a ASC NULLS LAST, annotated_data.b ASC NULLS LAST, annotated_data.c ASC NULLS LAST] ROWS BETWEEN 2 PRECEDING AND 1 FOLLOWING@14 as sum3, SUM(annotated_data.c) PARTITION BY [annotated_data.d] ORDER BY [annotated_data.a ASC NULLS LAST, annotated_data.b ASC NULLS LAST, annotated_data.c ASC NULLS LAST] ROWS BETWEEN 5 PRECEDING AND 1 PRECEDING@15 as sum4, SUM(annotated_data.c) PARTITION BY [annotated_data.a, annotated_data.b] ORDER BY [annotated_data.c ASC NULLS LAST] ROWS BETWEEN 2 PRECEDING AND 1 FOLLOWING@4 as sum5, SUM(annotated_data.c) PARTITION BY [annotated_data.a, annotated_data.b] ORDER BY [annotated_data.c ASC NULLS LAST] ROWS BETWEEN 5 PRECEDING AND 5 FOLLOWING@5 as sum6, SUM(annotated_data.c) PARTITION BY [annotated_data.b, annotated_data.a] ORDER BY [annotated_data.c ASC NULLS LAST] ROWS BETWEEN 2 PRECEDING AND 1 FOLLOWING@10 as sum7, SUM(annotated_data.c) PARTITION BY [annotated_data.b, annotated_data.a] ORDER BY [annotated_data.c ASC NULLS LAST] ROWS BETWEEN 5 PRECEDING AND 5 FOLLOWING@11 as sum8, SUM(annotated_data.c) PARTITION BY [annotated_data.a, annotated_data.b, annotated_data.d] ORDER BY [annotated_data.c ASC NULLS LAST] ROWS BETWEEN 2 PRECEDING AND 1 FOLLOWING@6 as sum9, SUM(annotated_data.c) PARTITION BY [annotated_data.a, annotated_data.b, annotated_data.d] ORDER BY [annotated_data.c ASC NULLS LAST] ROWS BETWEEN 5 PRECEDING AND CURRENT ROW@7 as sum10, SUM(annotated_data.c) PARTITION BY [annotated_data.b, annotated_data.a, annotated_data.d] ORDER BY [annotated_data.c ASC NULLS LAST] ROWS BETWEEN 2 PRECEDING AND 1 FOLLOWING@12 as sum11, SUM(annotated_data.c) PARTITION BY [annotated_data.b, annotated_data.a, annotated_data.d] ORDER BY [annotated_data.c ASC NULLS LAST] ROWS BETWEEN CURRENT ROW AND 1 FOLLOWING@13 as sum12]",
+ " BoundedWindowAggExec: wdw=[SUM(annotated_data.c): Ok(Field { name: \"SUM(annotated_data.c)\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(2)), end_bound: Following(UInt64(1)) }, SUM(annotated_data.c): Ok(Field { name: \"SUM(annotated_data.c)\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(5)), end_bound: Preceding(UInt64(1)) }], mode=[Sorted]",
+ " SortExec: expr=[d@3 ASC NULLS LAST,a@0 ASC NULLS LAST,b@1 ASC NULLS LAST,c@2 ASC NULLS LAST]",
+ " BoundedWindowAggExec: wdw=[SUM(annotated_data.c): Ok(Field { name: \"SUM(annotated_data.c)\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(2)), end_bound: Following(UInt64(1)) }, SUM(annotated_data.c): Ok(Field { name: \"SUM(annotated_data.c)\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: CurrentRow, end_bound: Following(UInt64(1)) }], mode=[Sorted]",
+ " SortExec: expr=[b@1 ASC NULLS LAST,a@0 ASC NULLS LAST,d@3 ASC NULLS LAST,c@2 ASC NULLS LAST]",
+ " BoundedWindowAggExec: wdw=[SUM(annotated_data.c): Ok(Field { name: \"SUM(annotated_data.c)\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(2)), end_bound: Following(UInt64(1)) }, SUM(annotated_data.c): Ok(Field { name: \"SUM(annotated_data.c)\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(5)), end_bound: Following(UInt64(5)) }], mode=[Sorted]",
+ " SortExec: expr=[b@1 ASC NULLS LAST,a@0 ASC NULLS LAST,c@2 ASC NULLS LAST]",
+ " BoundedWindowAggExec: wdw=[SUM(annotated_data.c): Ok(Field { name: \"SUM(annotated_data.c)\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(2)), end_bound: Following(UInt64(1)) }, SUM(annotated_data.c): Ok(Field { name: \"SUM(annotated_data.c)\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Following(UInt64(1)), end_bound: Following(UInt64(5)) }], mode=[Sorted]",
+ " SortExec: expr=[a@0 ASC NULLS LAST,d@3 ASC NULLS LAST,b@1 ASC NULLS LAST,c@2 ASC NULLS LAST]",
+ " BoundedWindowAggExec: wdw=[SUM(annotated_data.c): Ok(Field { name: \"SUM(annotated_data.c)\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(2)), end_bound: Following(UInt64(1)) }, SUM(annotated_data.c): Ok(Field { name: \"SUM(annotated_data.c)\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(5)), end_bound: CurrentRow }], mode=[Sorted]",
+ " SortExec: expr=[a@0 ASC NULLS LAST,b@1 ASC NULLS LAST,d@3 ASC NULLS LAST,c@2 ASC NULLS LAST]",
+ " BoundedWindowAggExec: wdw=[SUM(annotated_data.c): Ok(Field { name: \"SUM(annotated_data.c)\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(2)), end_bound: Following(UInt64(1)) }, SUM(annotated_data.c): Ok(Field { name: \"SUM(annotated_data.c)\", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(5)), end_bound: Following(UInt64(5)) }], mode=[Sorted]",
+ ]
+ };
+
+ let actual: Vec<&str> = formatted.trim().lines().collect();
+ let actual_len = actual.len();
+ let actual_trim_last = &actual[..actual_len - 1];
+ assert_eq!(
+ expected, actual_trim_last,
+ "\n\nexpected:\n\n{expected:#?}\nactual:\n\n{actual:#?}\n\n"
+ );
+ let actual = execute_to_batches(&ctx, sql).await;
+
+ let expected = vec![
+ "+---+---+---+------+------+------+------+------+------+------+------+------+-------+-------+-------+",
+ "| a | b | c | sum1 | sum2 | sum3 | sum4 | sum5 | sum6 | sum7 | sum8 | sum9 | sum10 | sum11 | sum12 |",
+ "+---+---+---+------+------+------+------+------+------+------+------+------+-------+-------+-------+",
+ "| 0 | 0 | 0 | 2 | 53 | 2 | | 1 | 15 | 1 | 15 | 2 | 0 | 2 | 2 |",
+ "| 0 | 0 | 1 | 8 | 61 | 8 | | 3 | 21 | 3 | 21 | 8 | 1 | 8 | 8 |",
+ "| 0 | 0 | 2 | 5 | 74 | 5 | 0 | 6 | 28 | 6 | 28 | 5 | 2 | 5 | 5 |",
+ "| 0 | 0 | 3 | 11 | 96 | 11 | 2 | 10 | 36 | 10 | 36 | 11 | 5 | 11 | 9 |",
+ "| 0 | 0 | 4 | 9 | 72 | 9 | | 14 | 45 | 14 | 45 | 9 | 4 | 9 | 9 |",
+ "+---+---+---+------+------+------+------+------+------+------+------+------+-------+-------+-------+",
+ ];
+ assert_batches_eq!(expected, &actual);
+ Ok(())
+ }
}
diff --git a/datafusion/core/tests/sqllogictests/test_files/window.slt b/datafusion/core/tests/sqllogictests/test_files/window.slt
index 04b1877e10..8b95005e1b 100644
--- a/datafusion/core/tests/sqllogictests/test_files/window.slt
+++ b/datafusion/core/tests/sqllogictests/test_files/window.slt
@@ -360,7 +360,7 @@ SortPreservingMergeExec: [b@0 ASC NULLS LAST]
ProjectionExec: expr=[b@0 as b, MAX(d.a)@1 as max_a, MAX(d.seq)@2 as MAX(d.seq)]
AggregateExec: mode=Single, gby=[b@2 as b], aggr=[MAX(d.a), MAX(d.seq)]
ProjectionExec: expr=[ROW_NUMBER() PARTITION BY [s.b] ORDER BY [s.a ASC NULLS LAST] RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW@2 as seq, a@0 as a, b@1 as b]
- BoundedWindowAggExec: wdw=[ROW_NUMBER(): Ok(Field { name: "ROW_NUMBER()", data_type: UInt64, nullable: false, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int64(NULL)), end_bound: CurrentRow }]
+ BoundedWindowAggExec: wdw=[ROW_NUMBER(): Ok(Field { name: "ROW_NUMBER()", data_type: UInt64, nullable: false, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int64(NULL)), end_bound: CurrentRow }], mode=[Sorted]
SortExec: expr=[b@1 ASC NULLS LAST,a@0 ASC NULLS LAST]
CoalesceBatchesExec: target_batch_size=8192
RepartitionExec: partitioning=Hash([Column { name: "b", index: 1 }], 4), input_partitions=4
@@ -1214,12 +1214,13 @@ Projection: aggregate_test_100.c9, SUM(aggregate_test_100.c9) ORDER BY [aggregat
TableScan: aggregate_test_100 projection=[c8, c9]
physical_plan
ProjectionExec: expr=[c9@0 as c9, SUM(aggregate_test_100.c9) ORDER BY [aggregate_test_100.c9 ASC NULLS LAST] RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW@2 as sum1, SUM(aggregate_test_100.c9) ORDER BY [aggregate_test_100.c9 ASC NULLS LAST, aggregate_test_100.c8 ASC NULLS LAST] RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW@1 as sum2]
- BoundedWindowAggExec: wdw=[SUM(aggregate_test_100.c9): Ok(Field { name: "SUM(aggregate_test_100.c9)", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(UInt64(NULL)), end_bound: CurrentRow }]
+ BoundedWindowAggExec: wdw=[SUM(aggregate_test_100.c9): Ok(Field { name: "SUM(aggregate_test_100.c9)", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(UInt64(NULL)), end_bound: CurrentRow }], mode=[Sorted]
ProjectionExec: expr=[c9@1 as c9, SUM(aggregate_test_100.c9) ORDER BY [aggregate_test_100.c9 ASC NULLS LAST, aggregate_test_100.c8 ASC NULLS LAST] RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW@2 as SUM(aggregate_test_100.c9)]
- BoundedWindowAggExec: wdw=[SUM(aggregate_test_100.c9): Ok(Field { name: "SUM(aggregate_test_100.c9)", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(UInt64(NULL)), end_bound: CurrentRow }]
+ BoundedWindowAggExec: wdw=[SUM(aggregate_test_100.c9): Ok(Field { name: "SUM(aggregate_test_100.c9)", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(UInt64(NULL)), end_bound: CurrentRow }], mode=[Sorted]
SortExec: expr=[c9@1 ASC NULLS LAST,c8@0 ASC NULLS LAST]
CsvExec: files={1 group: [[WORKSPACE_ROOT/testing/data/csv/aggregate_test_100.csv]]}, has_header=true, limit=None, projection=[c8, c9]
+
# over_order_by_sort_keys_sorting_prefix_compacting
# Only 1 SortExec was added
@@ -1235,11 +1236,12 @@ Projection: aggregate_test_100.c2, MAX(aggregate_test_100.c9) ORDER BY [aggregat
physical_plan
ProjectionExec: expr=[c2@0 as c2, MAX(aggregate_test_100.c9) ORDER BY [aggregate_test_100.c2 ASC NULLS LAST] RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW@3 as MAX(aggregate_test_100.c9), SUM(aggregate_test_100.c9) ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING@4 as SUM(aggregate_test_100.c9), MIN(aggregate_test_100.c9) ORDER BY [aggregate_test_100.c2 ASC NULLS LAST, aggregate_test_100.c9 ASC NULLS LAST] RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW@2 as MIN(aggregate_test_100.c9)]
WindowAggExec: wdw=[SUM(aggregate_test_100.c9): Ok(Field { name: "SUM(aggregate_test_100.c9)", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(NULL)), end_bound: Following(UInt64(NULL)) }]
- BoundedWindowAggExec: wdw=[MAX(aggregate_test_100.c9): Ok(Field { name: "MAX(aggregate_test_100.c9)", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int8(NULL)), end_bound: CurrentRow }]
- BoundedWindowAggExec: wdw=[MIN(aggregate_test_100.c9): Ok(Field { name: "MIN(aggregate_test_100.c9)", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int8(NULL)), end_bound: CurrentRow }]
+ BoundedWindowAggExec: wdw=[MAX(aggregate_test_100.c9): Ok(Field { name: "MAX(aggregate_test_100.c9)", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int8(NULL)), end_bound: CurrentRow }], mode=[Sorted]
+ BoundedWindowAggExec: wdw=[MIN(aggregate_test_100.c9): Ok(Field { name: "MIN(aggregate_test_100.c9)", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int8(NULL)), end_bound: CurrentRow }], mode=[Sorted]
SortExec: expr=[c2@0 ASC NULLS LAST,c9@1 ASC NULLS LAST]
CsvExec: files={1 group: [[WORKSPACE_ROOT/testing/data/csv/aggregate_test_100.csv]]}, has_header=true, limit=None, projection=[c2, c9]
+
# FIXME: for now we are not detecting prefix of sorting keys in order to re-arrange with global and save one SortExec
# over_order_by_sort_keys_sorting_global_order_compacting
@@ -1258,9 +1260,9 @@ physical_plan
SortExec: expr=[c2@0 ASC NULLS LAST]
ProjectionExec: expr=[c2@0 as c2, MAX(aggregate_test_100.c9) ORDER BY [aggregate_test_100.c9 ASC NULLS LAST, aggregate_test_100.c2 ASC NULLS LAST] RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW@3 as MAX(aggregate_test_100.c9), SUM(aggregate_test_100.c9) ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING@4 as SUM(aggregate_test_100.c9), MIN(aggregate_test_100.c9) ORDER BY [aggregate_test_100.c2 ASC NULLS LAST, aggregate_test_100.c9 ASC NULLS LAST] RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW@2 as MIN(aggregate_test_100.c9)]
WindowAggExec: wdw=[SUM(aggregate_test_100.c9): Ok(Field { name: "SUM(aggregate_test_100.c9)", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(NULL)), end_bound: Following(UInt64(NULL)) }]
- BoundedWindowAggExec: wdw=[MAX(aggregate_test_100.c9): Ok(Field { name: "MAX(aggregate_test_100.c9)", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(UInt64(NULL)), end_bound: CurrentRow }]
+ BoundedWindowAggExec: wdw=[MAX(aggregate_test_100.c9): Ok(Field { name: "MAX(aggregate_test_100.c9)", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(UInt64(NULL)), end_bound: CurrentRow }], mode=[Sorted]
SortExec: expr=[c9@1 ASC NULLS LAST,c2@0 ASC NULLS LAST]
- BoundedWindowAggExec: wdw=[MIN(aggregate_test_100.c9): Ok(Field { name: "MIN(aggregate_test_100.c9)", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int8(NULL)), end_bound: CurrentRow }]
+ BoundedWindowAggExec: wdw=[MIN(aggregate_test_100.c9): Ok(Field { name: "MIN(aggregate_test_100.c9)", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int8(NULL)), end_bound: CurrentRow }], mode=[Sorted]
SortExec: expr=[c2@0 ASC NULLS LAST,c9@1 ASC NULLS LAST]
CsvExec: files={1 group: [[WORKSPACE_ROOT/testing/data/csv/aggregate_test_100.csv]]}, has_header=true, limit=None, projection=[c2, c9]
@@ -1282,18 +1284,19 @@ Projection: SUM(aggregate_test_100.c4) PARTITION BY [aggregate_test_100.c1, aggr
TableScan: aggregate_test_100 projection=[c1, c2, c4]
physical_plan
ProjectionExec: expr=[SUM(aggregate_test_100.c4) PARTITION BY [aggregate_test_100.c1, aggregate_test_100.c2] ORDER BY [aggregate_test_100.c2 ASC NULLS LAST] ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING@2 as SUM(aggregate_test_100.c4), COUNT(UInt8(1)) PARTITION BY [aggregate_test_100.c1] ORDER BY [aggregate_test_100.c2 ASC NULLS LAST] ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING@3 as COUNT(UInt8(1))]
- BoundedWindowAggExec: wdw=[COUNT(UInt8(1)): Ok(Field { name: "COUNT(UInt8(1))", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(1)), end_bound: Following(UInt64(1)) }]
+ BoundedWindowAggExec: wdw=[COUNT(UInt8(1)): Ok(Field { name: "COUNT(UInt8(1))", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(1)), end_bound: Following(UInt64(1)) }], mode=[Sorted]
SortExec: expr=[c1@0 ASC NULLS LAST,c2@1 ASC NULLS LAST]
CoalesceBatchesExec: target_batch_size=4096
RepartitionExec: partitioning=Hash([Column { name: "c1", index: 0 }], 2), input_partitions=2
ProjectionExec: expr=[c1@0 as c1, c2@1 as c2, SUM(aggregate_test_100.c4) PARTITION BY [aggregate_test_100.c1, aggregate_test_100.c2] ORDER BY [aggregate_test_100.c2 ASC NULLS LAST] ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING@3 as SUM(aggregate_test_100.c4)]
- BoundedWindowAggExec: wdw=[SUM(aggregate_test_100.c4): Ok(Field { name: "SUM(aggregate_test_100.c4)", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(1)), end_bound: Following(UInt64(1)) }]
+ BoundedWindowAggExec: wdw=[SUM(aggregate_test_100.c4): Ok(Field { name: "SUM(aggregate_test_100.c4)", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(1)), end_bound: Following(UInt64(1)) }], mode=[Sorted]
SortExec: expr=[c1@0 ASC NULLS LAST,c2@1 ASC NULLS LAST]
CoalesceBatchesExec: target_batch_size=4096
RepartitionExec: partitioning=Hash([Column { name: "c1", index: 0 }, Column { name: "c2", index: 1 }], 2), input_partitions=2
RepartitionExec: partitioning=RoundRobinBatch(2), input_partitions=1
CsvExec: files={1 group: [[WORKSPACE_ROOT/testing/data/csv/aggregate_test_100.csv]]}, has_header=true, limit=None, projection=[c1, c2, c4]
+
# test_window_agg_sort_reversed_plan
# Only 1 SortExec was added
query TT
@@ -1313,8 +1316,8 @@ Projection: aggregate_test_100.c9, SUM(aggregate_test_100.c9) ORDER BY [aggregat
physical_plan
ProjectionExec: expr=[c9@0 as c9, SUM(aggregate_test_100.c9) ORDER BY [aggregate_test_100.c9 ASC NULLS LAST] ROWS BETWEEN 1 PRECEDING AND 5 FOLLOWING@2 as sum1, SUM(aggregate_test_100.c9) ORDER BY [aggregate_test_100.c9 DESC NULLS FIRST] ROWS BETWEEN 1 PRECEDING AND 5 FOLLOWING@1 as sum2]
GlobalLimitExec: skip=0, fetch=5
- BoundedWindowAggExec: wdw=[SUM(aggregate_test_100.c9): Ok(Field { name: "SUM(aggregate_test_100.c9)", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(5)), end_bound: Following(UInt64(1)) }]
- BoundedWindowAggExec: wdw=[SUM(aggregate_test_100.c9): Ok(Field { name: "SUM(aggregate_test_100.c9)", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(1)), end_bound: Following(UInt64(5)) }]
+ BoundedWindowAggExec: wdw=[SUM(aggregate_test_100.c9): Ok(Field { name: "SUM(aggregate_test_100.c9)", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(5)), end_bound: Following(UInt64(1)) }], mode=[Sorted]
+ BoundedWindowAggExec: wdw=[SUM(aggregate_test_100.c9): Ok(Field { name: "SUM(aggregate_test_100.c9)", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(1)), end_bound: Following(UInt64(5)) }], mode=[Sorted]
SortExec: expr=[c9@0 DESC]
CsvExec: files={1 group: [[WORKSPACE_ROOT/testing/data/csv/aggregate_test_100.csv]]}, has_header=true, limit=None, projection=[c9]
@@ -1354,8 +1357,8 @@ Projection: aggregate_test_100.c9, FIRST_VALUE(aggregate_test_100.c9) ORDER BY [
physical_plan
ProjectionExec: expr=[c9@0 as c9, FIRST_VALUE(aggregate_test_100.c9) ORDER BY [aggregate_test_100.c9 ASC NULLS LAST] ROWS BETWEEN 1 PRECEDING AND 5 FOLLOWING@4 as fv1, FIRST_VALUE(aggregate_test_100.c9) ORDER BY [aggregate_test_100.c9 DESC NULLS FIRST] ROWS BETWEEN 1 PRECEDING AND 5 FOLLOWING@1 as fv2, LAG(aggregate_test_100.c9,Int64(2),Int64(10101)) ORDER BY [aggregate_test_100.c9 ASC NULLS LAST] RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW@5 as lag1, LAG(aggregate_test_100.c9,Int64(2),Int64(10101)) ORDER BY [aggregate_test_100.c9 DESC NULLS FIRST] ROWS BETWEEN 10 PRECEDING AND 1 FOLLOWING@2 as lag2, LEAD(aggregate_test_100.c9,Int64(2),Int64(10101)) ORDER BY [aggregate_test_100.c9 ASC NULLS LAST] RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW@6 as lead1, LEAD(aggregate_test_100.c9,Int64(2),Int64(10101)) ORDER BY [aggregate_test_100.c9 DESC NULLS FIRST] ROWS BETWEEN 10 PRECEDING AND 1 FOLLOWING@3 as lead2]
GlobalLimitExec: skip=0, fetch=5
- BoundedWindowAggExec: wdw=[FIRST_VALUE(aggregate_test_100.c9): Ok(Field { name: "FIRST_VALUE(aggregate_test_100.c9)", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(5)), end_bound: Following(UInt64(1)) }, LAG(aggregate_test_100.c9,Int64(2),Int64(10101)): Ok(Field { name: "LAG(aggregate_test_100.c9,Int64(2),Int64(10101))", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: CurrentRow, end_bound: Following(UInt64(NULL)) }, LEAD(aggregate_test_100.c9,Int64(2),Int64(10101)): Ok(Field { name: "LEAD(aggregate_test_100.c9,Int64(2),Int64(10101))", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: CurrentRow, end_bound: Following(UInt64(NULL)) }]
- BoundedWindowAggExec: wdw=[FIRST_VALUE(aggregate_test_100.c9): Ok(Field { name: "FIRST_VALUE(aggregate_test_100.c9)", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(1)), end_bound: Following(UInt64(5)) }, LAG(aggregate_test_100.c9,Int64(2),Int64(10101)): Ok(Field { name: "LAG(aggregate_test_100.c9,Int64(2),Int64(10101))", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(10)), end_bound: Following(UInt64(1)) }, LEAD(aggregate_test_100.c9,Int64(2),Int64(10101)): Ok(Field { name: "LEAD(aggregate_test_100.c9,Int64(2),Int64(10101))", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(10)), end_bound: Following(UInt64(1)) }]
+ BoundedWindowAggExec: wdw=[FIRST_VALUE(aggregate_test_100.c9): Ok(Field { name: "FIRST_VALUE(aggregate_test_100.c9)", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(5)), end_bound: Following(UInt64(1)) }, LAG(aggregate_test_100.c9,Int64(2),Int64(10101)): Ok(Field { name: "LAG(aggregate_test_100.c9,Int64(2),Int64(10101))", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: CurrentRow, end_bound: Following(UInt64(NULL)) }, LEAD(aggregate_test_100.c9,Int64(2),Int64(10101)): Ok(Field { name: "LEAD(aggregate_test_100.c9,Int64(2),Int64(10101))", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: CurrentRow, end_bound: Following(UInt64(NULL)) }], mode=[Sorted]
+ BoundedWindowAggExec: wdw=[FIRST_VALUE(aggregate_test_100.c9): Ok(Field { name: "FIRST_VALUE(aggregate_test_100.c9)", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(1)), end_bound: Following(UInt64(5)) }, LAG(aggregate_test_100.c9,Int64(2),Int64(10101)): Ok(Field { name: "LAG(aggregate_test_100.c9,Int64(2),Int64(10101))", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(10)), end_bound: Following(UInt64(1)) }, LEAD(aggregate_test_100.c9,Int64(2),Int64(10101)): Ok(Field { name: "LEAD(aggregate_test_100.c9,Int64(2),Int64(10101))", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(10)), end_bound: Following(UInt64(1)) }], mode=[Sorted]
SortExec: expr=[c9@0 DESC]
CsvExec: files={1 group: [[WORKSPACE_ROOT/testing/data/csv/aggregate_test_100.csv]]}, has_header=true, limit=None, projection=[c9]
@@ -1397,9 +1400,9 @@ Projection: aggregate_test_100.c9, ROW_NUMBER() ORDER BY [aggregate_test_100.c9
physical_plan
ProjectionExec: expr=[c9@0 as c9, ROW_NUMBER() ORDER BY [aggregate_test_100.c9 ASC NULLS LAST] ROWS BETWEEN 1 PRECEDING AND 5 FOLLOWING@2 as rn1, ROW_NUMBER() ORDER BY [aggregate_test_100.c9 DESC NULLS FIRST] ROWS BETWEEN 1 PRECEDING AND 5 FOLLOWING@1 as rn2]
GlobalLimitExec: skip=0, fetch=5
- BoundedWindowAggExec: wdw=[ROW_NUMBER(): Ok(Field { name: "ROW_NUMBER()", data_type: UInt64, nullable: false, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(1)), end_bound: Following(UInt64(5)) }]
+ BoundedWindowAggExec: wdw=[ROW_NUMBER(): Ok(Field { name: "ROW_NUMBER()", data_type: UInt64, nullable: false, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(1)), end_bound: Following(UInt64(5)) }], mode=[Sorted]
SortExec: expr=[c9@0 ASC NULLS LAST]
- BoundedWindowAggExec: wdw=[ROW_NUMBER(): Ok(Field { name: "ROW_NUMBER()", data_type: UInt64, nullable: false, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(1)), end_bound: Following(UInt64(5)) }]
+ BoundedWindowAggExec: wdw=[ROW_NUMBER(): Ok(Field { name: "ROW_NUMBER()", data_type: UInt64, nullable: false, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(1)), end_bound: Following(UInt64(5)) }], mode=[Sorted]
SortExec: expr=[c9@0 DESC]
CsvExec: files={1 group: [[WORKSPACE_ROOT/testing/data/csv/aggregate_test_100.csv]]}, has_header=true, limit=None, projection=[c9]
@@ -1439,10 +1442,10 @@ Projection: aggregate_test_100.c9, SUM(aggregate_test_100.c9) ORDER BY [aggregat
physical_plan
ProjectionExec: expr=[c9@2 as c9, SUM(aggregate_test_100.c9) ORDER BY [aggregate_test_100.c9 ASC NULLS LAST, aggregate_test_100.c1 ASC NULLS LAST, aggregate_test_100.c2 ASC NULLS LAST] ROWS BETWEEN 1 PRECEDING AND 5 FOLLOWING@5 as sum1, SUM(aggregate_test_100.c9) ORDER BY [aggregate_test_100.c9 DESC NULLS FIRST, aggregate_test_100.c1 DESC NULLS FIRST] ROWS BETWEEN 1 PRECEDING AND 5 FOLLOWING@3 as sum2, ROW_NUMBER() ORDER BY [aggregate_test_100.c9 DESC NULLS FIRST] ROWS BETWEEN 1 PRECEDING AND 5 FOLLOWING@4 as rn2]
GlobalLimitExec: skip=0, fetch=5
- BoundedWindowAggExec: wdw=[SUM(aggregate_test_100.c9): Ok(Field { name: "SUM(aggregate_test_100.c9)", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(1)), end_bound: Following(UInt64(5)) }]
+ BoundedWindowAggExec: wdw=[SUM(aggregate_test_100.c9): Ok(Field { name: "SUM(aggregate_test_100.c9)", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(1)), end_bound: Following(UInt64(5)) }], mode=[Sorted]
SortExec: expr=[c9@2 ASC NULLS LAST,c1@0 ASC NULLS LAST,c2@1 ASC NULLS LAST]
- BoundedWindowAggExec: wdw=[ROW_NUMBER(): Ok(Field { name: "ROW_NUMBER()", data_type: UInt64, nullable: false, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(1)), end_bound: Following(UInt64(5)) }]
- BoundedWindowAggExec: wdw=[SUM(aggregate_test_100.c9): Ok(Field { name: "SUM(aggregate_test_100.c9)", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(1)), end_bound: Following(UInt64(5)) }]
+ BoundedWindowAggExec: wdw=[ROW_NUMBER(): Ok(Field { name: "ROW_NUMBER()", data_type: UInt64, nullable: false, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(1)), end_bound: Following(UInt64(5)) }], mode=[Sorted]
+ BoundedWindowAggExec: wdw=[SUM(aggregate_test_100.c9): Ok(Field { name: "SUM(aggregate_test_100.c9)", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(1)), end_bound: Following(UInt64(5)) }], mode=[Sorted]
SortExec: expr=[c9@2 DESC,c1@0 DESC]
CsvExec: files={1 group: [[WORKSPACE_ROOT/testing/data/csv/aggregate_test_100.csv]]}, has_header=true, limit=None, projection=[c1, c2, c9]
@@ -1523,17 +1526,17 @@ ProjectionExec: expr=[SUM(null_cases.c1) ORDER BY [null_cases.c3 ASC NULLS LAST]
GlobalLimitExec: skip=0, fetch=5
WindowAggExec: wdw=[SUM(null_cases.c1): Ok(Field { name: "SUM(null_cases.c1)", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int64(10)), end_bound: Following(Int64(11)) }, SUM(null_cases.c1): Ok(Field { name: "SUM(null_cases.c1)", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int64(NULL)), end_bound: CurrentRow }, SUM(null_cases.c1): Ok(Field { name: "SUM(null_cases.c1)", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int64(NULL)), end_bound: Following(Int64(11)) }, SUM(null_cases.c1): Ok(Field { name: "SUM(null_cases.c1)", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: CurrentRow, end_bound: Following(Int64(NULL)) }]
ProjectionExec: expr=[c1@0 as c1, c3@2 as c3, SUM(null_cases.c1) ORDER BY [null_cases.c3 DESC NULLS FIRST, null_cases.c1 ASC NULLS LAST] RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW@3 as SUM(null_cases.c1), SUM(null_cases.c1) ORDER BY [null_cases.c3 DESC NULLS FIRST] RANGE BETWEEN 10 PRECEDING AND 11 FOLLOWING@4 as SUM(null_cases.c1), SUM(null_cases.c1) ORDER BY [null_cases.c3 DESC NULLS FIRST] RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW@5 as SUM(null_cases.c1), SUM(null_cases.c1) ORDER BY [null_cases.c3 DESC NULLS FIRST] RANGE BETWEEN UNBOUNDED PRECEDING AND 11 FOLLOWING@6 as SUM(null_cases.c1), SUM(null_cases.c1) ORDER BY [null_cases.c3 DESC NULLS FIRST] RANGE BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING@7 as SUM(null_cases.c1), SUM(null_cases.c1) ORDER BY [null_cases.c3 DESC NULLS LAST] RANGE BETWEEN 10 PRECEDING AND 11 FOLLOWING@8 as SUM(null_cases.c1), SUM(null_cases.c1) ORDER BY [null_cases.c3 DESC NULLS LAST] RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW@9 as SUM(null_cases.c1), SUM(null_cases.c1) ORDER BY [null_cases.c3 DESC NULLS LAST] RANGE BETWEEN UNBOUNDED PRECEDING AND 11 FOLLOWING@10 as SUM(null_cases.c1), SUM(null_cases.c1) ORDER BY [null_cases.c3 DESC NULLS LAST] RANGE BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING@11 as SUM(null_cases.c1), SUM(null_cases.c1) ORDER BY [null_cases.c3 ASC NULLS FIRST] RANGE BETWEEN 10 PRECEDING AND 11 FOLLOWING@12 as SUM(null_cases.c1), SUM(null_cases.c1) ORDER BY [null_cases.c3 ASC NULLS FIRST] RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW@13 as SUM(null_cases.c1), SUM(null_cases.c1) ORDER BY [null_cases.c3 ASC NULLS FIRST] RANGE BETWEEN UNBOUNDED PRECEDING AND 11 FOLLOWING@14 as SUM(null_cases.c1), SUM(null_cases.c1) ORDER BY [null_cases.c3 ASC NULLS FIRST] RANGE BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING@15 as SUM(null_cases.c1), SUM(null_cases.c1) ORDER BY [null_cases.c3 ASC NULLS LAST, null_cases.c1 DESC NULLS FIRST] RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW@16 as SUM(null_cases.c1), SUM(null_cases.c1) ORDER BY [null_cases.c3 ASC NULLS LAST, null_cases.c1 ASC NULLS FIRST] RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW@17 as SUM(null_cases.c1), SUM(null_cases.c1) ORDER BY [null_cases.c3 ASC NULLS LAST, null_cases.c2 ASC NULLS LAST] RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW@18 as SUM(null_cases.c1)]
- BoundedWindowAggExec: wdw=[SUM(null_cases.c1): Ok(Field { name: "SUM(null_cases.c1)", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int64(NULL)), end_bound: CurrentRow }]
+ BoundedWindowAggExec: wdw=[SUM(null_cases.c1): Ok(Field { name: "SUM(null_cases.c1)", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int64(NULL)), end_bound: CurrentRow }], mode=[Sorted]
SortExec: expr=[c3@2 ASC NULLS LAST,c2@1 ASC NULLS LAST]
- BoundedWindowAggExec: wdw=[SUM(null_cases.c1): Ok(Field { name: "SUM(null_cases.c1)", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int64(NULL)), end_bound: CurrentRow }]
+ BoundedWindowAggExec: wdw=[SUM(null_cases.c1): Ok(Field { name: "SUM(null_cases.c1)", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int64(NULL)), end_bound: CurrentRow }], mode=[Sorted]
SortExec: expr=[c3@2 ASC NULLS LAST,c1@0 ASC]
- BoundedWindowAggExec: wdw=[SUM(null_cases.c1): Ok(Field { name: "SUM(null_cases.c1)", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int64(NULL)), end_bound: CurrentRow }]
+ BoundedWindowAggExec: wdw=[SUM(null_cases.c1): Ok(Field { name: "SUM(null_cases.c1)", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int64(NULL)), end_bound: CurrentRow }], mode=[Sorted]
SortExec: expr=[c3@2 ASC NULLS LAST,c1@0 DESC]
WindowAggExec: wdw=[SUM(null_cases.c1): Ok(Field { name: "SUM(null_cases.c1)", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int64(11)), end_bound: Following(Int64(10)) }, SUM(null_cases.c1): Ok(Field { name: "SUM(null_cases.c1)", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: CurrentRow, end_bound: Following(Int64(NULL)) }, SUM(null_cases.c1): Ok(Field { name: "SUM(null_cases.c1)", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int64(11)), end_bound: Following(Int64(NULL)) }, SUM(null_cases.c1): Ok(Field { name: "SUM(null_cases.c1)", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int64(NULL)), end_bound: CurrentRow }]
WindowAggExec: wdw=[SUM(null_cases.c1): Ok(Field { name: "SUM(null_cases.c1)", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int64(10)), end_bound: Following(Int64(11)) }, SUM(null_cases.c1): Ok(Field { name: "SUM(null_cases.c1)", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int64(NULL)), end_bound: CurrentRow }, SUM(null_cases.c1): Ok(Field { name: "SUM(null_cases.c1)", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int64(NULL)), end_bound: Following(Int64(11)) }, SUM(null_cases.c1): Ok(Field { name: "SUM(null_cases.c1)", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: CurrentRow, end_bound: Following(Int64(NULL)) }]
SortExec: expr=[c3@2 DESC NULLS LAST]
WindowAggExec: wdw=[SUM(null_cases.c1): Ok(Field { name: "SUM(null_cases.c1)", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int64(10)), end_bound: Following(Int64(11)) }, SUM(null_cases.c1): Ok(Field { name: "SUM(null_cases.c1)", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int64(NULL)), end_bound: CurrentRow }, SUM(null_cases.c1): Ok(Field { name: "SUM(null_cases.c1)", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int64(NULL)), end_bound: Following(Int64(11)) }, SUM(null_cases.c1): Ok(Field { name: "SUM(null_cases.c1)", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: CurrentRow, end_bound: Following(Int64(NULL)) }]
- BoundedWindowAggExec: wdw=[SUM(null_cases.c1): Ok(Field { name: "SUM(null_cases.c1)", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int64(NULL)), end_bound: CurrentRow }]
+ BoundedWindowAggExec: wdw=[SUM(null_cases.c1): Ok(Field { name: "SUM(null_cases.c1)", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int64(NULL)), end_bound: CurrentRow }], mode=[Sorted]
SortExec: expr=[c3@2 DESC,c1@0 ASC NULLS LAST]
CsvExec: files={1 group: [[WORKSPACE_ROOT/datafusion/core/tests/data/null_cases.csv]]}, has_header=true, limit=None, projection=[c1, c2, c3]
@@ -1607,8 +1610,8 @@ Projection: aggregate_test_100.c9, SUM(aggregate_test_100.c9) ORDER BY [aggregat
physical_plan
ProjectionExec: expr=[c9@1 as c9, SUM(aggregate_test_100.c9) ORDER BY [aggregate_test_100.c1 ASC NULLS LAST, aggregate_test_100.c9 DESC NULLS FIRST] ROWS BETWEEN 1 PRECEDING AND 5 FOLLOWING@2 as sum1, SUM(aggregate_test_100.c9) PARTITION BY [aggregate_test_100.c1] ORDER BY [aggregate_test_100.c9 DESC NULLS FIRST] ROWS BETWEEN 1 PRECEDING AND 5 FOLLOWING@3 as sum2]
GlobalLimitExec: skip=0, fetch=5
- BoundedWindowAggExec: wdw=[SUM(aggregate_test_100.c9): Ok(Field { name: "SUM(aggregate_test_100.c9)", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(1)), end_bound: Following(UInt64(5)) }]
- BoundedWindowAggExec: wdw=[SUM(aggregate_test_100.c9): Ok(Field { name: "SUM(aggregate_test_100.c9)", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(1)), end_bound: Following(UInt64(5)) }]
+ BoundedWindowAggExec: wdw=[SUM(aggregate_test_100.c9): Ok(Field { name: "SUM(aggregate_test_100.c9)", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(1)), end_bound: Following(UInt64(5)) }], mode=[Sorted]
+ BoundedWindowAggExec: wdw=[SUM(aggregate_test_100.c9): Ok(Field { name: "SUM(aggregate_test_100.c9)", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(1)), end_bound: Following(UInt64(5)) }], mode=[Sorted]
SortExec: expr=[c1@0 ASC NULLS LAST,c9@1 DESC]
CsvExec: files={1 group: [[WORKSPACE_ROOT/testing/data/csv/aggregate_test_100.csv]]}, has_header=true, limit=None, projection=[c1, c9]
@@ -1651,8 +1654,8 @@ Projection: aggregate_test_100.c9, SUM(aggregate_test_100.c9) PARTITION BY [aggr
physical_plan
ProjectionExec: expr=[c9@1 as c9, SUM(aggregate_test_100.c9) PARTITION BY [aggregate_test_100.c1] ORDER BY [aggregate_test_100.c9 ASC NULLS LAST] ROWS BETWEEN 1 PRECEDING AND 5 FOLLOWING@3 as sum1, SUM(aggregate_test_100.c9) PARTITION BY [aggregate_test_100.c1] ORDER BY [aggregate_test_100.c9 DESC NULLS FIRST] ROWS BETWEEN 1 PRECEDING AND 5 FOLLOWING@2 as sum2]
GlobalLimitExec: skip=0, fetch=5
- BoundedWindowAggExec: wdw=[SUM(aggregate_test_100.c9): Ok(Field { name: "SUM(aggregate_test_100.c9)", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(5)), end_bound: Following(UInt64(1)) }]
- BoundedWindowAggExec: wdw=[SUM(aggregate_test_100.c9): Ok(Field { name: "SUM(aggregate_test_100.c9)", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(1)), end_bound: Following(UInt64(5)) }]
+ BoundedWindowAggExec: wdw=[SUM(aggregate_test_100.c9): Ok(Field { name: "SUM(aggregate_test_100.c9)", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(5)), end_bound: Following(UInt64(1)) }], mode=[Sorted]
+ BoundedWindowAggExec: wdw=[SUM(aggregate_test_100.c9): Ok(Field { name: "SUM(aggregate_test_100.c9)", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(1)), end_bound: Following(UInt64(5)) }], mode=[Sorted]
SortExec: expr=[c1@0 ASC NULLS LAST,c9@1 DESC]
CsvExec: files={1 group: [[WORKSPACE_ROOT/testing/data/csv/aggregate_test_100.csv]]}, has_header=true, limit=None, projection=[c1, c9]
@@ -1698,10 +1701,11 @@ ProjectionExec: expr=[c3@0 as c3, SUM(aggregate_test_100.c9) ORDER BY [aggregate
GlobalLimitExec: skip=0, fetch=5
WindowAggExec: wdw=[SUM(aggregate_test_100.c9): Ok(Field { name: "SUM(aggregate_test_100.c9)", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: CurrentRow, end_bound: Following(Int16(NULL)) }]
ProjectionExec: expr=[c3@1 as c3, c4@2 as c4, c9@3 as c9, SUM(aggregate_test_100.c9) ORDER BY [aggregate_test_100.c3 + aggregate_test_100.c4 DESC NULLS FIRST, aggregate_test_100.c9 DESC NULLS FIRST, aggregate_test_100.c2 ASC NULLS LAST] RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW@4 as SUM(aggregate_test_100.c9)]
- BoundedWindowAggExec: wdw=[SUM(aggregate_test_100.c9): Ok(Field { name: "SUM(aggregate_test_100.c9)", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int16(NULL)), end_bound: CurrentRow }]
+ BoundedWindowAggExec: wdw=[SUM(aggregate_test_100.c9): Ok(Field { name: "SUM(aggregate_test_100.c9)", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int16(NULL)), end_bound: CurrentRow }], mode=[Sorted]
SortExec: expr=[c3@1 + c4@2 DESC,c9@3 DESC,c2@0 ASC NULLS LAST]
CsvExec: files={1 group: [[WORKSPACE_ROOT/testing/data/csv/aggregate_test_100.csv]]}, has_header=true, limit=None, projection=[c2, c3, c4, c9]
+
query III
SELECT c3,
SUM(c9) OVER(ORDER BY c3+c4 DESC, c9 DESC, c2 ASC) as sum1,
@@ -1791,17 +1795,18 @@ physical_plan
GlobalLimitExec: skip=0, fetch=5
SortPreservingMergeExec: [c3@0 ASC NULLS LAST]
ProjectionExec: expr=[c3@0 as c3, SUM(aggregate_test_100.c9) ORDER BY [aggregate_test_100.c3 DESC NULLS FIRST, aggregate_test_100.c9 DESC NULLS FIRST, aggregate_test_100.c2 ASC NULLS LAST] RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW@2 as sum1, SUM(aggregate_test_100.c9) PARTITION BY [aggregate_test_100.c3] ORDER BY [aggregate_test_100.c9 DESC NULLS FIRST] RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW@3 as sum2]
- BoundedWindowAggExec: wdw=[SUM(aggregate_test_100.c9): Ok(Field { name: "SUM(aggregate_test_100.c9)", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(UInt64(NULL)), end_bound: CurrentRow }]
+ BoundedWindowAggExec: wdw=[SUM(aggregate_test_100.c9): Ok(Field { name: "SUM(aggregate_test_100.c9)", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(UInt64(NULL)), end_bound: CurrentRow }], mode=[Sorted]
SortExec: expr=[c3@0 ASC NULLS LAST,c9@1 DESC]
CoalesceBatchesExec: target_batch_size=4096
RepartitionExec: partitioning=Hash([Column { name: "c3", index: 0 }], 2), input_partitions=2
RepartitionExec: partitioning=RoundRobinBatch(2), input_partitions=1
ProjectionExec: expr=[c3@1 as c3, c9@2 as c9, SUM(aggregate_test_100.c9) ORDER BY [aggregate_test_100.c3 DESC NULLS FIRST, aggregate_test_100.c9 DESC NULLS FIRST, aggregate_test_100.c2 ASC NULLS LAST] RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW@3 as SUM(aggregate_test_100.c9)]
- BoundedWindowAggExec: wdw=[SUM(aggregate_test_100.c9): Ok(Field { name: "SUM(aggregate_test_100.c9)", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int16(NULL)), end_bound: CurrentRow }]
+ BoundedWindowAggExec: wdw=[SUM(aggregate_test_100.c9): Ok(Field { name: "SUM(aggregate_test_100.c9)", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int16(NULL)), end_bound: CurrentRow }], mode=[Sorted]
SortExec: expr=[c3@1 DESC,c9@2 DESC,c2@0 ASC NULLS LAST]
CsvExec: files={1 group: [[WORKSPACE_ROOT/testing/data/csv/aggregate_test_100.csv]]}, has_header=true, limit=None, projection=[c2, c3, c9]
+
query III
SELECT c3,
SUM(c9) OVER(ORDER BY c3 DESC, c9 DESC, c2 ASC) as sum1,
@@ -1832,7 +1837,7 @@ Sort: aggregate_test_100.c1 ASC NULLS LAST
physical_plan
SortPreservingMergeExec: [c1@0 ASC NULLS LAST]
ProjectionExec: expr=[c1@0 as c1, ROW_NUMBER() PARTITION BY [aggregate_test_100.c1] ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING@1 as rn1]
- BoundedWindowAggExec: wdw=[ROW_NUMBER(): Ok(Field { name: "ROW_NUMBER()", data_type: UInt64, nullable: false, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(NULL)), end_bound: Following(UInt64(NULL)) }]
+ BoundedWindowAggExec: wdw=[ROW_NUMBER(): Ok(Field { name: "ROW_NUMBER()", data_type: UInt64, nullable: false, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(NULL)), end_bound: Following(UInt64(NULL)) }], mode=[Sorted]
SortExec: expr=[c1@0 ASC NULLS LAST]
CoalesceBatchesExec: target_batch_size=4096
RepartitionExec: partitioning=Hash([Column { name: "c1", index: 0 }], 2), input_partitions=2
@@ -1959,7 +1964,7 @@ physical_plan
SortExec: expr=[c1@0 ASC NULLS LAST]
CoalescePartitionsExec
ProjectionExec: expr=[c1@0 as c1, ROW_NUMBER() PARTITION BY [aggregate_test_100.c1] ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING@1 as rn1]
- BoundedWindowAggExec: wdw=[ROW_NUMBER(): Ok(Field { name: "ROW_NUMBER()", data_type: UInt64, nullable: false, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(NULL)), end_bound: Following(UInt64(NULL)) }]
+ BoundedWindowAggExec: wdw=[ROW_NUMBER(): Ok(Field { name: "ROW_NUMBER()", data_type: UInt64, nullable: false, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(NULL)), end_bound: Following(UInt64(NULL)) }], mode=[Sorted]
SortExec: expr=[c1@0 ASC NULLS LAST]
CoalesceBatchesExec: target_batch_size=4096
RepartitionExec: partitioning=Hash([Column { name: "c1", index: 0 }], 2), input_partitions=2
@@ -1985,10 +1990,10 @@ Sort: aggregate_test_100.c1 ASC NULLS LAST
physical_plan
SortExec: expr=[c1@0 ASC NULLS LAST]
ProjectionExec: expr=[c1@0 as c1, SUM(aggregate_test_100.c9) PARTITION BY [aggregate_test_100.c1] ORDER BY [aggregate_test_100.c9 ASC NULLS LAST] ROWS BETWEEN 1 PRECEDING AND 3 FOLLOWING@2 as sum1, SUM(aggregate_test_100.c9) ORDER BY [aggregate_test_100.c9 ASC NULLS LAST] ROWS BETWEEN 1 PRECEDING AND 5 FOLLOWING@3 as sum2]
- BoundedWindowAggExec: wdw=[SUM(aggregate_test_100.c9): Ok(Field { name: "SUM(aggregate_test_100.c9)", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(1)), end_bound: Following(UInt64(5)) }]
+ BoundedWindowAggExec: wdw=[SUM(aggregate_test_100.c9): Ok(Field { name: "SUM(aggregate_test_100.c9)", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(1)), end_bound: Following(UInt64(5)) }], mode=[Sorted]
SortPreservingMergeExec: [c9@1 ASC NULLS LAST]
SortExec: expr=[c9@1 ASC NULLS LAST]
- BoundedWindowAggExec: wdw=[SUM(aggregate_test_100.c9): Ok(Field { name: "SUM(aggregate_test_100.c9)", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(1)), end_bound: Following(UInt64(3)) }]
+ BoundedWindowAggExec: wdw=[SUM(aggregate_test_100.c9): Ok(Field { name: "SUM(aggregate_test_100.c9)", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(1)), end_bound: Following(UInt64(3)) }], mode=[Sorted]
SortExec: expr=[c1@0 ASC NULLS LAST,c9@1 ASC NULLS LAST]
CoalesceBatchesExec: target_batch_size=4096
RepartitionExec: partitioning=Hash([Column { name: "c1", index: 0 }], 2), input_partitions=2
@@ -2077,15 +2082,16 @@ physical_plan
GlobalLimitExec: skip=0, fetch=5
SortExec: fetch=5, expr=[c9@0 ASC NULLS LAST]
ProjectionExec: expr=[c9@2 as c9, SUM(aggregate_test_100.c9) PARTITION BY [aggregate_test_100.c1, aggregate_test_100.c2] ORDER BY [aggregate_test_100.c9 ASC NULLS LAST] ROWS BETWEEN 1 PRECEDING AND 5 FOLLOWING@4 as sum1, SUM(aggregate_test_100.c9) PARTITION BY [aggregate_test_100.c2, aggregate_test_100.c1] ORDER BY [aggregate_test_100.c9 ASC NULLS LAST] ROWS BETWEEN 1 PRECEDING AND 5 FOLLOWING@6 as sum2, SUM(aggregate_test_100.c9) PARTITION BY [aggregate_test_100.c1, aggregate_test_100.c2] ORDER BY [aggregate_test_100.c9 ASC NULLS LAST, aggregate_test_100.c8 ASC NULLS LAST] ROWS BETWEEN 1 PRECEDING AND UNBOUNDED FOLLOWING@3 as sum3, SUM(aggregate_test_100.c9) PARTITION BY [aggregate_test_100.c2, aggregate_test_100.c1] ORDER BY [aggregate_test_100.c9 ASC NULLS LAST, aggregate_test_100.c8 ASC NULLS LAST] ROWS BETWEEN 1 PRECEDING AND UNBOUNDED FOLLOWING@5 as sum4]
- BoundedWindowAggExec: wdw=[SUM(aggregate_test_100.c9): Ok(Field { name: "SUM(aggregate_test_100.c9)", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(1)), end_bound: Following(UInt64(5)) }]
+ BoundedWindowAggExec: wdw=[SUM(aggregate_test_100.c9): Ok(Field { name: "SUM(aggregate_test_100.c9)", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(1)), end_bound: Following(UInt64(5)) }], mode=[Sorted]
ProjectionExec: expr=[c1@0 as c1, c2@1 as c2, c9@3 as c9, SUM(aggregate_test_100.c9) PARTITION BY [aggregate_test_100.c1, aggregate_test_100.c2] ORDER BY [aggregate_test_100.c9 ASC NULLS LAST, aggregate_test_100.c8 ASC NULLS LAST] ROWS BETWEEN 1 PRECEDING AND UNBOUNDED FOLLOWING@4 as SUM(aggregate_test_100.c9), SUM(aggregate_test_100.c9) PARTITION BY [aggregate_test_100.c1, aggregate_test_100.c2] ORDER BY [aggregate_test_100.c9 ASC NULLS LAST] ROWS BETWEEN 1 PRECEDING AND 5 FOLLOWING@5 as SUM(aggregate_test_100.c9), SUM(aggregate_test_100.c9) PARTITION BY [aggregate_test_100.c2, aggregate_test_100.c1] ORDER BY [aggregate_test_100.c9 ASC NULLS LAST, aggregate_test_100.c8 ASC NULLS LAST] ROWS BETWEEN 1 PRECEDING AND UNBOUNDED FOLLOWING@6 as SUM(aggregate_test_100.c9)]
WindowAggExec: wdw=[SUM(aggregate_test_100.c9): Ok(Field { name: "SUM(aggregate_test_100.c9)", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(1)), end_bound: Following(UInt64(NULL)) }]
- BoundedWindowAggExec: wdw=[SUM(aggregate_test_100.c9): Ok(Field { name: "SUM(aggregate_test_100.c9)", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(1)), end_bound: Following(UInt64(5)) }]
+ BoundedWindowAggExec: wdw=[SUM(aggregate_test_100.c9): Ok(Field { name: "SUM(aggregate_test_100.c9)", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(1)), end_bound: Following(UInt64(5)) }], mode=[Sorted]
WindowAggExec: wdw=[SUM(aggregate_test_100.c9): Ok(Field { name: "SUM(aggregate_test_100.c9)", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(1)), end_bound: Following(UInt64(NULL)) }]
SortExec: expr=[c1@0 ASC NULLS LAST,c2@1 ASC NULLS LAST,c9@3 ASC NULLS LAST,c8@2 ASC NULLS LAST]
CsvExec: files={1 group: [[WORKSPACE_ROOT/testing/data/csv/aggregate_test_100.csv]]}, has_header=true, limit=None, projection=[c1, c2, c8, c9]
+
query IIIII
SELECT c9,
SUM(c9) OVER(PARTITION BY c1, c2 ORDER BY c9 ASC ROWS BETWEEN 1 PRECEDING AND 5 FOLLOWING) as sum1,
@@ -2132,18 +2138,19 @@ Projection: t1.c9, SUM(t1.c9) PARTITION BY [t1.c1, t1.c2] ORDER BY [t1.c9 ASC NU
physical_plan
ProjectionExec: expr=[c9@1 as c9, SUM(t1.c9) PARTITION BY [t1.c1, t1.c2] ORDER BY [t1.c9 ASC NULLS LAST] ROWS BETWEEN 1 PRECEDING AND 5 FOLLOWING@4 as sum1, SUM(t1.c9) PARTITION BY [t1.c2, t1.c1_alias] ORDER BY [t1.c9 ASC NULLS LAST] ROWS BETWEEN 1 PRECEDING AND 5 FOLLOWING@6 as sum2, SUM(t1.c9) PARTITION BY [t1.c1, t1.c2] ORDER BY [t1.c9 ASC NULLS LAST, t1.c8 ASC NULLS LAST] ROWS BETWEEN 1 PRECEDING AND UNBOUNDED FOLLOWING@3 as sum3, SUM(t1.c9) PARTITION BY [t1.c2, t1.c1_alias] ORDER BY [t1.c9 ASC NULLS LAST, t1.c8 ASC NULLS LAST] ROWS BETWEEN 1 PRECEDING AND UNBOUNDED FOLLOWING@5 as sum4]
GlobalLimitExec: skip=0, fetch=5
- BoundedWindowAggExec: wdw=[SUM(t1.c9): Ok(Field { name: "SUM(t1.c9)", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(1)), end_bound: Following(UInt64(5)) }]
+ BoundedWindowAggExec: wdw=[SUM(t1.c9): Ok(Field { name: "SUM(t1.c9)", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(1)), end_bound: Following(UInt64(5)) }], mode=[Sorted]
ProjectionExec: expr=[c2@0 as c2, c9@2 as c9, c1_alias@3 as c1_alias, SUM(t1.c9) PARTITION BY [t1.c1, t1.c2] ORDER BY [t1.c9 ASC NULLS LAST, t1.c8 ASC NULLS LAST] ROWS BETWEEN 1 PRECEDING AND UNBOUNDED FOLLOWING@4 as SUM(t1.c9), SUM(t1.c9) PARTITION BY [t1.c1, t1.c2] ORDER BY [t1.c9 ASC NULLS LAST] ROWS BETWEEN 1 PRECEDING AND 5 FOLLOWING@5 as SUM(t1.c9), SUM(t1.c9) PARTITION BY [t1.c2, t1.c1_alias] ORDER BY [t1.c9 ASC NULLS LAST, t1.c8 ASC NULLS LAST] ROWS BETWEEN 1 PRECEDING AND UNBOUNDED FOLLOWING@6 as SUM(t1.c9)]
WindowAggExec: wdw=[SUM(t1.c9): Ok(Field { name: "SUM(t1.c9)", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(1)), end_bound: Following(UInt64(NULL)) }]
SortExec: expr=[c2@0 ASC NULLS LAST,c1_alias@3 ASC NULLS LAST,c9@2 ASC NULLS LAST,c8@1 ASC NULLS LAST]
ProjectionExec: expr=[c2@1 as c2, c8@2 as c8, c9@3 as c9, c1_alias@4 as c1_alias, SUM(t1.c9) PARTITION BY [t1.c1, t1.c2] ORDER BY [t1.c9 ASC NULLS LAST, t1.c8 ASC NULLS LAST] ROWS BETWEEN 1 PRECEDING AND UNBOUNDED FOLLOWING@5 as SUM(t1.c9), SUM(t1.c9) PARTITION BY [t1.c1, t1.c2] ORDER BY [t1.c9 ASC NULLS LAST] ROWS BETWEEN 1 PRECEDING AND 5 FOLLOWING@6 as SUM(t1.c9)]
- BoundedWindowAggExec: wdw=[SUM(t1.c9): Ok(Field { name: "SUM(t1.c9)", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(1)), end_bound: Following(UInt64(5)) }]
+ BoundedWindowAggExec: wdw=[SUM(t1.c9): Ok(Field { name: "SUM(t1.c9)", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(1)), end_bound: Following(UInt64(5)) }], mode=[Sorted]
WindowAggExec: wdw=[SUM(t1.c9): Ok(Field { name: "SUM(t1.c9)", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(1)), end_bound: Following(UInt64(NULL)) }]
SortExec: expr=[c1@0 ASC NULLS LAST,c2@1 ASC NULLS LAST,c9@3 ASC NULLS LAST,c8@2 ASC NULLS LAST]
ProjectionExec: expr=[c1@0 as c1, c2@1 as c2, c8@2 as c8, c9@3 as c9, c1@0 as c1_alias]
CsvExec: files={1 group: [[WORKSPACE_ROOT/testing/data/csv/aggregate_test_100.csv]]}, has_header=true, limit=None, projection=[c1, c2, c8, c9]
+
query IIIII
SELECT c9,
SUM(c9) OVER(PARTITION BY c1, c2 ORDER BY c9 ASC ROWS BETWEEN 1 PRECEDING AND 5 FOLLOWING) as sum1,
@@ -2182,9 +2189,9 @@ ProjectionExec: expr=[sum1@0 as sum1, sum2@1 as sum2]
GlobalLimitExec: skip=0, fetch=5
SortExec: fetch=5, expr=[c9@2 ASC NULLS LAST]
ProjectionExec: expr=[SUM(aggregate_test_100.c12) ORDER BY [aggregate_test_100.c1 ASC NULLS LAST, aggregate_test_100.c2 ASC NULLS LAST] GROUPS BETWEEN 1 PRECEDING AND 1 FOLLOWING@3 as sum1, SUM(aggregate_test_100.c12) ORDER BY [aggregate_test_100.c1 ASC NULLS LAST] GROUPS BETWEEN 5 PRECEDING AND 3 PRECEDING@4 as sum2, c9@1 as c9]
- BoundedWindowAggExec: wdw=[SUM(aggregate_test_100.c12): Ok(Field { name: "SUM(aggregate_test_100.c12)", data_type: Float64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Groups, start_bound: Preceding(UInt64(5)), end_bound: Preceding(UInt64(3)) }]
+ BoundedWindowAggExec: wdw=[SUM(aggregate_test_100.c12): Ok(Field { name: "SUM(aggregate_test_100.c12)", data_type: Float64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Groups, start_bound: Preceding(UInt64(5)), end_bound: Preceding(UInt64(3)) }], mode=[Sorted]
ProjectionExec: expr=[c1@0 as c1, c9@2 as c9, c12@3 as c12, SUM(aggregate_test_100.c12) ORDER BY [aggregate_test_100.c1 ASC NULLS LAST, aggregate_test_100.c2 ASC NULLS LAST] GROUPS BETWEEN 1 PRECEDING AND 1 FOLLOWING@4 as SUM(aggregate_test_100.c12)]
- BoundedWindowAggExec: wdw=[SUM(aggregate_test_100.c12): Ok(Field { name: "SUM(aggregate_test_100.c12)", data_type: Float64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Groups, start_bound: Preceding(UInt64(1)), end_bound: Following(UInt64(1)) }]
+ BoundedWindowAggExec: wdw=[SUM(aggregate_test_100.c12): Ok(Field { name: "SUM(aggregate_test_100.c12)", data_type: Float64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Groups, start_bound: Preceding(UInt64(1)), end_bound: Following(UInt64(1)) }], mode=[Sorted]
SortExec: expr=[c1@0 ASC NULLS LAST,c2@1 ASC NULLS LAST]
CsvExec: files={1 group: [[WORKSPACE_ROOT/testing/data/csv/aggregate_test_100.csv]]}, has_header=true, limit=None, projection=[c1, c2, c9, c12]
diff --git a/datafusion/core/tests/window_fuzz.rs b/datafusion/core/tests/window_fuzz.rs
index 179bada53c..e8524304a3 100644
--- a/datafusion/core/tests/window_fuzz.rs
+++ b/datafusion/core/tests/window_fuzz.rs
@@ -26,18 +26,19 @@ use hashbrown::HashMap;
use rand::rngs::StdRng;
use rand::{Rng, SeedableRng};
-use datafusion::physical_plan::collect;
use datafusion::physical_plan::memory::MemoryExec;
+use datafusion::physical_plan::sorts::sort::SortExec;
use datafusion::physical_plan::windows::{
- create_window_expr, BoundedWindowAggExec, WindowAggExec,
+ create_window_expr, BoundedWindowAggExec, PartitionSearchMode, WindowAggExec,
};
+use datafusion::physical_plan::{collect, ExecutionPlan};
use datafusion_expr::{
AggregateFunction, BuiltInWindowFunction, WindowFrame, WindowFrameBound,
WindowFrameUnits, WindowFunction,
};
use datafusion::prelude::{SessionConfig, SessionContext};
-use datafusion_common::ScalarValue;
+use datafusion_common::{Result, ScalarValue};
use datafusion_physical_expr::expressions::{col, lit};
use datafusion_physical_expr::{PhysicalExpr, PhysicalSortExpr};
use test_utils::add_empty_batches;
@@ -45,57 +46,119 @@ use test_utils::add_empty_batches;
#[cfg(test)]
mod tests {
use super::*;
+ use datafusion::physical_plan::windows::PartitionSearchMode::{
+ Linear, PartiallySorted, Sorted,
+ };
- #[tokio::test(flavor = "multi_thread", worker_threads = 8)]
- async fn single_order_by_test() {
- let n = 100;
- let distincts = vec![1, 100];
- for distinct in distincts {
- let mut handles = Vec::new();
- for i in 0..n {
- let job = tokio::spawn(run_window_test(
- make_staggered_batches::<true>(1000, distinct, i),
- i,
- vec!["a"],
- vec![],
- ));
- handles.push(job);
- }
- for job in handles {
- job.await.unwrap();
- }
- }
- }
-
- #[tokio::test(flavor = "multi_thread", worker_threads = 8)]
- async fn order_by_with_partition_test() {
- let n = 100;
- let distincts = vec![1, 100];
- for distinct in distincts {
- // since we have sorted pairs (a,b) to not violate per partition soring
- // partition should be field a, order by should be field b
+ #[tokio::test(flavor = "multi_thread", worker_threads = 16)]
+ async fn window_bounded_window_random_comparison() -> Result<()> {
+ // make_staggered_batches gives result sorted according to a, b, c
+ // In the test cases first entry represents partition by columns
+ // Second entry represents order by columns.
+ // Third entry represents search mode.
+ // In sorted mode physical plans are in the form for WindowAggExec
+ //```
+ // WindowAggExec
+ // MemoryExec]
+ // ```
+ // and in the form for BoundedWindowAggExec
+ // ```
+ // BoundedWindowAggExec
+ // MemoryExec
+ // ```
+ // In Linear and PartiallySorted mode physical plans are in the form for WindowAggExec
+ //```
+ // WindowAggExec
+ // SortExec(required by window function)
+ // MemoryExec]
+ // ```
+ // and in the form for BoundedWindowAggExec
+ // ```
+ // BoundedWindowAggExec
+ // MemoryExec
+ // ```
+ let test_cases = vec![
+ (vec!["a"], vec!["a"], Sorted),
+ (vec!["a"], vec!["b"], Sorted),
+ (vec!["a"], vec!["a", "b"], Sorted),
+ (vec!["a"], vec!["b", "c"], Sorted),
+ (vec!["a"], vec!["a", "b", "c"], Sorted),
+ (vec!["b"], vec!["a"], Linear),
+ (vec!["b"], vec!["a", "b"], Linear),
+ (vec!["b"], vec!["a", "c"], Linear),
+ (vec!["b"], vec!["a", "b", "c"], Linear),
+ (vec!["c"], vec!["a"], Linear),
+ (vec!["c"], vec!["a", "b"], Linear),
+ (vec!["c"], vec!["a", "c"], Linear),
+ (vec!["c"], vec!["a", "b", "c"], Linear),
+ (vec!["b", "a"], vec!["a"], Sorted),
+ (vec!["b", "a"], vec!["b"], Sorted),
+ (vec!["b", "a"], vec!["c"], Sorted),
+ (vec!["b", "a"], vec!["a", "b"], Sorted),
+ (vec!["b", "a"], vec!["b", "c"], Sorted),
+ (vec!["b", "a"], vec!["a", "c"], Sorted),
+ (vec!["b", "a"], vec!["a", "b", "c"], Sorted),
+ (vec!["c", "b"], vec!["a"], Linear),
+ (vec!["c", "b"], vec!["a", "b"], Linear),
+ (vec!["c", "b"], vec!["a", "c"], Linear),
+ (vec!["c", "b"], vec!["a", "b", "c"], Linear),
+ (vec!["c", "a"], vec!["a"], PartiallySorted(vec![1])),
+ (vec!["c", "a"], vec!["b"], PartiallySorted(vec![1])),
+ (vec!["c", "a"], vec!["c"], PartiallySorted(vec![1])),
+ (vec!["c", "a"], vec!["a", "b"], PartiallySorted(vec![1])),
+ (vec!["c", "a"], vec!["b", "c"], PartiallySorted(vec![1])),
+ (vec!["c", "a"], vec!["a", "c"], PartiallySorted(vec![1])),
+ (
+ vec!["c", "a"],
+ vec!["a", "b", "c"],
+ PartiallySorted(vec![1]),
+ ),
+ (vec!["c", "b", "a"], vec!["a"], Sorted),
+ (vec!["c", "b", "a"], vec!["b"], Sorted),
+ (vec!["c", "b", "a"], vec!["c"], Sorted),
+ (vec!["c", "b", "a"], vec!["a", "b"], Sorted),
+ (vec!["c", "b", "a"], vec!["b", "c"], Sorted),
+ (vec!["c", "b", "a"], vec!["a", "c"], Sorted),
+ (vec!["c", "b", "a"], vec!["a", "b", "c"], Sorted),
+ ];
+ let n = 300;
+ let n_distincts = vec![10, 20];
+ for n_distinct in n_distincts {
let mut handles = Vec::new();
for i in 0..n {
+ let idx = i % test_cases.len();
+ let (pb_cols, ob_cols, search_mode) = test_cases[idx].clone();
let job = tokio::spawn(run_window_test(
- make_staggered_batches::<true>(1000, distinct, i),
- i,
- vec!["b"],
- vec!["a"],
+ make_staggered_batches::<true>(1000, n_distinct, i as u64),
+ i as u64,
+ pb_cols,
+ ob_cols,
+ search_mode,
));
handles.push(job);
}
for job in handles {
- job.await.unwrap();
+ job.await.unwrap()?;
}
}
+ Ok(())
}
}
fn get_random_function(
schema: &SchemaRef,
rng: &mut StdRng,
+ is_linear: bool,
) -> (WindowFunction, Vec<Arc<dyn PhysicalExpr>>, String) {
- let mut args = vec![col("x", schema).unwrap()];
+ let mut args = if is_linear {
+ // In linear test for the test version with WindowAggExec we use insert SortExecs to the plan to be able to generate
+ // same result with BoundedWindowAggExec which doesn't use any SortExec. To make result
+ // non-dependent on table order. We should use column a in the window function
+ // (Given that we do not use ROWS for the window frame. ROWS also introduces dependency to the table order.).
+ vec![col("a", schema).unwrap()]
+ } else {
+ vec![col("x", schema).unwrap()]
+ };
let mut window_fn_map = HashMap::new();
// HashMap values consists of tuple first element is WindowFunction, second is additional argument
// window function requires if any. For most of the window functions additional argument is empty
@@ -127,20 +190,45 @@ fn get_random_function(
vec![],
),
);
- window_fn_map.insert(
- "row_number",
- (
- WindowFunction::BuiltInWindowFunction(BuiltInWindowFunction::RowNumber),
- vec![],
- ),
- );
- window_fn_map.insert(
- "rank",
- (
- WindowFunction::BuiltInWindowFunction(BuiltInWindowFunction::Rank),
- vec![],
- ),
- );
+ if !is_linear {
+ // row_number, rank, lead, lag doesn't use its window frame to calculate result. Their results are calculated
+ // according to table scan order. This adds the dependency to table order. Hence do not use these functions in
+ // Partition by linear test.
+ window_fn_map.insert(
+ "row_number",
+ (
+ WindowFunction::BuiltInWindowFunction(BuiltInWindowFunction::RowNumber),
+ vec![],
+ ),
+ );
+ window_fn_map.insert(
+ "rank",
+ (
+ WindowFunction::BuiltInWindowFunction(BuiltInWindowFunction::Rank),
+ vec![],
+ ),
+ );
+ window_fn_map.insert(
+ "lead",
+ (
+ WindowFunction::BuiltInWindowFunction(BuiltInWindowFunction::Lead),
+ vec![
+ lit(ScalarValue::Int64(Some(rng.gen_range(1..10)))),
+ lit(ScalarValue::Int64(Some(rng.gen_range(1..1000)))),
+ ],
+ ),
+ );
+ window_fn_map.insert(
+ "lag",
+ (
+ WindowFunction::BuiltInWindowFunction(BuiltInWindowFunction::Lag),
+ vec![
+ lit(ScalarValue::Int64(Some(rng.gen_range(1..10)))),
+ lit(ScalarValue::Int64(Some(rng.gen_range(1..1000)))),
+ ],
+ ),
+ );
+ }
window_fn_map.insert(
"first_value",
(
@@ -162,26 +250,6 @@ fn get_random_function(
vec![lit(ScalarValue::Int64(Some(rng.gen_range(1..10))))],
),
);
- window_fn_map.insert(
- "lead",
- (
- WindowFunction::BuiltInWindowFunction(BuiltInWindowFunction::Lead),
- vec![
- lit(ScalarValue::Int64(Some(rng.gen_range(1..10)))),
- lit(ScalarValue::Int64(Some(rng.gen_range(1..1000)))),
- ],
- ),
- );
- window_fn_map.insert(
- "lag",
- (
- WindowFunction::BuiltInWindowFunction(BuiltInWindowFunction::Lag),
- vec![
- lit(ScalarValue::Int64(Some(rng.gen_range(1..10)))),
- lit(ScalarValue::Int64(Some(rng.gen_range(1..1000)))),
- ],
- ),
- );
let rand_fn_idx = rng.gen_range(0..window_fn_map.len());
let fn_name = window_fn_map.keys().collect::<Vec<_>>()[rand_fn_idx];
@@ -193,17 +261,17 @@ fn get_random_function(
(window_fn.clone(), args, fn_name.to_string())
}
-fn get_random_window_frame(rng: &mut StdRng) -> WindowFrame {
+fn get_random_window_frame(rng: &mut StdRng, is_linear: bool) -> WindowFrame {
struct Utils {
val: i32,
is_preceding: bool,
}
let first_bound = Utils {
- val: rng.gen_range(0..50),
+ val: rng.gen_range(0..10),
is_preceding: rng.gen_range(0..2) == 0,
};
let second_bound = Utils {
- val: rng.gen_range(0..50),
+ val: rng.gen_range(0..10),
is_preceding: rng.gen_range(0..2) == 0,
};
let (start_bound, end_bound) =
@@ -225,7 +293,15 @@ fn get_random_window_frame(rng: &mut StdRng) -> WindowFrame {
let units = if rand_num < 1 {
WindowFrameUnits::Range
} else if rand_num < 2 {
- WindowFrameUnits::Rows
+ if is_linear {
+ // In linear test we sort data for WindowAggExec
+ // However, we do not sort data for BoundedWindowExec
+ // Since sorting is unstable, to make sure final result are comparable after sorting
+ // We shouldn't use Rows. This would add dependency to the table order.
+ WindowFrameUnits::Range
+ } else {
+ WindowFrameUnits::Rows
+ }
} else {
WindowFrameUnits::Groups
};
@@ -296,25 +372,27 @@ fn get_random_window_frame(rng: &mut StdRng) -> WindowFrame {
async fn run_window_test(
input1: Vec<RecordBatch>,
random_seed: u64,
- orderby_columns: Vec<&str>,
partition_by_columns: Vec<&str>,
-) {
+ orderby_columns: Vec<&str>,
+ search_mode: PartitionSearchMode,
+) -> Result<()> {
+ let is_linear = !matches!(search_mode, PartitionSearchMode::Sorted);
let mut rng = StdRng::seed_from_u64(random_seed);
let schema = input1[0].schema();
let session_config = SessionConfig::new().with_batch_size(50);
let ctx = SessionContext::with_config(session_config);
- let (window_fn, args, fn_name) = get_random_function(&schema, &mut rng);
+ let (window_fn, args, fn_name) = get_random_function(&schema, &mut rng, is_linear);
- let window_frame = get_random_window_frame(&mut rng);
+ let window_frame = get_random_window_frame(&mut rng, is_linear);
let mut orderby_exprs = vec![];
- for column in orderby_columns {
+ for column in &orderby_columns {
orderby_exprs.push(PhysicalSortExpr {
expr: col(column, &schema).unwrap(),
options: SortOptions::default(),
})
}
let mut partitionby_exprs = vec![];
- for column in partition_by_columns {
+ for column in &partition_by_columns {
partitionby_exprs.push(col(column, &schema).unwrap());
}
let mut sort_keys = vec![];
@@ -325,15 +403,35 @@ async fn run_window_test(
})
}
for order_by_expr in &orderby_exprs {
- sort_keys.push(order_by_expr.clone())
+ if !sort_keys.contains(order_by_expr) {
+ sort_keys.push(order_by_expr.clone())
+ }
}
let concat_input_record = concat_batches(&schema, &input1).unwrap();
- let exec1 = Arc::new(
- MemoryExec::try_new(&[vec![concat_input_record]], schema.clone(), None)
- .unwrap()
- .with_sort_information(sort_keys.clone()),
- );
+ let source_sort_keys = vec![
+ PhysicalSortExpr {
+ expr: col("a", &schema)?,
+ options: Default::default(),
+ },
+ PhysicalSortExpr {
+ expr: col("b", &schema)?,
+ options: Default::default(),
+ },
+ PhysicalSortExpr {
+ expr: col("c", &schema)?,
+ options: Default::default(),
+ },
+ ];
+ let memory_exec =
+ MemoryExec::try_new(&[vec![concat_input_record]], schema.clone(), None).unwrap();
+ let memory_exec = memory_exec.with_sort_information(source_sort_keys.clone());
+ let mut exec1 = Arc::new(memory_exec) as Arc<dyn ExecutionPlan>;
+ // Table is ordered according to ORDER BY a, b, c In linear test we use PARTITION BY b, ORDER BY a
+ // For WindowAggExec to produce correct result it need table to be ordered by b,a. Hence add a sort.
+ if is_linear {
+ exec1 = Arc::new(SortExec::new(sort_keys.clone(), exec1)) as _;
+ }
let usual_window_exec = Arc::new(
WindowAggExec::try_new(
vec![create_window_expr(
@@ -351,11 +449,11 @@ async fn run_window_test(
vec![],
)
.unwrap(),
- );
+ ) as _;
let exec2 = Arc::new(
MemoryExec::try_new(&[input1.clone()], schema.clone(), None)
.unwrap()
- .with_sort_information(sort_keys),
+ .with_sort_information(source_sort_keys.clone()),
);
let running_window_exec = Arc::new(
BoundedWindowAggExec::try_new(
@@ -372,10 +470,10 @@ async fn run_window_test(
exec2,
schema.clone(),
vec![],
+ search_mode,
)
.unwrap(),
- );
-
+ ) as Arc<dyn ExecutionPlan>;
let task_ctx = ctx.task_ctx();
let collected_usual = collect(usual_window_exec, task_ctx.clone()).await.unwrap();
@@ -405,41 +503,41 @@ async fn run_window_test(
"Inconsistent result for window_frame: {window_frame:?}, window_fn: {window_fn:?}, args:{args:?}"
);
}
+ Ok(())
}
/// Return randomly sized record batches with:
-/// two sorted int32 columns 'a', 'b' ranged from 0..len / DISTINCT as columns
-/// two random int32 columns 'x', 'y' as other columns
+/// three sorted int32 columns 'a', 'b', 'c' ranged from 0..DISTINCT as columns
+/// one random int32 column x
fn make_staggered_batches<const STREAM: bool>(
len: usize,
- distinct: usize,
+ n_distinct: usize,
random_seed: u64,
) -> Vec<RecordBatch> {
// use a random number generator to pick a random sized output
let mut rng = StdRng::seed_from_u64(random_seed);
- let mut input12: Vec<(i32, i32)> = vec![(0, 0); len];
- let mut input3: Vec<i32> = vec![0; len];
+ let mut input123: Vec<(i32, i32, i32)> = vec![(0, 0, 0); len];
let mut input4: Vec<i32> = vec![0; len];
- input12.iter_mut().for_each(|v| {
+ input123.iter_mut().for_each(|v| {
*v = (
- rng.gen_range(0..(len / distinct)) as i32,
- rng.gen_range(0..(len / distinct)) as i32,
+ rng.gen_range(0..n_distinct) as i32,
+ rng.gen_range(0..n_distinct) as i32,
+ rng.gen_range(0..n_distinct) as i32,
)
});
- rng.fill(&mut input3[..]);
+ input123.sort();
rng.fill(&mut input4[..]);
- input12.sort();
- let input1 = Int32Array::from_iter_values(input12.clone().into_iter().map(|k| k.0));
- let input2 = Int32Array::from_iter_values(input12.clone().into_iter().map(|k| k.1));
- let input3 = Int32Array::from_iter_values(input3.into_iter());
+ let input1 = Int32Array::from_iter_values(input123.iter().map(|k| k.0));
+ let input2 = Int32Array::from_iter_values(input123.iter().map(|k| k.1));
+ let input3 = Int32Array::from_iter_values(input123.iter().map(|k| k.2));
let input4 = Int32Array::from_iter_values(input4.into_iter());
// split into several record batches
let mut remainder = RecordBatch::try_from_iter(vec![
("a", Arc::new(input1) as ArrayRef),
("b", Arc::new(input2) as ArrayRef),
- ("x", Arc::new(input3) as ArrayRef),
- ("y", Arc::new(input4) as ArrayRef),
+ ("c", Arc::new(input3) as ArrayRef),
+ ("x", Arc::new(input4) as ArrayRef),
])
.unwrap();
diff --git a/datafusion/physical-expr/src/window/window_expr.rs b/datafusion/physical-expr/src/window/window_expr.rs
index 45e6f46ef0..140ce67f4a 100644
--- a/datafusion/physical-expr/src/window/window_expr.rs
+++ b/datafusion/physical-expr/src/window/window_expr.rs
@@ -400,6 +400,8 @@ pub struct PartitionBatchState {
pub record_batch: RecordBatch,
/// Flag indicating whether we have received all data for this partition
pub is_end: bool,
+ /// Number of rows emitted for each partition
+ pub n_out_row: usize,
}
/// Key for IndexMap for each unique partition