1use std::cmp::Ordering;
8use std::collections::{BTreeSet, HashSet};
9use std::sync::Arc;
10
11use crate::expr::{Alias, Sort, WildcardOptions, WindowFunctionParams};
12use crate::expr_rewriter::strip_outer_reference;
13use crate::{
14 BinaryExpr, Expr, ExprSchemable, Filter, GroupingSet, LogicalPlan, Operator, and,
15};
16use datafusion_expr_common::signature::{Signature, TypeSignature};
17
18use arrow::datatypes::{DataType, Field, FieldRef, Schema};
19use datafusion_common::tree_node::{
20 Transformed, TransformedResult, TreeNode, TreeNodeRecursion,
21};
22use datafusion_common::utils::get_at_indices;
23use datafusion_common::{
24 Column, DFSchema, DFSchemaRef, DataFusionError, Diagnostic, HashMap, Result, Span,
25 TableReference, internal_err, plan_datafusion_err, plan_err,
26};
27
28#[cfg(not(feature = "sql"))]
29use crate::sql::{ExceptSelectItem, ExcludeSelectItem, Ident, ObjectName};
30use indexmap::IndexSet;
31#[cfg(feature = "sql")]
32use sqlparser::ast::{ExceptSelectItem, ExcludeSelectItem, Ident, ObjectName};
33
34pub use datafusion_functions_aggregate_common::order::AggregateOrderSensitivity;
35
36pub use datafusion_common::utils::expr::COUNT_STAR_EXPANSION;
39
40pub fn grouping_set_expr_count(group_expr: &[Expr]) -> Result<usize> {
43 if let Some(Expr::GroupingSet(grouping_set)) = group_expr.first() {
44 if group_expr.len() > 1 {
45 return plan_err!(
46 "Invalid group by expressions, GroupingSet must be the only expression"
47 );
48 }
49 Ok(grouping_set.distinct_expr().len() + 1)
51 } else {
52 grouping_set_to_exprlist(group_expr).map(|exprs| exprs.len())
53 }
54}
55
56fn powerset_indices(len: usize) -> impl Iterator<Item = Vec<usize>> {
60 (0..(1 << len)).map(move |mask: u64| {
61 let mut indices = Vec::with_capacity(mask.count_ones() as usize);
62 let mut bitset = mask;
63 while bitset > 0 {
64 let rightmost: u64 = bitset & !(bitset - 1);
65 let idx = rightmost.trailing_zeros() as usize;
66 indices.push(idx);
67 bitset &= bitset - 1;
68 }
69 indices
70 })
71}
72
73pub fn powerset<T>(slice: &[T]) -> Result<Vec<Vec<&T>>> {
91 if slice.len() >= 64 {
92 return plan_err!("The size of the set must be less than 64");
93 }
94
95 Ok(powerset_indices(slice.len())
96 .map(|indices| indices.iter().map(|&idx| &slice[idx]).collect())
97 .collect())
98}
99
100fn check_grouping_set_size_limit(size: usize) -> Result<()> {
102 let max_grouping_set_size = 65535;
103 if size > max_grouping_set_size {
104 return plan_err!(
105 "The number of group_expression in grouping_set exceeds the maximum limit {max_grouping_set_size}, found {size}"
106 );
107 }
108
109 Ok(())
110}
111
112fn check_grouping_sets_size_limit(size: usize) -> Result<()> {
114 let max_grouping_sets_size = 4096;
115 if size > max_grouping_sets_size {
116 return plan_err!(
117 "The number of grouping_set in grouping_sets exceeds the maximum limit {max_grouping_sets_size}, found {size}"
118 );
119 }
120
121 Ok(())
122}
123
124fn merge_grouping_set<T: Clone>(left: &[T], right: &[T]) -> Result<Vec<T>> {
136 check_grouping_set_size_limit(left.len() + right.len())?;
137 Ok(left.iter().chain(right.iter()).cloned().collect())
138}
139
140fn cross_join_grouping_sets<T: Clone>(
153 left: &[Vec<T>],
154 right: &[Vec<T>],
155) -> Result<Vec<Vec<T>>> {
156 let grouping_sets_size = left.len() * right.len();
157
158 check_grouping_sets_size_limit(grouping_sets_size)?;
159
160 let mut result = Vec::with_capacity(grouping_sets_size);
161 for le in left {
162 for re in right {
163 result.push(merge_grouping_set(le, re)?);
164 }
165 }
166 Ok(result)
167}
168
169pub fn enumerate_grouping_sets(group_expr: Vec<Expr>) -> Result<Vec<Expr>> {
190 let has_grouping_set = group_expr
191 .iter()
192 .any(|expr| matches!(expr, Expr::GroupingSet(_)));
193 if !has_grouping_set || group_expr.len() == 1 {
194 return Ok(group_expr);
195 }
196 let partial_sets = group_expr
198 .iter()
199 .map(|expr| {
200 let exprs = match expr {
201 Expr::GroupingSet(GroupingSet::GroupingSets(grouping_sets)) => {
202 check_grouping_sets_size_limit(grouping_sets.len())?;
203 grouping_sets.iter().map(|e| e.iter().collect()).collect()
204 }
205 Expr::GroupingSet(GroupingSet::Cube(group_exprs)) => {
206 let grouping_sets = powerset(group_exprs)?;
207 check_grouping_sets_size_limit(grouping_sets.len())?;
208 grouping_sets
209 }
210 Expr::GroupingSet(GroupingSet::Rollup(group_exprs)) => {
211 let size = group_exprs.len();
212 let slice = group_exprs.as_slice();
213 check_grouping_sets_size_limit(size * (size + 1) / 2 + 1)?;
214 (0..=size).map(|i| slice[0..i].iter().collect()).collect()
215 }
216 expr => vec![vec![expr]],
217 };
218 Ok(exprs)
219 })
220 .collect::<Result<Vec<_>>>()?;
221
222 let grouping_sets = partial_sets
224 .into_iter()
225 .map(Ok)
226 .reduce(|l, r| cross_join_grouping_sets(&l?, &r?))
227 .transpose()?
228 .map(|e| {
229 e.into_iter()
230 .map(|e| e.into_iter().cloned().collect())
231 .collect()
232 })
233 .unwrap_or_default();
234
235 Ok(vec![Expr::GroupingSet(GroupingSet::GroupingSets(
236 grouping_sets,
237 ))])
238}
239
240pub fn grouping_set_to_exprlist(group_expr: &[Expr]) -> Result<Vec<&Expr>> {
243 if let Some(Expr::GroupingSet(grouping_set)) = group_expr.first() {
244 if group_expr.len() > 1 {
245 return plan_err!(
246 "Invalid group by expressions, GroupingSet must be the only expression"
247 );
248 }
249 Ok(grouping_set.distinct_expr())
250 } else {
251 Ok(group_expr
252 .iter()
253 .collect::<IndexSet<_>>()
254 .into_iter()
255 .collect())
256 }
257}
258
259pub fn expr_to_columns(expr: &Expr, accum: &mut HashSet<Column>) -> Result<()> {
262 expr.apply(|expr| {
263 match expr {
264 Expr::Column(qc) => {
265 accum.insert(qc.clone());
266 }
267 #[expect(deprecated)]
272 Expr::Unnest(_)
273 | Expr::ScalarVariable(_, _)
274 | Expr::Alias(_)
275 | Expr::Literal(_, _)
276 | Expr::BinaryExpr { .. }
277 | Expr::Like { .. }
278 | Expr::SimilarTo { .. }
279 | Expr::Not(_)
280 | Expr::IsNotNull(_)
281 | Expr::IsNull(_)
282 | Expr::IsTrue(_)
283 | Expr::IsFalse(_)
284 | Expr::IsUnknown(_)
285 | Expr::IsNotTrue(_)
286 | Expr::IsNotFalse(_)
287 | Expr::IsNotUnknown(_)
288 | Expr::Negative(_)
289 | Expr::Between { .. }
290 | Expr::Case { .. }
291 | Expr::Cast { .. }
292 | Expr::TryCast { .. }
293 | Expr::ScalarFunction(..)
294 | Expr::WindowFunction { .. }
295 | Expr::AggregateFunction { .. }
296 | Expr::GroupingSet(_)
297 | Expr::InList { .. }
298 | Expr::Exists { .. }
299 | Expr::InSubquery(_)
300 | Expr::SetComparison(_)
301 | Expr::ScalarSubquery(_)
302 | Expr::Wildcard { .. }
303 | Expr::Placeholder(_)
304 | Expr::OuterReferenceColumn { .. }
305 | Expr::HigherOrderFunction(_)
306 | Expr::Lambda(_)
307 | Expr::LambdaVariable(_) => {}
308 }
309 Ok(TreeNodeRecursion::Continue)
310 })
311 .map(|_| ())
312}
313
314fn get_excluded_columns(
317 opt_exclude: Option<&ExcludeSelectItem>,
318 opt_except: Option<&ExceptSelectItem>,
319 schema: &DFSchema,
320 qualifier: Option<&TableReference>,
321) -> Result<Vec<Column>> {
322 let mut idents = vec![];
323 if let Some(excepts) = opt_except {
324 idents.push(&excepts.first_element);
325 idents.extend(&excepts.additional_elements);
326 }
327 let exclude_owned: Vec<Ident>;
330 if let Some(exclude) = opt_exclude {
331 let object_name_to_ident = |name: &ObjectName| -> Result<Ident> {
332 if name.0.len() != 1 {
333 return plan_err!(
334 "EXCLUDE with multi-part identifiers is not supported: {name}"
335 );
336 }
337 let part = &name.0[0];
338 let Some(ident) = part.as_ident() else {
339 return plan_err!(
340 "EXCLUDE with non-identifier name part is not supported: {part}"
341 );
342 };
343 Ok(ident.clone())
344 };
345 exclude_owned = match exclude {
346 ExcludeSelectItem::Single(name) => vec![object_name_to_ident(name)?],
347 ExcludeSelectItem::Multiple(names) => names
348 .iter()
349 .map(object_name_to_ident)
350 .collect::<Result<Vec<_>>>()?,
351 };
352 idents.extend(exclude_owned.iter());
353 }
354 let n_elem = idents.len();
356 let unique_idents = idents.into_iter().collect::<HashSet<_>>();
357 if n_elem != unique_idents.len() {
360 return plan_err!("EXCLUDE or EXCEPT contains duplicate column names");
361 }
362
363 let mut result = Vec::with_capacity(unique_idents.len());
364 for ident in unique_idents.into_iter() {
365 let col_name = ident.value.as_str();
366 let (qualifier, field) = schema.qualified_field_with_name(qualifier, col_name)?;
367 result.push(Column::from((qualifier, field)));
368 }
369 Ok(result)
370}
371
372fn get_exprs_except_skipped(
374 schema: &DFSchema,
375 columns_to_skip: &HashSet<Column>,
376) -> Vec<Expr> {
377 if columns_to_skip.is_empty() {
378 schema.iter().map(Expr::from).collect::<Vec<Expr>>()
379 } else {
380 schema
381 .columns()
382 .iter()
383 .filter_map(|c| {
384 if !columns_to_skip.contains(c) {
385 Some(Expr::Column(c.clone()))
386 } else {
387 None
388 }
389 })
390 .collect::<Vec<Expr>>()
391 }
392}
393
394fn exclude_using_columns(plan: &LogicalPlan) -> Result<HashSet<Column>> {
399 let output_columns: HashSet<_> = plan.schema().columns().iter().cloned().collect();
400 let mut excluded = HashSet::new();
401 for cols in plan.using_columns()? {
402 let mut cols: Vec<_> = cols
408 .into_iter()
409 .filter(|c| output_columns.contains(c))
410 .collect();
411
412 cols.sort();
415
416 let mut seen_names = HashSet::new();
419 for col in cols {
420 if seen_names.contains(col.name.as_str()) {
421 excluded.insert(col); } else {
423 seen_names.insert(col.name.clone()); }
425 }
426 }
427 Ok(excluded)
428}
429
430pub fn expand_wildcard(
432 schema: &DFSchema,
433 plan: &LogicalPlan,
434 wildcard_options: Option<&WildcardOptions>,
435) -> Result<Vec<Expr>> {
436 let mut columns_to_skip = exclude_using_columns(plan)?;
437 let excluded_columns = if let Some(WildcardOptions {
438 exclude: opt_exclude,
439 except: opt_except,
440 ..
441 }) = wildcard_options
442 {
443 get_excluded_columns(opt_exclude.as_ref(), opt_except.as_ref(), schema, None)?
444 } else {
445 vec![]
446 };
447 columns_to_skip.extend(excluded_columns);
449 Ok(get_exprs_except_skipped(schema, &columns_to_skip))
450}
451
452pub fn expand_qualified_wildcard(
454 qualifier: &TableReference,
455 schema: &DFSchema,
456 wildcard_options: Option<&WildcardOptions>,
457) -> Result<Vec<Expr>> {
458 let qualified_indices = schema.fields_indices_with_qualified(qualifier);
459 let projected_func_dependencies = schema
460 .functional_dependencies()
461 .project_functional_dependencies(&qualified_indices, qualified_indices.len());
462 let fields_with_qualified = get_at_indices(schema.fields(), &qualified_indices)?;
463 if fields_with_qualified.is_empty() {
464 return plan_err!("Invalid qualifier {qualifier}");
465 }
466
467 let qualified_schema = Arc::new(Schema::new_with_metadata(
468 fields_with_qualified,
469 schema.metadata().clone(),
470 ));
471 let qualified_dfschema =
472 DFSchema::try_from_qualified_schema(qualifier.clone(), &qualified_schema)?
473 .with_functional_dependencies(projected_func_dependencies)?;
474 let excluded_columns = if let Some(WildcardOptions {
475 exclude: opt_exclude,
476 except: opt_except,
477 ..
478 }) = wildcard_options
479 {
480 get_excluded_columns(
481 opt_exclude.as_ref(),
482 opt_except.as_ref(),
483 schema,
484 Some(qualifier),
485 )?
486 } else {
487 vec![]
488 };
489 let mut columns_to_skip = HashSet::new();
491 columns_to_skip.extend(excluded_columns);
492 Ok(get_exprs_except_skipped(
493 &qualified_dfschema,
494 &columns_to_skip,
495 ))
496}
497
498type WindowSortKey = Vec<(Sort, bool)>;
501
502pub fn generate_sort_key(
504 partition_by: &[Expr],
505 order_by: &[Sort],
506) -> Result<WindowSortKey> {
507 let normalized_order_by_keys = order_by
508 .iter()
509 .map(|e| {
510 let Sort { expr, .. } = e;
511 Sort::new(expr.clone(), true, false)
512 })
513 .collect::<Vec<_>>();
514
515 let num_keys = partition_by.len() + order_by.len();
516 let mut final_sort_keys = Vec::with_capacity(num_keys);
517 let mut is_partition_flag = Vec::with_capacity(num_keys);
518 for e in partition_by {
519 let e = e.clone().sort(true, false);
522 if let Some(pos) = normalized_order_by_keys.iter().position(|key| key.eq(&e)) {
523 let order_by_key = &order_by[pos];
524 if !final_sort_keys.contains(order_by_key) {
525 final_sort_keys.push(order_by_key.clone());
526 is_partition_flag.push(true);
527 }
528 } else if !final_sort_keys.contains(&e) {
529 final_sort_keys.push(e);
530 is_partition_flag.push(true);
531 }
532 }
533
534 for e in order_by {
535 if !final_sort_keys.contains(e) {
536 final_sort_keys.push(e.clone());
537 is_partition_flag.push(false);
538 }
539 }
540 let res = final_sort_keys
541 .into_iter()
542 .zip(is_partition_flag)
543 .collect::<Vec<_>>();
544 Ok(res)
545}
546
547pub fn compare_sort_expr(
550 sort_expr_a: &Sort,
551 sort_expr_b: &Sort,
552 schema: &DFSchemaRef,
553) -> Ordering {
554 let Sort {
555 expr: expr_a,
556 asc: asc_a,
557 nulls_first: nulls_first_a,
558 } = sort_expr_a;
559
560 let Sort {
561 expr: expr_b,
562 asc: asc_b,
563 nulls_first: nulls_first_b,
564 } = sort_expr_b;
565
566 let ref_indexes_a = find_column_indexes_referenced_by_expr(expr_a, schema);
567 let ref_indexes_b = find_column_indexes_referenced_by_expr(expr_b, schema);
568 for (idx_a, idx_b) in ref_indexes_a.iter().zip(ref_indexes_b.iter()) {
569 match idx_a.cmp(idx_b) {
570 Ordering::Less => {
571 return Ordering::Less;
572 }
573 Ordering::Greater => {
574 return Ordering::Greater;
575 }
576 Ordering::Equal => {}
577 }
578 }
579 match ref_indexes_a.len().cmp(&ref_indexes_b.len()) {
580 Ordering::Less => return Ordering::Greater,
581 Ordering::Greater => {
582 return Ordering::Less;
583 }
584 Ordering::Equal => {}
585 }
586 match (asc_a, asc_b) {
587 (true, false) => {
588 return Ordering::Greater;
589 }
590 (false, true) => {
591 return Ordering::Less;
592 }
593 _ => {}
594 }
595 match (nulls_first_a, nulls_first_b) {
596 (true, false) => {
597 return Ordering::Less;
598 }
599 (false, true) => {
600 return Ordering::Greater;
601 }
602 _ => {}
603 }
604 Ordering::Equal
605}
606
607pub fn group_window_expr_by_sort_keys(
609 window_expr: impl IntoIterator<Item = Expr>,
610) -> Result<Vec<(WindowSortKey, Vec<Expr>)>> {
611 let mut result = vec![];
612
613 window_expr.into_iter().try_for_each(|expr| {
614 let inner = match &expr {
617 Expr::Alias(alias) => alias.expr.as_ref(),
618 _ => &expr,
619 };
620
621 let Expr::WindowFunction(window_fun) = inner else {
622 return internal_err!("Impossibly got non-window expr {expr:?}");
623 };
624
625 let WindowFunctionParams {
626 partition_by,
627 order_by,
628 ..
629 } = &window_fun.as_ref().params;
630
631 let sort_key = generate_sort_key(partition_by, order_by)?;
632
633 if let Some((_, values)) = result.iter_mut().find(
634 |group: &&mut (WindowSortKey, Vec<Expr>)| {
635 matches!(group, (key, _) if *key == sort_key)
636 },
637 ) {
638 values.push(expr);
639 } else {
640 result.push((sort_key, vec![expr]));
641 }
642
643 Ok(())
644 })?;
645
646 Ok(result)
647}
648
649pub fn find_aggregate_exprs<'a>(exprs: impl IntoIterator<Item = &'a Expr>) -> Vec<Expr> {
653 find_exprs_in_exprs(exprs, &|nested_expr| {
654 matches!(nested_expr, Expr::AggregateFunction { .. })
655 })
656}
657
658pub(crate) fn check_aggregate_and_window_nesting<'a>(
680 exprs: impl IntoIterator<Item = &'a Expr>,
681) -> Result<()> {
682 for expr in exprs {
683 expr.apply(|outer| {
684 if !matches!(outer, Expr::AggregateFunction(_) | Expr::WindowFunction(_)) {
685 return Ok(TreeNodeRecursion::Continue);
686 }
687
688 let mut err = None;
691 outer.apply_children(|child| {
692 child.apply(|inner| {
693 err = illegal_nesting_err(outer, inner);
694 if err.is_some() {
695 Ok(TreeNodeRecursion::Stop)
696 } else {
697 Ok(TreeNodeRecursion::Continue)
698 }
699 })
700 })?;
701
702 match err {
703 Some(err) => Err(err),
704 None => Ok(TreeNodeRecursion::Continue),
705 }
706 })?;
707 }
708 Ok(())
709}
710
711fn illegal_nesting_err(outer: &Expr, inner: &Expr) -> Option<DataFusionError> {
714 let (message, help) = match (outer, inner) {
716 (Expr::AggregateFunction(_), Expr::AggregateFunction(_)) => (
717 "Aggregate function calls cannot be nested",
718 format!("Compute '{inner}' in an inner query and aggregate its result"),
719 ),
720 (Expr::AggregateFunction(_), Expr::WindowFunction(_)) => (
721 "Aggregate function calls cannot contain window function calls",
722 format!("Compute '{inner}' in an inner query and aggregate its result"),
723 ),
724 (Expr::WindowFunction(_), Expr::WindowFunction(_)) => (
725 "Window function calls cannot be nested",
726 format!("Compute '{inner}' in an inner query and use its result here"),
727 ),
728 _ => return None,
730 };
731
732 Some(
733 plan_datafusion_err!("{message}: '{inner}' is nested inside '{outer}'")
734 .with_diagnostic(
735 Diagnostic::new_error(message, first_span(inner)).with_help(help, None),
736 ),
737 )
738}
739
740fn first_span(expr: &Expr) -> Option<Span> {
745 let mut span = None;
746 expr.apply(|e| {
747 span = e.spans().and_then(|spans| spans.first());
748 if span.is_some() {
749 Ok(TreeNodeRecursion::Stop)
750 } else {
751 Ok(TreeNodeRecursion::Continue)
752 }
753 })
754 .ok()?;
755 span
756}
757
758pub fn check_no_window_functions(expr: &Expr, clause: &str) -> Result<()> {
780 match first_window_function(expr) {
781 None => Ok(()),
782 Some(window) => Err(window_function_not_allowed_err(
783 window,
784 clause,
785 first_span(window),
786 format!(
787 "Compute '{window}' first, in a Window node or an inner query, and filter on its result"
788 ),
789 )),
790 }
791}
792
793fn first_window_function(expr: &Expr) -> Option<&Expr> {
796 let mut window = None;
797 expr.apply(|e| {
798 if matches!(e, Expr::WindowFunction(_)) {
799 window = Some(e);
800 Ok(TreeNodeRecursion::Stop)
801 } else {
802 Ok(TreeNodeRecursion::Continue)
803 }
804 })
805 .ok()?;
806 window
807}
808
809pub fn window_function_not_allowed_err(
816 window: &Expr,
817 clause: &str,
818 span: Option<Span>,
819 help: impl Into<String>,
820) -> DataFusionError {
821 let message = format!("Window function calls are not allowed in {clause}");
822 plan_datafusion_err!("{message}: '{window}'")
823 .with_diagnostic(Diagnostic::new_error(message, span).with_help(help, None))
824}
825
826pub fn find_window_exprs<'a>(exprs: impl IntoIterator<Item = &'a Expr>) -> Vec<Expr> {
829 find_exprs_in_exprs(exprs, &|nested_expr| {
830 matches!(nested_expr, Expr::WindowFunction { .. })
831 })
832}
833
834pub fn find_out_reference_exprs(expr: &Expr) -> Vec<Expr> {
837 find_exprs_in_expr(expr, &|nested_expr| {
838 matches!(nested_expr, Expr::OuterReferenceColumn { .. })
839 })
840}
841
842fn find_exprs_in_exprs<'a, F>(
846 exprs: impl IntoIterator<Item = &'a Expr>,
847 test_fn: &F,
848) -> Vec<Expr>
849where
850 F: Fn(&Expr) -> bool,
851{
852 let mut found = IndexSet::new();
853 for expr in exprs {
854 collect_exprs_in_expr(expr, test_fn, &mut found);
855 }
856 found.into_iter().collect()
857}
858
859fn find_exprs_in_expr<F>(expr: &Expr, test_fn: &F) -> Vec<Expr>
863where
864 F: Fn(&Expr) -> bool,
865{
866 find_exprs_in_exprs(std::iter::once(expr), test_fn)
867}
868
869fn collect_exprs_in_expr<F>(expr: &Expr, test_fn: &F, found: &mut IndexSet<Expr>)
870where
871 F: Fn(&Expr) -> bool,
872{
873 expr.apply(|expr| {
874 if test_fn(expr) {
875 if !found.contains(expr) {
876 found.insert(expr.clone());
877 }
878 return Ok(TreeNodeRecursion::Jump);
880 }
881
882 Ok(TreeNodeRecursion::Continue)
883 })
884 .expect("no way to return error during recursion");
886}
887
888pub fn inspect_expr_pre<F, E>(expr: &Expr, mut f: F) -> Result<(), E>
890where
891 F: FnMut(&Expr) -> Result<(), E>,
892{
893 let mut err = Ok(());
894 expr.apply(|expr| {
895 if let Err(e) = f(expr) {
896 err = Err(e);
898 Ok(TreeNodeRecursion::Stop)
899 } else {
900 Ok(TreeNodeRecursion::Continue)
902 }
903 })
904 .expect("no way to return error during recursion");
906
907 err
908}
909
910pub(crate) fn get_unnested_list_field(
912 data_type: &DataType,
913 depth: usize,
914) -> Result<&Field> {
915 match data_type {
916 DataType::List(field)
917 | DataType::FixedSizeList(field, _)
918 | DataType::LargeList(field)
919 | DataType::ListView(field)
920 | DataType::LargeListView(field) => {
921 if depth == 1 {
922 return Ok(field.as_ref());
923 }
924 return get_unnested_list_field(field.data_type(), depth - 1);
925 }
926 _ => {}
927 }
928
929 internal_err!("trying to unnest on invalid data type {data_type}")
930}
931
932pub fn exprlist_to_fields<'a>(
950 exprs: impl IntoIterator<Item = &'a Expr>,
951 plan: &LogicalPlan,
952) -> Result<Vec<(Option<TableReference>, Arc<Field>)>> {
953 let input_schema = plan.schema();
955 exprs
956 .into_iter()
957 .map(|e| e.to_field(input_schema))
958 .collect()
959}
960
961pub fn columnize_expr(e: Expr, input: &LogicalPlan) -> Result<Expr> {
977 Columnizer::new(input).columnize(e)
978}
979
980pub(crate) struct Columnizer<'a> {
983 output_exprs: HashMap<&'a Expr, Column>,
984}
985
986impl<'a> Columnizer<'a> {
987 pub(crate) fn new(input: &'a LogicalPlan) -> Self {
988 let output_exprs = input
989 .columnized_output_exprs()
990 .map(|exprs| exprs.into_iter().collect())
991 .unwrap_or_default();
992 Self { output_exprs }
993 }
994
995 pub(crate) fn columnize(&self, e: Expr) -> Result<Expr> {
996 if self.output_exprs.is_empty() {
997 return Ok(e);
998 }
999 e.transform_down(|node: Expr| match self.output_exprs.get(&node) {
1000 Some(column) => Ok(Transformed::new(
1001 Expr::Column(column.clone()),
1002 true,
1003 TreeNodeRecursion::Jump,
1004 )),
1005 None => Ok(Transformed::no(node)),
1006 })
1007 .data()
1008 }
1009}
1010
1011pub fn find_column_exprs(exprs: &[Expr]) -> Vec<Expr> {
1014 exprs
1015 .iter()
1016 .flat_map(find_columns_referenced_by_expr)
1017 .map(Expr::Column)
1018 .collect()
1019}
1020
1021pub(crate) fn find_columns_referenced_by_expr(e: &Expr) -> Vec<Column> {
1022 let mut exprs = vec![];
1023 e.apply(|expr| {
1024 if let Expr::Column(c) = expr {
1025 exprs.push(c.clone())
1026 }
1027 Ok(TreeNodeRecursion::Continue)
1028 })
1029 .expect("Unexpected error");
1031 exprs
1032}
1033
1034pub fn passthrough_field_index(expr: &Expr, schema: &DFSchema) -> Option<usize> {
1044 match expr {
1045 Expr::Column(col) => {
1046 let (_, field) = schema.qualified_field_from_column(col).ok()?;
1047 schema.fields().iter().position(|f| std::ptr::eq(f, field))
1048 }
1049 Expr::Alias(alias) => passthrough_field_index(&alias.expr, schema),
1050 _ => None,
1051 }
1052}
1053
1054pub fn expr_as_column_expr(expr: &Expr, plan: &LogicalPlan) -> Result<Expr> {
1056 match expr {
1057 Expr::Column(col) => {
1058 let (qualifier, field) = plan.schema().qualified_field_from_column(col)?;
1059 Ok(Expr::from(Column::from((qualifier, field))))
1060 }
1061 _ => Ok(Expr::Column(Column::from_name(
1062 expr.schema_name().to_string(),
1063 ))),
1064 }
1065}
1066
1067pub(crate) fn find_column_indexes_referenced_by_expr(
1070 e: &Expr,
1071 schema: &DFSchemaRef,
1072) -> Vec<usize> {
1073 let mut indexes = vec![];
1074 e.apply(|expr| {
1075 match expr {
1076 Expr::Column(qc) => {
1077 if let Ok(idx) = schema.index_of_column(qc) {
1078 indexes.push(idx);
1079 }
1080 }
1081 Expr::Literal(_, _) => {
1082 indexes.push(usize::MAX);
1083 }
1084 _ => {}
1085 }
1086 Ok(TreeNodeRecursion::Continue)
1087 })
1088 .unwrap();
1089 indexes
1090}
1091
1092pub fn can_hash(data_type: &DataType) -> bool {
1096 match data_type {
1097 DataType::Null => true,
1098 DataType::Boolean => true,
1099 DataType::Int8 => true,
1100 DataType::Int16 => true,
1101 DataType::Int32 => true,
1102 DataType::Int64 => true,
1103 DataType::UInt8 => true,
1104 DataType::UInt16 => true,
1105 DataType::UInt32 => true,
1106 DataType::UInt64 => true,
1107 DataType::Float16 => true,
1108 DataType::Float32 => true,
1109 DataType::Float64 => true,
1110 DataType::Decimal32(_, _) => true,
1111 DataType::Decimal64(_, _) => true,
1112 DataType::Decimal128(_, _) => true,
1113 DataType::Decimal256(_, _) => true,
1114 DataType::Timestamp(_, _) => true,
1115 DataType::Utf8 => true,
1116 DataType::LargeUtf8 => true,
1117 DataType::Utf8View => true,
1118 DataType::Binary => true,
1119 DataType::LargeBinary => true,
1120 DataType::BinaryView => true,
1121 DataType::Date32 => true,
1122 DataType::Date64 => true,
1123 DataType::Time32(_) => true,
1124 DataType::Time64(_) => true,
1125 DataType::Duration(_) => true,
1126 DataType::Interval(_) => true,
1127 DataType::FixedSizeBinary(_) => true,
1128 DataType::Dictionary(key_type, value_type) => {
1129 DataType::is_dictionary_key_type(key_type) && can_hash(value_type)
1130 }
1131 DataType::List(value_type) => can_hash(value_type.data_type()),
1132 DataType::LargeList(value_type) => can_hash(value_type.data_type()),
1133 DataType::FixedSizeList(value_type, _) => can_hash(value_type.data_type()),
1134 DataType::Map(map_struct, true | false) => can_hash(map_struct.data_type()),
1135 DataType::Struct(fields) => fields.iter().all(|f| can_hash(f.data_type())),
1136
1137 DataType::ListView(_)
1138 | DataType::LargeListView(_)
1139 | DataType::Union(_, _)
1140 | DataType::RunEndEncoded(_, _) => false,
1141 }
1142}
1143
1144pub fn check_all_columns_from_schema(
1146 columns: &HashSet<&Column>,
1147 schema: &DFSchema,
1148) -> Result<bool> {
1149 for col in columns.iter() {
1150 let exist = schema.is_column_from_schema(col);
1151 if !exist {
1152 return Ok(false);
1153 }
1154 }
1155
1156 Ok(true)
1157}
1158
1159pub fn find_valid_equijoin_key_pair(
1168 left_key: &Expr,
1169 right_key: &Expr,
1170 left_schema: &DFSchema,
1171 right_schema: &DFSchema,
1172) -> Result<Option<(Expr, Expr)>> {
1173 let left_using_columns = left_key.column_refs();
1174 let right_using_columns = right_key.column_refs();
1175
1176 if left_using_columns.is_empty() || right_using_columns.is_empty() {
1178 return Ok(None);
1179 }
1180
1181 let left_is_narrower = left_schema.fields().len() <= right_schema.fields().len();
1187 let check = |left_columns: &HashSet<&Column>,
1188 right_columns: &HashSet<&Column>|
1189 -> Result<bool> {
1190 let left = (left_columns, left_schema);
1191 let right = (right_columns, right_schema);
1192 let (first, second) = if left_is_narrower {
1193 (left, right)
1194 } else {
1195 (right, left)
1196 };
1197 Ok(check_all_columns_from_schema(first.0, first.1)?
1198 && check_all_columns_from_schema(second.0, second.1)?)
1199 };
1200
1201 if check(&left_using_columns, &right_using_columns)? {
1202 return Ok(Some((left_key.clone(), right_key.clone())));
1203 } else if check(&right_using_columns, &left_using_columns)? {
1204 return Ok(Some((right_key.clone(), left_key.clone())));
1205 }
1206
1207 Ok(None)
1208}
1209
1210#[expect(clippy::needless_pass_by_value)]
1222#[deprecated(since = "53.0.0", note = "Internal function")]
1223pub fn generate_signature_error_msg(
1224 func_name: &str,
1225 func_signature: Signature,
1226 input_expr_types: &[DataType],
1227) -> String {
1228 let candidate_signatures = func_signature
1229 .type_signature
1230 .to_string_repr_with_names(func_signature.parameter_names.as_deref())
1231 .iter()
1232 .map(|args_str| format!("\t{func_name}({args_str})"))
1233 .collect::<Vec<String>>()
1234 .join("\n");
1235
1236 format!(
1237 "No function matches the given name and argument types '{}({})'. You might need to add explicit type casts.\n\tCandidate functions:\n{}",
1238 func_name,
1239 TypeSignature::join_types(input_expr_types, ", "),
1240 candidate_signatures
1241 )
1242}
1243
1244pub(crate) fn generate_signature_error_message(
1256 func_name: &str,
1257 func_signature: &Signature,
1258 input_expr_types: &[DataType],
1259) -> String {
1260 #[expect(deprecated)]
1261 generate_signature_error_msg(func_name, func_signature.clone(), input_expr_types)
1262}
1263
1264pub fn split_conjunction(expr: &Expr) -> Vec<&Expr> {
1268 split_conjunction_impl(expr, vec![])
1269}
1270
1271fn split_conjunction_impl<'a>(expr: &'a Expr, mut exprs: Vec<&'a Expr>) -> Vec<&'a Expr> {
1272 match expr {
1273 Expr::BinaryExpr(BinaryExpr {
1274 right,
1275 op: Operator::And,
1276 left,
1277 }) => {
1278 let exprs = split_conjunction_impl(left, exprs);
1279 split_conjunction_impl(right, exprs)
1280 }
1281 Expr::Alias(Alias { expr, .. }) => split_conjunction_impl(expr, exprs),
1282 other => {
1283 exprs.push(other);
1284 exprs
1285 }
1286 }
1287}
1288
1289pub fn iter_conjunction(expr: &Expr) -> impl Iterator<Item = &Expr> {
1293 let mut stack = vec![expr];
1294 std::iter::from_fn(move || {
1295 while let Some(expr) = stack.pop() {
1296 match expr {
1297 Expr::BinaryExpr(BinaryExpr {
1298 right,
1299 op: Operator::And,
1300 left,
1301 }) => {
1302 stack.push(right);
1303 stack.push(left);
1304 }
1305 Expr::Alias(Alias { expr, .. }) => stack.push(expr),
1306 other => return Some(other),
1307 }
1308 }
1309 None
1310 })
1311}
1312
1313pub fn iter_conjunction_owned(expr: Expr) -> impl Iterator<Item = Expr> {
1317 let mut stack = vec![expr];
1318 std::iter::from_fn(move || {
1319 while let Some(expr) = stack.pop() {
1320 match expr {
1321 Expr::BinaryExpr(BinaryExpr {
1322 right,
1323 op: Operator::And,
1324 left,
1325 }) => {
1326 stack.push(*right);
1327 stack.push(*left);
1328 }
1329 Expr::Alias(Alias { expr, .. }) => stack.push(*expr),
1330 other => return Some(other),
1331 }
1332 }
1333 None
1334 })
1335}
1336
1337pub fn split_conjunction_owned(expr: Expr) -> Vec<Expr> {
1356 split_binary_owned(expr, Operator::And)
1357}
1358
1359pub fn split_binary_owned(expr: Expr, op: Operator) -> Vec<Expr> {
1379 split_binary_owned_impl(expr, op, vec![])
1380}
1381
1382fn split_binary_owned_impl(
1383 expr: Expr,
1384 operator: Operator,
1385 mut exprs: Vec<Expr>,
1386) -> Vec<Expr> {
1387 match expr {
1388 Expr::BinaryExpr(BinaryExpr { right, op, left }) if op == operator => {
1389 let exprs = split_binary_owned_impl(*left, operator, exprs);
1390 split_binary_owned_impl(*right, operator, exprs)
1391 }
1392 Expr::Alias(Alias { expr, .. }) => {
1393 split_binary_owned_impl(*expr, operator, exprs)
1394 }
1395 other => {
1396 exprs.push(other);
1397 exprs
1398 }
1399 }
1400}
1401
1402pub fn split_binary(expr: &Expr, op: Operator) -> Vec<&Expr> {
1406 split_binary_impl(expr, op, vec![])
1407}
1408
1409fn split_binary_impl<'a>(
1410 expr: &'a Expr,
1411 operator: Operator,
1412 mut exprs: Vec<&'a Expr>,
1413) -> Vec<&'a Expr> {
1414 match expr {
1415 Expr::BinaryExpr(BinaryExpr { right, op, left }) if *op == operator => {
1416 let exprs = split_binary_impl(left, operator, exprs);
1417 split_binary_impl(right, operator, exprs)
1418 }
1419 Expr::Alias(Alias { expr, .. }) => split_binary_impl(expr, operator, exprs),
1420 other => {
1421 exprs.push(other);
1422 exprs
1423 }
1424 }
1425}
1426
1427pub fn conjunction(filters: impl IntoIterator<Item = Expr>) -> Option<Expr> {
1447 filters.into_iter().reduce(Expr::and)
1448}
1449
1450pub fn disjunction(filters: impl IntoIterator<Item = Expr>) -> Option<Expr> {
1470 filters.into_iter().reduce(Expr::or)
1471}
1472
1473pub fn add_filter(plan: LogicalPlan, predicates: &[&Expr]) -> Result<LogicalPlan> {
1488 let predicate = predicates
1490 .iter()
1491 .skip(1)
1492 .fold(predicates[0].clone(), |acc, predicate| {
1493 and(acc, (*predicate).to_owned())
1494 });
1495
1496 Ok(LogicalPlan::Filter(Filter::try_new(
1497 predicate,
1498 Arc::new(plan),
1499 )?))
1500}
1501
1502#[deprecated(
1513 since = "56.0.0",
1514 note = "This decorrelation helper is intended for internal optimizer use and has no public replacement"
1515)]
1516pub fn find_join_exprs(exprs: Vec<&Expr>) -> Result<(Vec<Expr>, Vec<Expr>)> {
1517 let mut joins = vec![];
1518 let mut others = vec![];
1519 for filter in exprs.into_iter() {
1520 if filter.contains_outer() {
1522 if !matches!(filter, Expr::BinaryExpr(BinaryExpr{ left, op: Operator::Eq, right }) if left.eq(right))
1523 {
1524 joins.push(strip_outer_reference((*filter).clone()));
1525 }
1526 } else {
1527 others.push((*filter).clone());
1528 }
1529 }
1530
1531 Ok((joins, others))
1532}
1533
1534pub fn only_or_err<T>(slice: &[T]) -> Result<&T> {
1544 match slice {
1545 [it] => Ok(it),
1546 [] => plan_err!("No items found!"),
1547 _ => plan_err!("More than one item found!"),
1548 }
1549}
1550
1551pub fn merge_schema(inputs: &[&LogicalPlan]) -> DFSchema {
1556 if inputs.len() == 1 {
1557 inputs[0].schema().as_ref().clone()
1558 } else {
1559 inputs.iter().map(|input| input.schema()).fold(
1560 DFSchema::empty(),
1561 |mut lhs, rhs| {
1562 lhs.merge(rhs);
1563 lhs
1564 },
1565 )
1566 }
1567}
1568
1569pub fn format_state_name(name: &str, state_name: &str) -> String {
1571 format!("{name}[{state_name}]")
1572}
1573
1574pub fn ordering_state_fields(
1578 name: &str,
1579 ordering_fields: &[FieldRef],
1580) -> impl Iterator<Item = FieldRef> {
1581 ordering_fields.iter().enumerate().map(|(idx, field)| {
1582 Arc::new(
1583 field
1584 .as_ref()
1585 .clone()
1586 .with_name(format_state_name(name, &format!("ordering_{idx}"))),
1587 )
1588 })
1589}
1590
1591pub fn collect_subquery_cols(
1593 exprs: &[Expr],
1594 subquery_schema: &DFSchema,
1595) -> Result<BTreeSet<Column>> {
1596 exprs.iter().try_fold(BTreeSet::new(), |mut cols, expr| {
1597 for col in expr.column_refs().into_iter() {
1598 if subquery_schema.has_column(col) {
1599 cols.insert(col.clone());
1600 }
1601 }
1602
1603 Result::<_>::Ok(cols)
1604 })
1605}
1606
1607pub fn collect_subquery_join_exprs(
1618 exprs: &[Expr],
1619 subquery_schema: &DFSchema,
1620) -> Result<Vec<Expr>> {
1621 let mut result: Vec<Expr> = vec![];
1622 for expr in exprs {
1623 expr.apply(|e| {
1624 if e.column_refs()
1625 .into_iter()
1626 .all(|col| subquery_schema.has_column(col))
1627 && !e.column_refs().is_empty()
1628 && !result.contains(e)
1629 {
1630 result.push(e.clone());
1631 return Ok(TreeNodeRecursion::Jump);
1632 }
1633 Ok(TreeNodeRecursion::Continue)
1634 })?;
1635 }
1636 Ok(result)
1637}
1638
1639#[cfg(test)]
1640mod tests {
1641 use super::*;
1642 use crate::{
1643 Cast, ExprFunctionExt, WindowFunctionDefinition, col, cube,
1644 expr::WindowFunction,
1645 expr_vec_fmt, grouping_set, lit, rollup,
1646 test::function_stub::{max_udaf, min_udaf, sum_udaf},
1647 };
1648 use arrow::datatypes::{Metadata, UnionFields, UnionMode};
1649 use datafusion_expr_common::signature::Volatility;
1650
1651 #[test]
1652 fn passthrough_field_index_resolves_like_a_column_reference() -> Result<()> {
1653 let field = |name| Arc::new(Field::new(name, DataType::Int32, false));
1654 let schema = DFSchema::new_with_metadata(
1655 vec![
1656 (Some("a".into()), field("id")),
1657 (Some("b".into()), field("id")),
1658 (Some("b".into()), field("v")),
1659 ],
1660 Metadata::default(),
1661 )?;
1662 let index = |e: Expr| passthrough_field_index(&e, &schema);
1663
1664 assert_eq!(index(col("b.id")), Some(1));
1665 assert_eq!(index(col("v").alias("w")), Some(2));
1666 assert_eq!(index(col("id")), None);
1668 assert_eq!(index(crate::cast(col("b.id"), DataType::Int64)), None);
1670 Ok(())
1671 }
1672
1673 #[test]
1674 fn find_aggregate_exprs_dedups_in_order_of_appearance() {
1675 use crate::test::function_stub::{count, sum};
1676
1677 let exprs = [
1678 sum(col("a")) + count(col("b")),
1679 count(col("b")) * sum(col("c")),
1680 sum(col("a")) + sum(col("a")),
1681 ];
1682 assert_eq!(
1683 find_aggregate_exprs(&exprs),
1684 vec![sum(col("a")), count(col("b")), sum(col("c"))]
1685 );
1686 }
1687
1688 #[test]
1689 fn test_group_window_expr_by_sort_keys_empty_case() -> Result<()> {
1690 let result = group_window_expr_by_sort_keys(vec![])?;
1691 let expected: Vec<(WindowSortKey, Vec<Expr>)> = vec![];
1692 assert_eq!(expected, result);
1693 Ok(())
1694 }
1695
1696 #[test]
1697 fn test_group_window_expr_by_sort_keys_empty_window() -> Result<()> {
1698 let max1 = Expr::from(WindowFunction::new(
1699 WindowFunctionDefinition::AggregateUDF(max_udaf()),
1700 vec![col("name")],
1701 ));
1702 let max2 = Expr::from(WindowFunction::new(
1703 WindowFunctionDefinition::AggregateUDF(max_udaf()),
1704 vec![col("name")],
1705 ));
1706 let min3 = Expr::from(WindowFunction::new(
1707 WindowFunctionDefinition::AggregateUDF(min_udaf()),
1708 vec![col("name")],
1709 ));
1710 let sum4 = Expr::from(WindowFunction::new(
1711 WindowFunctionDefinition::AggregateUDF(sum_udaf()),
1712 vec![col("age")],
1713 ));
1714 let exprs = &[max1.clone(), max2.clone(), min3.clone(), sum4.clone()];
1715 let result = group_window_expr_by_sort_keys(exprs.to_vec())?;
1716 let key = vec![];
1717 let expected: Vec<(WindowSortKey, Vec<Expr>)> =
1718 vec![(key, vec![max1, max2, min3, sum4])];
1719 assert_eq!(expected, result);
1720 Ok(())
1721 }
1722
1723 #[test]
1724 fn test_group_window_expr_by_sort_keys_aliased_window_expr() -> Result<()> {
1725 let age_asc = Sort::new(col("age"), true, true);
1726 let max1 = Expr::from(WindowFunction::new(
1727 WindowFunctionDefinition::AggregateUDF(max_udaf()),
1728 vec![col("name")],
1729 ))
1730 .order_by(vec![age_asc.clone()])
1731 .build()
1732 .unwrap();
1733 let max1_aliased = max1.clone().alias("max_name");
1738
1739 let result =
1740 group_window_expr_by_sort_keys(vec![max1.clone(), max1_aliased.clone()])?;
1741
1742 let key = vec![(age_asc, false)];
1743 let expected: Vec<(WindowSortKey, Vec<Expr>)> =
1744 vec![(key, vec![max1, max1_aliased])];
1745 assert_eq!(expected, result);
1746 Ok(())
1747 }
1748 #[test]
1749 fn test_group_window_expr_by_sort_keys() -> Result<()> {
1750 let age_asc = Sort::new(col("age"), true, true);
1751 let name_desc = Sort::new(col("name"), false, true);
1752 let created_at_desc = Sort::new(col("created_at"), false, true);
1753 let max1 = Expr::from(WindowFunction::new(
1754 WindowFunctionDefinition::AggregateUDF(max_udaf()),
1755 vec![col("name")],
1756 ))
1757 .order_by(vec![age_asc.clone(), name_desc.clone()])
1758 .build()
1759 .unwrap();
1760 let max2 = Expr::from(WindowFunction::new(
1761 WindowFunctionDefinition::AggregateUDF(max_udaf()),
1762 vec![col("name")],
1763 ));
1764 let min3 = Expr::from(WindowFunction::new(
1765 WindowFunctionDefinition::AggregateUDF(min_udaf()),
1766 vec![col("name")],
1767 ))
1768 .order_by(vec![age_asc.clone(), name_desc.clone()])
1769 .build()
1770 .unwrap();
1771 let sum4 = Expr::from(WindowFunction::new(
1772 WindowFunctionDefinition::AggregateUDF(sum_udaf()),
1773 vec![col("age")],
1774 ))
1775 .order_by(vec![
1776 name_desc.clone(),
1777 age_asc.clone(),
1778 created_at_desc.clone(),
1779 ])
1780 .build()
1781 .unwrap();
1782 let exprs = &[max1.clone(), max2.clone(), min3.clone(), sum4.clone()];
1784 let result = group_window_expr_by_sort_keys(exprs.to_vec())?;
1785
1786 let key1 = vec![(age_asc.clone(), false), (name_desc.clone(), false)];
1787 let key2 = vec![];
1788 let key3 = vec![
1789 (name_desc, false),
1790 (age_asc, false),
1791 (created_at_desc, false),
1792 ];
1793
1794 let expected: Vec<(WindowSortKey, Vec<Expr>)> = vec![
1795 (key1, vec![max1, min3]),
1796 (key2, vec![max2]),
1797 (key3, vec![sum4]),
1798 ];
1799 assert_eq!(expected, result);
1800 Ok(())
1801 }
1802
1803 #[test]
1804 fn avoid_generate_duplicate_sort_keys() -> Result<()> {
1805 let asc_or_desc = [true, false];
1806 let nulls_first_or_last = [true, false];
1807 let partition_by = &[col("age"), col("name"), col("created_at")];
1808 for asc_ in asc_or_desc {
1809 for nulls_first_ in nulls_first_or_last {
1810 let order_by = &[
1811 Sort {
1812 expr: col("age"),
1813 asc: asc_,
1814 nulls_first: nulls_first_,
1815 },
1816 Sort {
1817 expr: col("name"),
1818 asc: asc_,
1819 nulls_first: nulls_first_,
1820 },
1821 ];
1822
1823 let expected = vec![
1824 (
1825 Sort {
1826 expr: col("age"),
1827 asc: asc_,
1828 nulls_first: nulls_first_,
1829 },
1830 true,
1831 ),
1832 (
1833 Sort {
1834 expr: col("name"),
1835 asc: asc_,
1836 nulls_first: nulls_first_,
1837 },
1838 true,
1839 ),
1840 (
1841 Sort {
1842 expr: col("created_at"),
1843 asc: true,
1844 nulls_first: false,
1845 },
1846 true,
1847 ),
1848 ];
1849 let result = generate_sort_key(partition_by, order_by)?;
1850 assert_eq!(expected, result);
1851 }
1852 }
1853 Ok(())
1854 }
1855
1856 #[test]
1857 fn test_enumerate_grouping_sets() -> Result<()> {
1858 let multi_cols = vec![col("col1"), col("col2"), col("col3")];
1859 let simple_col = col("simple_col");
1860 let cube = cube(multi_cols.clone());
1861 let rollup = rollup(multi_cols.clone());
1862 let grouping_set = grouping_set(vec![multi_cols]);
1863
1864 let sets = enumerate_grouping_sets(vec![simple_col.clone()])?;
1866 let result = format!("[{}]", expr_vec_fmt!(sets));
1867 assert_eq!("[simple_col]", &result);
1868
1869 let sets = enumerate_grouping_sets(vec![cube.clone()])?;
1871 let result = format!("[{}]", expr_vec_fmt!(sets));
1872 assert_eq!("[CUBE (col1, col2, col3)]", &result);
1873
1874 let sets = enumerate_grouping_sets(vec![rollup.clone()])?;
1876 let result = format!("[{}]", expr_vec_fmt!(sets));
1877 assert_eq!("[ROLLUP (col1, col2, col3)]", &result);
1878
1879 let sets = enumerate_grouping_sets(vec![simple_col.clone(), cube.clone()])?;
1881 let result = format!("[{}]", expr_vec_fmt!(sets));
1882 assert_eq!(
1883 "[GROUPING SETS (\
1884 (simple_col), \
1885 (simple_col, col1), \
1886 (simple_col, col2), \
1887 (simple_col, col1, col2), \
1888 (simple_col, col3), \
1889 (simple_col, col1, col3), \
1890 (simple_col, col2, col3), \
1891 (simple_col, col1, col2, col3))]",
1892 &result
1893 );
1894
1895 let sets = enumerate_grouping_sets(vec![simple_col.clone(), rollup.clone()])?;
1897 let result = format!("[{}]", expr_vec_fmt!(sets));
1898 assert_eq!(
1899 "[GROUPING SETS (\
1900 (simple_col), \
1901 (simple_col, col1), \
1902 (simple_col, col1, col2), \
1903 (simple_col, col1, col2, col3))]",
1904 &result
1905 );
1906
1907 let sets =
1909 enumerate_grouping_sets(vec![simple_col.clone(), grouping_set.clone()])?;
1910 let result = format!("[{}]", expr_vec_fmt!(sets));
1911 assert_eq!(
1912 "[GROUPING SETS (\
1913 (simple_col, col1, col2, col3))]",
1914 &result
1915 );
1916
1917 let sets = enumerate_grouping_sets(vec![
1919 simple_col.clone(),
1920 grouping_set,
1921 rollup.clone(),
1922 ])?;
1923 let result = format!("[{}]", expr_vec_fmt!(sets));
1924 assert_eq!(
1925 "[GROUPING SETS (\
1926 (simple_col, col1, col2, col3), \
1927 (simple_col, col1, col2, col3, col1), \
1928 (simple_col, col1, col2, col3, col1, col2), \
1929 (simple_col, col1, col2, col3, col1, col2, col3))]",
1930 &result
1931 );
1932
1933 let sets = enumerate_grouping_sets(vec![simple_col, cube, rollup])?;
1935 let result = format!("[{}]", expr_vec_fmt!(sets));
1936 assert_eq!(
1937 "[GROUPING SETS (\
1938 (simple_col), \
1939 (simple_col, col1), \
1940 (simple_col, col1, col2), \
1941 (simple_col, col1, col2, col3), \
1942 (simple_col, col1), \
1943 (simple_col, col1, col1), \
1944 (simple_col, col1, col1, col2), \
1945 (simple_col, col1, col1, col2, col3), \
1946 (simple_col, col2), \
1947 (simple_col, col2, col1), \
1948 (simple_col, col2, col1, col2), \
1949 (simple_col, col2, col1, col2, col3), \
1950 (simple_col, col1, col2), \
1951 (simple_col, col1, col2, col1), \
1952 (simple_col, col1, col2, col1, col2), \
1953 (simple_col, col1, col2, col1, col2, col3), \
1954 (simple_col, col3), \
1955 (simple_col, col3, col1), \
1956 (simple_col, col3, col1, col2), \
1957 (simple_col, col3, col1, col2, col3), \
1958 (simple_col, col1, col3), \
1959 (simple_col, col1, col3, col1), \
1960 (simple_col, col1, col3, col1, col2), \
1961 (simple_col, col1, col3, col1, col2, col3), \
1962 (simple_col, col2, col3), \
1963 (simple_col, col2, col3, col1), \
1964 (simple_col, col2, col3, col1, col2), \
1965 (simple_col, col2, col3, col1, col2, col3), \
1966 (simple_col, col1, col2, col3), \
1967 (simple_col, col1, col2, col3, col1), \
1968 (simple_col, col1, col2, col3, col1, col2), \
1969 (simple_col, col1, col2, col3, col1, col2, col3))]",
1970 &result
1971 );
1972
1973 Ok(())
1974 }
1975 #[test]
1976 fn test_split_conjunction() {
1977 let expr = col("a");
1978 let result = split_conjunction(&expr);
1979 assert_eq!(result, vec![&expr]);
1980 }
1981
1982 #[test]
1983 fn test_split_conjunction_two() {
1984 let expr = col("a").eq(lit(5)).and(col("b"));
1985 let expr1 = col("a").eq(lit(5));
1986 let expr2 = col("b");
1987
1988 let result = split_conjunction(&expr);
1989 assert_eq!(result, vec![&expr1, &expr2]);
1990 }
1991
1992 #[test]
1993 fn test_split_conjunction_alias() {
1994 let expr = col("a").eq(lit(5)).and(col("b").alias("the_alias"));
1995 let expr1 = col("a").eq(lit(5));
1996 let expr2 = col("b"); let result = split_conjunction(&expr);
1999 assert_eq!(result, vec![&expr1, &expr2]);
2000 }
2001
2002 #[test]
2003 fn test_split_conjunction_or() {
2004 let expr = col("a").eq(lit(5)).or(col("b"));
2005 let result = split_conjunction(&expr);
2006 assert_eq!(result, vec![&expr]);
2007 }
2008
2009 #[test]
2010 fn test_split_binary_owned() {
2011 let expr = col("a");
2012 assert_eq!(split_binary_owned(expr.clone(), Operator::And), vec![expr]);
2013 }
2014
2015 #[test]
2016 fn test_split_binary_owned_two() {
2017 assert_eq!(
2018 split_binary_owned(col("a").eq(lit(5)).and(col("b")), Operator::And),
2019 vec![col("a").eq(lit(5)), col("b")]
2020 );
2021 }
2022
2023 #[test]
2024 fn test_split_binary_owned_different_op() {
2025 let expr = col("a").eq(lit(5)).or(col("b"));
2026 assert_eq!(
2027 split_binary_owned(expr.clone(), Operator::And),
2029 vec![expr]
2030 );
2031 }
2032
2033 #[test]
2034 fn test_split_conjunction_owned() {
2035 let expr = col("a");
2036 assert_eq!(split_conjunction_owned(expr.clone()), vec![expr]);
2037 }
2038
2039 #[test]
2040 fn test_split_conjunction_owned_two() {
2041 assert_eq!(
2042 split_conjunction_owned(col("a").eq(lit(5)).and(col("b"))),
2043 vec![col("a").eq(lit(5)), col("b")]
2044 );
2045 }
2046
2047 #[test]
2048 fn test_split_conjunction_owned_alias() {
2049 assert_eq!(
2050 split_conjunction_owned(col("a").eq(lit(5)).and(col("b").alias("the_alias"))),
2051 vec![
2052 col("a").eq(lit(5)),
2053 col("b"),
2055 ]
2056 );
2057 }
2058
2059 #[test]
2060 fn test_conjunction_empty() {
2061 assert_eq!(conjunction(vec![]), None);
2062 }
2063
2064 #[test]
2065 fn test_conjunction() {
2066 let expr = conjunction(vec![col("a"), col("b"), col("c")]);
2068
2069 assert_eq!(expr, Some(col("a").and(col("b")).and(col("c"))));
2071
2072 assert_ne!(expr, Some(col("a").and(col("b").and(col("c")))));
2074 }
2075
2076 #[test]
2077 fn test_disjunction_empty() {
2078 assert_eq!(disjunction(vec![]), None);
2079 }
2080
2081 #[test]
2082 fn test_disjunction() {
2083 let expr = disjunction(vec![col("a"), col("b"), col("c")]);
2085
2086 assert_eq!(expr, Some(col("a").or(col("b")).or(col("c"))));
2088
2089 assert_ne!(expr, Some(col("a").or(col("b").or(col("c")))));
2091 }
2092
2093 #[test]
2094 fn test_split_conjunction_owned_or() {
2095 let expr = col("a").eq(lit(5)).or(col("b"));
2096 assert_eq!(split_conjunction_owned(expr.clone()), vec![expr]);
2097 }
2098
2099 #[test]
2100 fn test_collect_expr() -> Result<()> {
2101 let mut accum: HashSet<Column> = HashSet::new();
2102 expr_to_columns(
2103 &Expr::Cast(Cast::new(Box::new(col("a")), DataType::Float64)),
2104 &mut accum,
2105 )?;
2106 expr_to_columns(
2107 &Expr::Cast(Cast::new(Box::new(col("a")), DataType::Float64)),
2108 &mut accum,
2109 )?;
2110 assert_eq!(1, accum.len());
2111 assert!(accum.contains(&Column::from_name("a")));
2112 Ok(())
2113 }
2114
2115 #[test]
2116 fn test_can_hash() {
2117 let union_fields: UnionFields = [
2118 (0, Arc::new(Field::new("A", DataType::Int32, true))),
2119 (1, Arc::new(Field::new("B", DataType::Float64, true))),
2120 ]
2121 .into_iter()
2122 .collect();
2123
2124 let union_type = DataType::Union(union_fields, UnionMode::Sparse);
2125 assert!(!can_hash(&union_type));
2126
2127 let list_union_type =
2128 DataType::List(Arc::new(Field::new("my_union", union_type, true)));
2129 assert!(!can_hash(&list_union_type));
2130 }
2131
2132 #[test]
2133 fn test_generate_signature_error_msg_with_parameter_names() {
2134 let sig = Signature::one_of(
2135 vec![
2136 TypeSignature::Exact(vec![DataType::Utf8, DataType::Int64]),
2137 TypeSignature::Exact(vec![
2138 DataType::Utf8,
2139 DataType::Int64,
2140 DataType::Int64,
2141 ]),
2142 ],
2143 Volatility::Immutable,
2144 )
2145 .with_parameter_names(vec![
2146 "str".to_string(),
2147 "start_pos".to_string(),
2148 "length".to_string(),
2149 ])
2150 .expect("valid parameter names");
2151
2152 let error_msg =
2154 generate_signature_error_message("substr", &sig, &[DataType::Utf8]);
2155
2156 assert!(
2157 error_msg.contains("str: Utf8, start_pos: Int64"),
2158 "Expected 'str: Utf8, start_pos: Int64' in error message, got: {error_msg}"
2159 );
2160 assert!(
2161 error_msg.contains("str: Utf8, start_pos: Int64, length: Int64"),
2162 "Expected 'str: Utf8, start_pos: Int64, length: Int64' in error message, got: {error_msg}"
2163 );
2164 }
2165
2166 #[test]
2167 fn test_generate_signature_error_msg_without_parameter_names() {
2168 let sig = Signature::one_of(
2169 vec![TypeSignature::Any(2), TypeSignature::Any(3)],
2170 Volatility::Immutable,
2171 );
2172
2173 let error_msg =
2174 generate_signature_error_message("my_func", &sig, &[DataType::Int32]);
2175
2176 assert!(
2177 error_msg.contains("Any, Any"),
2178 "Expected 'Any, Any' without parameter names, got: {error_msg}"
2179 );
2180 }
2181
2182 #[test]
2183 fn test_signature_error_msg_exact() {
2184 use insta::assert_snapshot;
2185
2186 let sig = Signature::one_of(
2187 vec![
2188 TypeSignature::Exact(vec![DataType::Float64, DataType::Int64]),
2189 TypeSignature::Exact(vec![DataType::Float32, DataType::Int64]),
2190 TypeSignature::Exact(vec![DataType::Float64]),
2191 TypeSignature::Exact(vec![DataType::Float32]),
2192 ],
2193 Volatility::Immutable,
2194 );
2195 let msg = generate_signature_error_message(
2196 "round",
2197 &sig,
2198 &[DataType::Float64, DataType::Float64],
2199 );
2200 assert_snapshot!(msg, @r"
2201 No function matches the given name and argument types 'round(Float64, Float64)'. You might need to add explicit type casts.
2202 Candidate functions:
2203 round(Float64, Int64)
2204 round(Float32, Int64)
2205 round(Float64)
2206 round(Float32)
2207 ");
2208 }
2209
2210 #[test]
2211 fn test_signature_error_msg_coercible() {
2212 use datafusion_common::types::NativeType;
2213 use datafusion_expr_common::signature::{Coercion, TypeSignatureClass};
2214 use insta::assert_snapshot;
2215
2216 let sig = Signature::coercible(
2217 vec![
2218 Coercion::new_implicit(
2219 TypeSignatureClass::Native(
2220 datafusion_common::types::logical_float64(),
2221 ),
2222 vec![TypeSignatureClass::Numeric],
2223 NativeType::Float64,
2224 ),
2225 Coercion::new_implicit(
2226 TypeSignatureClass::Native(datafusion_common::types::logical_int64()),
2227 vec![TypeSignatureClass::Integer],
2228 NativeType::Int64,
2229 ),
2230 ],
2231 Volatility::Immutable,
2232 );
2233 let msg = generate_signature_error_message(
2234 "round",
2235 &sig,
2236 &[DataType::Utf8, DataType::Utf8],
2237 );
2238 assert_snapshot!(msg, @r"
2239 No function matches the given name and argument types 'round(Utf8, Utf8)'. You might need to add explicit type casts.
2240 Candidate functions:
2241 round(Float64, Int64)
2242 ");
2243 }
2244
2245 #[test]
2246 fn test_signature_error_msg_with_names_coercible() {
2247 use datafusion_common::types::NativeType;
2248 use datafusion_expr_common::signature::{Coercion, TypeSignatureClass};
2249 use insta::assert_snapshot;
2250
2251 let sig = Signature::coercible(
2252 vec![
2253 Coercion::new_exact(TypeSignatureClass::Native(
2254 datafusion_common::types::logical_string(),
2255 )),
2256 Coercion::new_exact(TypeSignatureClass::Native(
2257 datafusion_common::types::logical_int64(),
2258 )),
2259 Coercion::new_implicit(
2260 TypeSignatureClass::Native(datafusion_common::types::logical_int64()),
2261 vec![TypeSignatureClass::Integer],
2262 NativeType::Int64,
2263 ),
2264 ],
2265 Volatility::Immutable,
2266 )
2267 .with_parameter_names(vec![
2268 "string".to_string(),
2269 "start_pos".to_string(),
2270 "length".to_string(),
2271 ])
2272 .expect("valid parameter names");
2273
2274 let msg = generate_signature_error_message("substr", &sig, &[DataType::Int32]);
2275 assert_snapshot!(msg, @r"
2276 No function matches the given name and argument types 'substr(Int32)'. You might need to add explicit type casts.
2277 Candidate functions:
2278 substr(string: String, start_pos: Int64, length: Int64)
2279 ");
2280 }
2281
2282 fn sum_over(args: Vec<Expr>) -> Expr {
2284 Expr::from(WindowFunction::new(
2285 WindowFunctionDefinition::AggregateUDF(sum_udaf()),
2286 args,
2287 ))
2288 }
2289
2290 #[test]
2291 fn test_check_aggregate_and_window_nesting_ok() -> Result<()> {
2292 use crate::test::function_stub::{count, sum};
2293
2294 let exprs = [
2295 sum(col("a")),
2297 count(col("a")) + lit(1),
2298 sum_over(vec![col("a")]),
2300 sum_over(vec![sum(col("a"))]),
2301 ];
2302
2303 check_aggregate_and_window_nesting(exprs.iter())?;
2304 Ok(())
2305 }
2306
2307 #[test]
2308 fn test_check_aggregate_and_window_nesting_err() {
2309 use crate::test::function_stub::{count, sum};
2310 use insta::assert_snapshot;
2311
2312 let err = check_aggregate_and_window_nesting([&sum(sum(col("a")))]).unwrap_err();
2314 assert_snapshot!(
2315 err.strip_backtrace(),
2316 @"Error during planning: Aggregate function calls cannot be nested: 'sum(a)' is nested inside 'sum(sum(a))'"
2317 );
2318
2319 let err = check_aggregate_and_window_nesting([&sum(col("a") + count(col("b")))])
2321 .unwrap_err();
2322 assert_snapshot!(
2323 err.strip_backtrace(),
2324 @"Error during planning: Aggregate function calls cannot be nested: 'COUNT(b)' is nested inside 'sum(a + COUNT(b))'"
2325 );
2326
2327 let filtered = sum(col("a"))
2329 .filter(sum(col("b")).gt(lit(0)))
2330 .build()
2331 .unwrap();
2332 let err = check_aggregate_and_window_nesting([&filtered]).unwrap_err();
2333 assert_snapshot!(
2334 err.strip_backtrace(),
2335 @"Error during planning: Aggregate function calls cannot be nested: 'sum(b)' is nested inside 'sum(a) FILTER (WHERE sum(b) > Int32(0))'"
2336 );
2337
2338 let ordered = sum(col("a"))
2340 .order_by(vec![Sort::new(sum(col("b")), true, false)])
2341 .build()
2342 .unwrap();
2343 let err = check_aggregate_and_window_nesting([&ordered]).unwrap_err();
2344 assert_snapshot!(
2345 err.strip_backtrace(),
2346 @"Error during planning: Aggregate function calls cannot be nested: 'sum(b)' is nested inside 'sum(a) ORDER BY [sum(b) ASC NULLS LAST]'"
2347 );
2348
2349 let err = check_aggregate_and_window_nesting([&sum(sum_over(vec![col("a")]))])
2351 .unwrap_err();
2352 assert_snapshot!(
2353 err.strip_backtrace(),
2354 @"Error during planning: Aggregate function calls cannot contain window function calls: 'sum(a) ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING' is nested inside 'sum(sum(a) ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)'"
2355 );
2356
2357 let err =
2359 check_aggregate_and_window_nesting([&sum_over(vec![sum_over(vec![col(
2360 "a",
2361 )])])])
2362 .unwrap_err();
2363 assert_snapshot!(
2364 err.strip_backtrace(),
2365 @"Error during planning: Window function calls cannot be nested: 'sum(a) ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING' is nested inside 'sum(sum(a) ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING'"
2366 );
2367 }
2368
2369 #[test]
2370 fn test_check_no_window_functions() -> Result<()> {
2371 use crate::test::function_stub::sum;
2372 use insta::assert_snapshot;
2373
2374 check_no_window_functions(&col("a"), "WHERE")?;
2376 check_no_window_functions(&(col("a") + lit(1)).gt(lit(0)), "WHERE")?;
2377 check_no_window_functions(&sum(col("a")).gt(lit(0)), "HAVING")?;
2378
2379 let err =
2381 check_no_window_functions(&sum_over(vec![col("a")]), "WHERE").unwrap_err();
2382 assert_snapshot!(
2383 err.strip_backtrace(),
2384 @"Error during planning: Window function calls are not allowed in WHERE: 'sum(a) ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING'"
2385 );
2386 let diag = err.diagnostic().expect("diagnostic");
2387 assert_snapshot!(
2388 diag.message,
2389 @"Window function calls are not allowed in WHERE"
2390 );
2391 assert_snapshot!(
2392 diag.helps[0].message,
2393 @"Compute 'sum(a) ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING' first, in a Window node or an inner query, and filter on its result"
2394 );
2395
2396 let predicate = sum_over(vec![sum(col("a"))]).gt(lit(10)).and(col("b"));
2399 let err = check_no_window_functions(&predicate, "HAVING").unwrap_err();
2400 assert_snapshot!(
2401 err.strip_backtrace(),
2402 @"Error during planning: Window function calls are not allowed in HAVING: 'sum(sum(a)) ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING'"
2403 );
2404
2405 Ok(())
2406 }
2407
2408 #[test]
2409 fn find_valid_equijoin_key_pair_inputs_of_different_widths() -> Result<()> {
2410 let schema = |name: &str, width: usize| {
2411 let fields = (0..width)
2412 .map(|i| Field::new(format!("c{i}"), DataType::Int32, false))
2413 .collect::<Vec<_>>();
2414 DFSchema::try_from_qualified_schema(name, &Schema::new(fields))
2415 };
2416 let narrow = schema("n", 1)?;
2417 let wide = schema("w", 3)?;
2418 let other = col("o.c0");
2419
2420 for (left_schema, right_schema, left, right) in [
2422 (&narrow, &wide, col("n.c0"), col("w.c2")),
2423 (&wide, &narrow, col("w.c2"), col("n.c0")),
2424 ] {
2425 let find = |left_key: &Expr, right_key: &Expr| {
2426 find_valid_equijoin_key_pair(
2427 left_key,
2428 right_key,
2429 left_schema,
2430 right_schema,
2431 )
2432 };
2433 let expected = Some((left.clone(), right.clone()));
2434 assert_eq!(find(&left, &right)?, expected);
2435 assert_eq!(find(&right, &left)?, expected);
2436 assert_eq!(find(&left, &other)?, None);
2437 assert_eq!(find(&other, &right)?, None);
2438 assert_eq!(find(&(left.clone() + right.clone()), &right)?, None);
2439 }
2440 Ok(())
2441 }
2442}