1use std::fmt::Debug;
8use std::sync::Arc;
9
10use crate::PhysicalExpr;
11use crate::expressions::Column;
12use crate::intervals::cp_solver::{ExprIntervalGraph, PropagationResult};
13use crate::utils::collect_columns;
14
15use arrow::datatypes::Schema;
16use datafusion_common::stats::Precision;
17use datafusion_common::{
18 ColumnStatistics, Result, ScalarValue, assert_or_internal_err,
19 internal_datafusion_err, internal_err,
20};
21use datafusion_expr::interval_arithmetic::{Interval, cardinality_ratio};
22
23#[derive(Clone, Debug, PartialEq)]
26pub struct AnalysisContext {
27 pub boundaries: Vec<ExprBoundaries>,
30 pub selectivity: Option<f64>,
34}
35
36impl AnalysisContext {
37 pub fn new(boundaries: Vec<ExprBoundaries>) -> Self {
38 Self {
39 boundaries,
40 selectivity: None,
41 }
42 }
43
44 pub fn with_selectivity(mut self, selectivity: f64) -> Self {
45 self.selectivity = Some(selectivity);
46 self
47 }
48
49 pub fn try_from_statistics(
51 input_schema: &Schema,
52 statistics: &[ColumnStatistics],
53 ) -> Result<Self> {
54 statistics
55 .iter()
56 .enumerate()
57 .map(|(idx, stats)| ExprBoundaries::try_from_column(input_schema, stats, idx))
58 .collect::<Result<Vec<_>>>()
59 .map(Self::new)
60 }
61}
62
63#[derive(Clone, Debug, PartialEq)]
70pub struct ExprBoundaries {
71 pub column: Column,
72 pub interval: Option<Interval>,
78 pub distinct_count: Precision<usize>,
80}
81
82impl ExprBoundaries {
83 pub fn try_from_column(
85 schema: &Schema,
86 col_stats: &ColumnStatistics,
87 col_index: usize,
88 ) -> Result<Self> {
89 let field = schema.fields().get(col_index).ok_or_else(|| {
90 internal_datafusion_err!(
91 "Could not create `ExprBoundaries`: in `try_from_column` `col_index`
92 has gone out of bounds with a value of {col_index}, the schema has {} columns.",
93 schema.fields.len()
94 )
95 })?;
96 let empty_field =
97 ScalarValue::try_from(field.data_type()).unwrap_or(ScalarValue::Null);
98 let interval = Interval::try_new(
99 col_stats
100 .min_value
101 .get_value()
102 .cloned()
103 .unwrap_or_else(|| empty_field.clone()),
104 col_stats
105 .max_value
106 .get_value()
107 .cloned()
108 .unwrap_or(empty_field),
109 )?;
110 let column = Column::new(field.name(), col_index);
111 Ok(ExprBoundaries {
112 column,
113 interval: Some(interval),
114 distinct_count: col_stats.distinct_count,
115 })
116 }
117
118 pub fn try_new_unbounded(schema: &Schema) -> Result<Vec<Self>> {
121 schema
122 .fields()
123 .iter()
124 .enumerate()
125 .map(|(i, field)| {
126 Ok(Self {
127 column: Column::new(field.name(), i),
128 interval: Some(Interval::make_unbounded(field.data_type())?),
129 distinct_count: Precision::Absent,
130 })
131 })
132 .collect()
133 }
134}
135
136pub fn analyze(
152 expr: &Arc<dyn PhysicalExpr>,
153 context: AnalysisContext,
154 schema: &Schema,
155) -> Result<AnalysisContext> {
156 let initial_boundaries = &context.boundaries;
157
158 if initial_boundaries
159 .iter()
160 .all(|bound| bound.interval.is_none())
161 {
162 assert_or_internal_err!(
163 !initial_boundaries
164 .iter()
165 .any(|bound| bound.distinct_count != Precision::Exact(0)),
166 "ExprBoundaries has a non-zero distinct count although it represents an empty table"
167 );
168 assert_or_internal_err!(
169 context.selectivity.unwrap_or(0.0) == 0.0,
170 "AnalysisContext has a non-zero selectivity although it represents an empty table"
171 );
172 Ok(context)
173 } else if initial_boundaries
174 .iter()
175 .any(|bound| bound.interval.is_none())
176 {
177 internal_err!(
178 "AnalysisContext is an inconsistent state. Some columns represent empty table while others don't"
179 )
180 } else {
181 let mut target_boundaries = context.boundaries;
182 let mut graph = ExprIntervalGraph::try_new(Arc::clone(expr), schema)?;
183 let columns = collect_columns(expr)
184 .into_iter()
185 .map(|c| Arc::new(c) as _)
186 .collect::<Vec<_>>();
187
188 let target_expr_and_indices = graph.gather_node_indices(columns.as_slice());
189 let mut target_indices_and_boundaries =
190 Vec::with_capacity(target_expr_and_indices.len());
191
192 for (expr, index) in &target_expr_and_indices {
193 if let Some(column) = expr.downcast_ref::<Column>()
194 && let Some(bound) =
195 target_boundaries.iter().find(|b| b.column == *column)
196 {
197 target_indices_and_boundaries
199 .push((*index, bound.interval.as_ref().unwrap().clone()));
200 }
201 }
202
203 match graph.update_ranges(&mut target_indices_and_boundaries, Interval::TRUE)? {
204 PropagationResult::Success => {
205 shrink_boundaries(&graph, target_boundaries, &target_expr_and_indices)
206 }
207 PropagationResult::Infeasible => {
208 for bound in &mut target_boundaries {
210 bound.interval = None;
211 }
212 Ok(AnalysisContext::new(target_boundaries).with_selectivity(0.0))
213 }
214 PropagationResult::CannotPropagate => {
215 Ok(AnalysisContext::new(target_boundaries).with_selectivity(1.0))
216 }
217 }
218 }
219}
220
221fn shrink_boundaries(
226 graph: &ExprIntervalGraph,
227 mut target_boundaries: Vec<ExprBoundaries>,
228 target_expr_and_indices: &[(Arc<dyn PhysicalExpr>, usize)],
229) -> Result<AnalysisContext> {
230 let initial_boundaries = target_boundaries.clone();
231 for (expr, i) in target_expr_and_indices {
232 if let Some(column) = expr.downcast_ref::<Column>()
233 && let Some(bound) = target_boundaries
234 .iter_mut()
235 .find(|bound| bound.column.eq(column))
236 {
237 bound.interval = Some(graph.get_interval(*i));
238 }
239 }
240
241 let selectivity = calculate_selectivity(&target_boundaries, &initial_boundaries)?;
242
243 assert_or_internal_err!(
244 (0.0..=1.0).contains(&selectivity),
245 "Selectivity is out of limit: {selectivity}",
246 );
247
248 Ok(AnalysisContext::new(target_boundaries).with_selectivity(selectivity))
249}
250
251fn singleton_selectivity(
262 initial_interval: &Interval,
263 target_interval: &Interval,
264 distinct_count: usize,
265) -> Option<f64> {
266 if distinct_count == 0
268 || target_interval.lower().is_null()
269 || target_interval.lower() != target_interval.upper()
270 {
271 return None;
272 }
273
274 let initial_is_same_singleton = !initial_interval.lower().is_null()
279 && initial_interval.lower() == initial_interval.upper()
280 && initial_interval.lower() == target_interval.lower();
281
282 if initial_is_same_singleton {
283 return None;
284 }
285
286 Some(1.0 / distinct_count as f64)
287}
288
289fn calculate_selectivity(
293 target_boundaries: &[ExprBoundaries],
294 initial_boundaries: &[ExprBoundaries],
295) -> Result<f64> {
296 if target_boundaries.len() != initial_boundaries.len() {
300 return Err(internal_datafusion_err!(
301 "The number of columns in the initial and target boundaries should be the same"
302 ));
303 }
304 let mut acc: f64 = 1.0;
305 for (initial, target) in initial_boundaries.iter().zip(target_boundaries) {
306 match (initial.interval.as_ref(), target.interval.as_ref()) {
307 (Some(initial_interval), Some(target_interval)) => {
308 if let Precision::Exact(distinct_count)
309 | Precision::Inexact(distinct_count) = target.distinct_count
310 && let Some(s) = singleton_selectivity(
311 initial_interval,
312 target_interval,
313 distinct_count,
314 )
315 {
316 acc *= s;
317 continue;
318 }
319 acc *= cardinality_ratio(initial_interval, target_interval);
320 }
321 (None, Some(_)) => {
322 return internal_err!(
323 "Initial boundary cannot be None while having a Some() target boundary"
324 );
325 }
326 _ => return Ok(0.0),
327 }
328 }
329
330 Ok(acc)
331}
332
333#[cfg(test)]
334mod tests {
335 use std::ops::Not;
336 use std::sync::Arc;
337
338 use arrow::datatypes::{DataType, Field, Schema};
339 use datafusion_common::{DFSchema, ScalarValue, assert_contains, stats::Precision};
340 use datafusion_expr::{
341 Expr, col, execution_props::ExecutionProps, interval_arithmetic::Interval, lit,
342 physical_planning_context::PhysicalPlanningContext,
343 };
344
345 use crate::{AnalysisContext, create_physical_expr, expressions::Column};
346
347 use super::{ExprBoundaries, analyze, calculate_selectivity, singleton_selectivity};
348
349 fn make_field(name: &str, data_type: DataType) -> Field {
350 let nullable = false;
351 Field::new(name, data_type, nullable)
352 }
353
354 #[test]
355 fn test_analyze_boundary_exprs() {
356 let schema = Arc::new(Schema::new(vec![make_field("a", DataType::Int32)]));
357
358 type TestCase = (Expr, Option<i32>, Option<i32>);
360
361 let test_cases: Vec<TestCase> = vec![
362 (col("a").gt(lit(10)), Some(11), None),
364 (col("a").lt(lit(20)), None, Some(19)),
366 (
368 col("a").gt(lit(10)).and(col("a").lt(lit(20))),
369 Some(11),
370 Some(19),
371 ),
372 (col("a").gt_eq(lit(10)), Some(10), None),
374 (col("a").lt_eq(lit(20)), None, Some(20)),
376 (
378 col("a").gt_eq(lit(10)).and(col("a").lt_eq(lit(20))),
379 Some(10),
380 Some(20),
381 ),
382 (
384 col("a")
385 .gt(lit(10))
386 .and(col("a").lt(lit(20)))
387 .and(col("a").lt(lit(15))),
388 Some(11),
389 Some(14),
390 ),
391 (
393 col("a")
394 .gt(lit(10))
395 .and(col("a").lt(lit(20)))
396 .and(col("a").gt(lit(15)))
397 .and(col("a").lt(lit(25))),
398 Some(16),
399 Some(19),
400 ),
401 ];
402 for (expr, lower, upper) in test_cases {
403 let boundaries = ExprBoundaries::try_new_unbounded(&schema).unwrap();
404 let df_schema = DFSchema::try_from(Arc::clone(&schema)).unwrap();
405 let physical_expr = create_physical_expr(
406 &expr,
407 &df_schema,
408 &ExecutionProps::new(),
409 &PhysicalPlanningContext::default(),
410 )
411 .unwrap();
412 let analysis_result = analyze(
413 &physical_expr,
414 AnalysisContext::new(boundaries),
415 df_schema.as_ref(),
416 )
417 .unwrap();
418 let Some(actual) = &analysis_result.boundaries[0].interval else {
419 panic!(
420 "The analysis result should contain non-empty intervals for all columns"
421 );
422 };
423 let expected = Interval::make(lower, upper).unwrap();
424 assert_eq!(
425 &expected, actual,
426 "did not get correct interval for SQL expression: {expr:?}"
427 );
428 }
429 }
430
431 #[test]
432 fn test_analyze_empty_set_boundary_exprs() {
433 let schema = Arc::new(Schema::new(vec![make_field("a", DataType::Int32)]));
434
435 let test_cases: Vec<Expr> = vec![
436 col("a").gt(lit(10)).and(col("a").lt(lit(10))),
438 col("a")
442 .gt(lit(10))
443 .and(col("a").lt(lit(20)))
444 .and(col("a").gt(lit(20)))
445 .and(col("a").lt(lit(30))),
446 ];
447
448 for expr in test_cases {
449 let boundaries = ExprBoundaries::try_new_unbounded(&schema).unwrap();
450 let df_schema = DFSchema::try_from(Arc::clone(&schema)).unwrap();
451 let physical_expr = create_physical_expr(
452 &expr,
453 &df_schema,
454 &ExecutionProps::new(),
455 &PhysicalPlanningContext::default(),
456 )
457 .unwrap();
458 let analysis_result = analyze(
459 &physical_expr,
460 AnalysisContext::new(boundaries),
461 df_schema.as_ref(),
462 )
463 .unwrap();
464
465 for boundary in analysis_result.boundaries {
466 assert!(boundary.interval.is_none());
467 }
468 }
469 }
470
471 #[test]
472 fn test_analyze_invalid_boundary_exprs() {
473 let schema = Arc::new(Schema::new(vec![make_field("a", DataType::Int32)]));
474 let expr = col("a").lt(lit(10)).or(col("a").gt(lit(20)));
475 let expected_error = "OR operator cannot yet propagate true intervals";
476 let boundaries = ExprBoundaries::try_new_unbounded(&schema).unwrap();
477 let df_schema = DFSchema::try_from(Arc::clone(&schema)).unwrap();
478 let physical_expr = create_physical_expr(
479 &expr,
480 &df_schema,
481 &ExecutionProps::new(),
482 &PhysicalPlanningContext::default(),
483 )
484 .unwrap();
485 let analysis_error = analyze(
486 &physical_expr,
487 AnalysisContext::new(boundaries),
488 df_schema.as_ref(),
489 )
490 .unwrap_err();
491 assert_contains!(analysis_error.to_string(), expected_error);
492 }
493
494 fn make_boundary(lower: i32, upper: i32, distinct_count: usize) -> ExprBoundaries {
499 ExprBoundaries {
500 column: Column::new("a", 0),
501 interval: Some(
502 Interval::try_new(
503 ScalarValue::Int32(Some(lower)),
504 ScalarValue::Int32(Some(upper)),
505 )
506 .unwrap(),
507 ),
508 distinct_count: Precision::Exact(distinct_count),
509 }
510 }
511
512 #[test]
516 fn test_singleton_selectivity_skipped_when_initial_is_same_singleton() {
517 let singleton =
518 Interval::try_new(ScalarValue::Int32(Some(5)), ScalarValue::Int32(Some(5)))
519 .unwrap();
520 assert_eq!(
522 singleton_selectivity(&singleton, &singleton, 10),
523 None,
524 "shortcut must not fire when initial interval was already the same singleton"
525 );
526 }
527
528 #[test]
531 fn test_singleton_selectivity_applied_when_range_collapses() {
532 let initial =
533 Interval::try_new(ScalarValue::Int32(Some(1)), ScalarValue::Int32(Some(100)))
534 .unwrap();
535 let target =
536 Interval::try_new(ScalarValue::Int32(Some(5)), ScalarValue::Int32(Some(5)))
537 .unwrap();
538 let result = singleton_selectivity(&initial, &target, 10);
539 assert_eq!(
540 result,
541 Some(0.1),
542 "shortcut must return 1/NDV when a range collapses to a singleton"
543 );
544 }
545
546 #[test]
552 fn test_calculate_selectivity_already_singleton_initial_interval() {
553 let already_singleton = make_boundary(7, 7, 1);
554
555 let selectivity = calculate_selectivity(
556 std::slice::from_ref(&already_singleton),
557 std::slice::from_ref(&already_singleton),
558 )
559 .unwrap();
560
561 let wide_initial = make_boundary(1, 100, 50);
562 let same_singleton_target = make_boundary(7, 7, 50);
563 let selectivity_new =
564 calculate_selectivity(&[same_singleton_target], &[wide_initial]).unwrap();
565 assert!(
566 (selectivity_new - 0.02).abs() < 1e-10,
567 "expected selectivity 1/NDV = 0.02, got {selectivity_new}"
568 );
569
570 let singleton_initial = make_boundary(7, 7, 50);
571 let singleton_target = make_boundary(7, 7, 50);
572 let selectivity_no_new_filter =
573 calculate_selectivity(&[singleton_target], &[singleton_initial]).unwrap();
574 assert!(
575 (selectivity_no_new_filter - 1.0).abs() < 1e-10,
576 "expected selectivity 1.0 when initial was already the same singleton, got {selectivity_no_new_filter}"
577 );
578
579 let _ = selectivity; }
581
582 fn analyze_not_eq_helper(
590 lower: f32,
591 upper: f32,
592 ) -> datafusion_common::Result<Option<Interval>> {
593 let schema = Arc::new(Schema::new(vec![make_field("a", DataType::Float32)]));
594 let df_schema = DFSchema::try_from(Arc::clone(&schema)).unwrap();
595
596 let boundaries = vec![ExprBoundaries {
598 column: Column::new("a", 0),
599 interval: Some(Interval::try_new(
600 ScalarValue::Float32(Some(lower)),
601 ScalarValue::Float32(Some(upper)),
602 )?),
603 distinct_count: Precision::Inexact(100),
604 }];
605 let ctx = AnalysisContext::new(boundaries);
606
607 let pred_not_eq = col("a").eq(lit(0.0f32)).not();
609 let phys_not = create_physical_expr(
610 &pred_not_eq,
611 &df_schema,
612 &ExecutionProps::new(),
613 &PhysicalPlanningContext::default(),
614 )?;
615 let out = analyze(&phys_not, ctx, df_schema.as_ref())?;
616 Ok(out.boundaries[0].interval.clone())
617 }
618
619 #[test]
620 fn test_analyze_not_eq_around_zero() -> datafusion_common::Result<()> {
621 let out = analyze_not_eq_helper(-1.0, 1.0)?;
625 let expected = Some(Interval::try_new(
626 ScalarValue::Float32(Some(-1.0)),
627 ScalarValue::Float32(Some(1.0)),
628 )?);
629 assert_eq!(
630 out, expected,
631 "NOT (a = 0.0) over [-1, 1] should yield [-1, 1], got {out:?}"
632 );
633 Ok(())
634 }
635
636 #[test]
637 fn test_analyze_not_eq_clamped_at_zero() -> datafusion_common::Result<()> {
638 let out = analyze_not_eq_helper(0.0, 0.0)?;
641 assert_eq!(
642 out, None,
643 "NOT (a = 0.0) over [0, 0] should yield None (infeasible), got {out:?}"
644 );
645 Ok(())
646 }
647
648 fn analyze_not_eq_f64_helper(
649 lower: f64,
650 upper: f64,
651 ) -> datafusion_common::Result<Option<Interval>> {
652 let schema = Arc::new(Schema::new(vec![make_field("a", DataType::Float64)]));
653 let df_schema = DFSchema::try_from(Arc::clone(&schema)).unwrap();
654
655 let boundaries = vec![ExprBoundaries {
656 column: Column::new("a", 0),
657 interval: Some(Interval::try_new(
658 ScalarValue::Float64(Some(lower)),
659 ScalarValue::Float64(Some(upper)),
660 )?),
661 distinct_count: Precision::Inexact(100),
662 }];
663 let ctx = AnalysisContext::new(boundaries);
664
665 let pred_not_eq = col("a").eq(lit(0.0f64)).not();
666 let phys_not = create_physical_expr(
667 &pred_not_eq,
668 &df_schema,
669 &ExecutionProps::new(),
670 &PhysicalPlanningContext::default(),
671 )?;
672 let out = analyze(&phys_not, ctx, df_schema.as_ref())?;
673 Ok(out.boundaries[0].interval.clone())
674 }
675
676 #[test]
686 fn test_analyze_not_eq_signed_zero_span_infeasible() -> datafusion_common::Result<()>
687 {
688 let out = analyze_not_eq_helper(-0.0, 0.0)?;
689 assert_eq!(
690 out, None,
691 "NOT (a = 0.0) over Float32 [-0.0, +0.0] should yield None (infeasible), got {out:?}"
692 );
693
694 let out = analyze_not_eq_f64_helper(-0.0, 0.0)?;
695 assert_eq!(
696 out, None,
697 "NOT (a = 0.0) over Float64 [-0.0, +0.0] should yield None (infeasible), got {out:?}"
698 );
699 Ok(())
700 }
701
702 fn analyze_between_helper(
703 lower: f32,
704 upper: f32,
705 negated: bool,
706 explicit_not: bool,
707 ) -> datafusion_common::Result<Option<Interval>> {
708 let schema = Arc::new(Schema::new(vec![make_field("a", DataType::Float32)]));
709 let df_schema = DFSchema::try_from(Arc::clone(&schema)).unwrap();
710 let boundaries = vec![ExprBoundaries {
711 column: Column::new("a", 0),
712 interval: Some(Interval::try_new(
713 ScalarValue::Float32(Some(lower)),
714 ScalarValue::Float32(Some(upper)),
715 )?),
716 distinct_count: Precision::Inexact(100),
717 }];
718
719 let between = col("a").between(lit(-1.0f32), lit(1.0f32));
720 let predicate = if explicit_not {
721 between.not()
722 } else if negated {
723 col("a").not_between(lit(-1.0f32), lit(1.0f32))
724 } else {
725 between
726 };
727 let physical_expr = create_physical_expr(
728 &predicate,
729 &df_schema,
730 &ExecutionProps::new(),
731 &PhysicalPlanningContext::default(),
732 )?;
733 let output = analyze(
734 &physical_expr,
735 AnalysisContext::new(boundaries),
736 df_schema.as_ref(),
737 )?;
738 Ok(output.boundaries[0].interval.clone())
739 }
740
741 #[test]
742 fn test_analyze_not_between_clamped() -> datafusion_common::Result<()> {
743 let expected = Some(Interval::try_new(
744 ScalarValue::Float32(Some(-1.0)),
745 ScalarValue::Float32(Some(1.0)),
746 )?);
747 assert_eq!(analyze_between_helper(-1.0, 1.0, false, false)?, expected);
748 assert_eq!(analyze_between_helper(-1.0, 1.0, true, false)?, None);
749 assert_eq!(analyze_between_helper(-1.0, 1.0, false, true)?, None);
750 Ok(())
751 }
752
753 #[test]
754 fn test_analyze_not_between_containing() -> datafusion_common::Result<()> {
755 let between = Some(Interval::try_new(
756 ScalarValue::Float32(Some(-1.0)),
757 ScalarValue::Float32(Some(1.0)),
758 )?);
759 let containing = Some(Interval::try_new(
760 ScalarValue::Float32(Some(-2.0)),
761 ScalarValue::Float32(Some(2.0)),
762 )?);
763 assert_eq!(analyze_between_helper(-2.0, 2.0, false, false)?, between);
764 assert_eq!(analyze_between_helper(-2.0, 2.0, true, false)?, containing);
765 assert_eq!(analyze_between_helper(-2.0, 2.0, false, true)?, containing);
766 Ok(())
767 }
768
769 #[test]
781 fn test_analyze_not_eq_nested_signed_zero_infeasible() -> datafusion_common::Result<()>
782 {
783 let schema = Arc::new(Schema::new(vec![
784 make_field("a", DataType::Float32),
785 make_field("b", DataType::Boolean),
786 ]));
787 let df_schema = DFSchema::try_from(Arc::clone(&schema)).unwrap();
788
789 let boundaries = vec![
790 ExprBoundaries {
791 column: Column::new("a", 0),
792 interval: Some(Interval::try_new(
793 ScalarValue::Float32(Some(-0.0f32)),
794 ScalarValue::Float32(Some(-0.0f32)),
795 )?),
796 distinct_count: Precision::Inexact(1),
797 },
798 ExprBoundaries {
799 column: Column::new("b", 1),
800 interval: Some(Interval::try_new(
801 ScalarValue::Boolean(Some(false)),
802 ScalarValue::Boolean(Some(true)),
803 )?),
804 distinct_count: Precision::Inexact(2),
805 },
806 ];
807 let ctx = AnalysisContext::new(boundaries);
808
809 let pred = col("a").eq(lit(0.0f32)).not().and(col("b"));
811 let phys = create_physical_expr(
812 &pred,
813 &df_schema,
814 &ExecutionProps::new(),
815 &PhysicalPlanningContext::default(),
816 )?;
817 let out = analyze(&phys, ctx, df_schema.as_ref())?;
818
819 assert!(
822 out.boundaries.iter().all(|b| b.interval.is_none()),
823 "NOT(a = +0.0) AND b over a=[-0.0,-0.0] should be infeasible (all boundaries None), got {:?}",
824 out.boundaries
825 );
826 assert_eq!(
827 out.selectivity,
828 Some(0.0),
829 "selectivity should be 0.0 for an infeasible predicate, got {:?}",
830 out.selectivity
831 );
832 Ok(())
833 }
834}