Apache DataFusion SQL Query Engine
Support "A column is known to be entirely NULL" in `PruningPredicate` (#9223)
Chunchun Yefa7ca27c1532
diff --git a/datafusion-examples/examples/pruning.rs b/datafusion-examples/examples/pruning.rsindex 1d84fc2d1e..3fa35049a8 100644--- a/datafusion-examples/examples/pruning.rs+++ b/datafusion-examples/examples/pruning.rs@@ -163,6 +163,11 @@ impl PruningStatistics for MyCatalog {None}+ fn row_counts(&self, _column: &Column) -> Option<ArrayRef> {+ // In this example, we know nothing about the number of rows in each file+ None+ }+fn contained(&self,_column: &Column,diff --git a/datafusion/core/src/datasource/physical_plan/parquet/mod.rs b/datafusion/core/src/datasource/physical_plan/parquet/mod.rsindex 2cfbb578da..a2e645cf3e 100644--- a/datafusion/core/src/datasource/physical_plan/parquet/mod.rs+++ b/datafusion/core/src/datasource/physical_plan/parquet/mod.rs@@ -1870,7 +1870,7 @@ mod tests {assert_contains!(&display,- "pruning_predicate=c1_min@0 != bar OR bar != c1_max@1"+ "pruning_predicate=CASE WHEN c1_null_count@2 = c1_row_count@3 THEN false ELSE c1_min@0 != bar OR bar != c1_max@1 END");assert_contains!(&display, r#"predicate=c1@0 != bar"#);diff --git a/datafusion/core/src/datasource/physical_plan/parquet/page_filter.rs b/datafusion/core/src/datasource/physical_plan/parquet/page_filter.rsindex 064a8e1fff..c7706f3458 100644--- a/datafusion/core/src/datasource/physical_plan/parquet/page_filter.rs+++ b/datafusion/core/src/datasource/physical_plan/parquet/page_filter.rs@@ -547,6 +547,10 @@ impl<'a> PruningStatistics for PagesPruningStatistics<'a> {}}+ fn row_counts(&self, _column: &datafusion_common::Column) -> Option<ArrayRef> {+ None+ }+fn contained(&self,_column: &datafusion_common::Column,diff --git a/datafusion/core/src/datasource/physical_plan/parquet/row_groups.rs b/datafusion/core/src/datasource/physical_plan/parquet/row_groups.rsindex 1a84f52a33..a0bb5ab712 100644--- a/datafusion/core/src/datasource/physical_plan/parquet/row_groups.rs+++ b/datafusion/core/src/datasource/physical_plan/parquet/row_groups.rs@@ -199,6 +199,10 @@ impl PruningStatistics for BloomFilterStatistics {None}+ fn row_counts(&self, _column: &Column) -> Option<ArrayRef> {+ None+ }+/// Use bloom filters to determine if we are sure this column can not/// possibly contain `values`///@@ -332,6 +336,10 @@ impl<'a> PruningStatistics for RowGroupPruningStatistics<'a> {scalar.to_array().ok()}+ fn row_counts(&self, _column: &Column) -> Option<ArrayRef> {+ None+ }+fn contained(&self,_column: &Column,diff --git a/datafusion/core/src/physical_optimizer/pruning.rs b/datafusion/core/src/physical_optimizer/pruning.rsindex d2126f90ec..80bb5ad42e 100644--- a/datafusion/core/src/physical_optimizer/pruning.rs+++ b/datafusion/core/src/physical_optimizer/pruning.rs@@ -53,7 +53,7 @@ use log::trace;////// 1. Minimum and maximum values for columns///-/// 2. Null counts for columns+/// 2. Null counts and row counts for columns////// 3. Whether the values in a column are contained in a set of literals///@@ -100,7 +100,8 @@ pub trait PruningStatistics {/// these statistics.////// This value corresponds to the size of the [`ArrayRef`] returned by- /// [`Self::min_values`], [`Self::max_values`], and [`Self::null_counts`].+ /// [`Self::min_values`], [`Self::max_values`], [`Self::null_counts`],+ /// and [`Self::row_counts`].fn num_containers(&self) -> usize;/// Return the number of null values for the named column as an@@ -111,6 +112,14 @@ pub trait PruningStatistics {/// Note: the returned array must contain [`Self::num_containers`] rowsfn null_counts(&self, column: &Column) -> Option<ArrayRef>;+ /// Return the number of rows for the named column in each container+ /// as an `Option<UInt64Array>`.+ ///+ /// See [`Self::min_values`] for when to return `None` and null values.+ ///+ /// Note: the returned array must contain [`Self::num_containers`] rows+ fn row_counts(&self, column: &Column) -> Option<ArrayRef>;+/// Returns [`BooleanArray`] where each row represents information known/// about specific literal `values` in a column.///@@ -268,7 +277,7 @@ pub trait PruningStatistics {/// 3. [`PruningStatistics`] that provides information about columns in that/// schema, for multiple “containers”. For each column in each container, it/// provides optional information on contained values, min_values, max_values,-/// and null_counts counts.+/// null_counts counts, and row_counts counts.////// **Outputs**:/// A (non null) boolean value for each container:@@ -306,17 +315,23 @@ pub trait PruningStatistics {/// * `false`: there are no rows that could possibly match the predicate,/// **PRUNES** the container///-/// For example, given a column `x`, the `x_min` and `x_max` and `x_null_count`-/// represent the minimum and maximum values, and the null count of column `x`,-/// provided by the `PruningStatistics`. Here are some examples of the rewritten-/// predicates:+/// For example, given a column `x`, the `x_min`, `x_max`, `x_null_count`, and+/// `x_row_count` represent the minimum and maximum values, the null count of+/// column `x`, and the row count of column `x`, provided by the `PruningStatistics`.+/// `x_null_count` and `x_row_count` are used to handle the case where the column `x`+/// is known to be all `NULL`s. Note this is different from knowing nothing about+/// the column `x`, which confusingly is encoded by returning `NULL` for the min/max+/// values from [`PruningStatistics::max_values`] and [`PruningStatistics::min_values`].+///+/// Here are some examples of the rewritten predicates:////// Original Predicate | Rewritten Predicate/// ------------------ | ---------------------/// `x = 5` | `x_min <= 5 AND 5 <= x_max`-/// `x < 5` | `x_max < 5`-/// `x = 5 AND y = 10` | `x_min <= 5 AND 5 <= x_max AND y_min <= 10 AND 10 <= y_max`-/// `x IS NULL` | `x_null_count > 0`+/// `x = 5` | `CASE WHEN x_null_count = x_row_count THEN false ELSE x_min <= 5 AND 5 <= x_max END`+/// `x < 5` | `CASE WHEN x_null_count = x_row_count THEN false ELSE x_max < 5 END`+/// `x = 5 AND y = 10` | `CASE WHEN x_null_count = x_row_count THEN false ELSE x_min <= 5 AND 5 <= x_max END AND CASE WHEN y_null_count = y_row_count THEN false ELSE y_min <= 10 AND 10 <= y_max END`+/// `x IS NULL` | `CASE WHEN x_null_count = x_row_count THEN false ELSE x_null_count > 0 END`+/// `CAST(x as int) = 5` | `CASE WHEN x_null_count = x_row_count THEN false ELSE CAST(x_min as int) <= 5 AND 5 <= CAST(x_max as int) END`////// ## Predicate Evaluation/// The PruningPredicate works in two passes@@ -326,28 +341,47 @@ pub trait PruningStatistics {/// LiteralGuarantees are not satisfied////// **Second Pass**: Evaluates the rewritten expression using the-/// min/max/null_counts values for each column for each container. For any+/// min/max/null_counts/row_counts values for each column for each container. For any/// container that this expression evaluates to `false`, it rules out those/// containers.///-/// For example, given the predicate, `x = 5 AND y = 10`, if we know `x` is-/// between `1 and 100` and we know that `y` is between `4` and `7`, the input-/// statistics might look like+///+/// ### Example 1+///+/// Given the predicate, `x = 5 AND y = 10`, the rewritten predicate would look like:+///+/// ```sql+/// CASE+/// WHEN x_null_count = x_row_count THEN false+/// ELSE x_min <= 5 AND 5 <= x_max+/// END+/// AND+/// CASE+/// WHEN y_null_count = y_row_count THEN false+/// ELSE y_min <= 10 AND 10 <= y_max+/// END+/// ```+///+/// If we know that for a given container, `x` is between `1 and 100` and we know that+/// `y` is between `4` and `7`, we know nothing about the null count and row count of+/// `x` and `y`, the input statistics might look like:////// Column | Value/// -------- | -----/// `x_min` | `1`/// `x_max` | `100`+/// `x_null_count` | `null`+/// `x_row_count` | `null`/// `y_min` | `4`/// `y_max` | `7`+/// `y_null_count` | `null`+/// `y_row_count` | `null`///-/// The rewritten predicate would look like-///-/// `x_min <= 5 AND 5 <= x_max AND y_min <= 10 AND 10 <= y_max`-///-/// When these values are substituted in to the rewritten predicate and+/// When these statistics values are substituted in to the rewritten predicate and/// simplified, the result is `false`:///+/// * `CASE WHEN null = null THEN false ELSE 1 <= 5 AND 5 <= 100 END AND CASE WHEN null = null THEN false ELSE 4 <= 10 AND 10 <= 7 END`+/// * `null = null` is `null` which is not true, so the `CASE` expression will use the `ELSE` clause/// * `1 <= 5 AND 5 <= 100 AND 4 <= 10 AND 10 <= 7`/// * `true AND true AND true AND false`/// * `false`@@ -364,6 +398,52 @@ pub trait PruningStatistics {/// more analysis, for example by actually reading the data and evaluating the/// predicate row by row.///+/// ### Example 2+///+/// Given the same predicate, `x = 5 AND y = 10`, the rewritten predicate would+/// look like the same as example 1:+///+/// ```sql+/// CASE+/// WHEN x_null_count = x_row_count THEN false+/// ELSE x_min <= 5 AND 5 <= x_max+/// END+/// AND+/// CASE+/// WHEN y_null_count = y_row_count THEN false+/// ELSE y_min <= 10 AND 10 <= y_max+/// END+/// ```+///+/// If we know that for another given container, `x_min` is NULL and `x_max` is+/// NULL (the min/max values are unknown), `x_null_count` is `100` and `x_row_count`+/// is `100`; we know that `y` is between `4` and `7`, but we know nothing about+/// the null count and row count of `y`. The input statistics might look like:+///+/// Column | Value+/// -------- | -----+/// `x_min` | `null`+/// `x_max` | `null`+/// `x_null_count` | `100`+/// `x_row_count` | `100`+/// `y_min` | `4`+/// `y_max` | `7`+/// `y_null_count` | `null`+/// `y_row_count` | `null`+///+/// When these statistics values are substituted in to the rewritten predicate and+/// simplified, the result is `false`:+///+/// * `CASE WHEN 100 = 100 THEN false ELSE null <= 5 AND 5 <= null END AND CASE WHEN null = null THEN false ELSE 4 <= 10 AND 10 <= 7 END`+/// * Since `100 = 100` is `true`, the `CASE` expression will use the `THEN` clause, i.e. `false`+/// * The other `CASE` expression will use the `ELSE` clause, i.e. `4 <= 10 AND 10 <= 7`+/// * `false AND true`+/// * `false`+///+/// Returning `false` means the container can be pruned, which matches the+/// intuition that `x = 5 AND y = 10` can’t be true for all values in `x`+/// are known to be NULL.+////// # Related Work////// [`PruningPredicate`] implements the type of min/max pruning described in@@ -744,6 +824,22 @@ impl RequiredColumns {"null_count",)}++ /// rewrite col --> col_row_count+ fn row_count_column_expr(+ &mut self,+ column: &phys_expr::Column,+ column_expr: &Arc<dyn PhysicalExpr>,+ field: &Field,+ ) -> Result<Arc<dyn PhysicalExpr>> {+ self.stat_column_expr(+ column,+ column_expr,+ field,+ StatisticsType::RowCount,+ "row_count",+ )+ }}impl From<Vec<(phys_expr::Column, StatisticsType, Field)>> for RequiredColumns {@@ -794,6 +890,7 @@ fn build_statistics_record_batch<S: PruningStatistics>(StatisticsType::Min => statistics.min_values(&column),StatisticsType::Max => statistics.max_values(&column),StatisticsType::NullCount => statistics.null_counts(&column),+ StatisticsType::RowCount => statistics.row_counts(&column),};let array = array.unwrap_or_else(|| new_null_array(data_type, num_containers));@@ -903,6 +1000,46 @@ impl<'a> PruningExpressionBuilder<'a> {self.required_columns.max_column_expr(&self.column, &self.column_expr, self.field)}++ /// This function is to simply retune the `null_count` physical expression no matter what the+ /// predicate expression is+ ///+ /// i.e., x > 5 => x_null_count,+ /// cast(x as int) < 10 => x_null_count,+ /// try_cast(x as float) < 10.0 => x_null_count+ fn null_count_column_expr(&mut self) -> Result<Arc<dyn PhysicalExpr>> {+ // Retune to [`phys_expr::Column`]+ let column_expr = Arc::new(self.column.clone()) as _;++ // null_count is DataType::UInt64, which is different from the column's data type (i.e. self.field)+ let null_count_field = &Field::new(self.field.name(), DataType::UInt64, true);++ self.required_columns.null_count_column_expr(+ &self.column,+ &column_expr,+ null_count_field,+ )+ }++ /// This function is to simply retune the `row_count` physical expression no matter what the+ /// predicate expression is+ ///+ /// i.e., x > 5 => x_row_count,+ /// cast(x as int) < 10 => x_row_count,+ /// try_cast(x as float) < 10.0 => x_row_count+ fn row_count_column_expr(&mut self) -> Result<Arc<dyn PhysicalExpr>> {+ // Retune to [`phys_expr::Column`]+ let column_expr = Arc::new(self.column.clone()) as _;++ // row_count is DataType::UInt64, which is different from the column's data type (i.e. self.field)+ let row_count_field = &Field::new(self.field.name(), DataType::UInt64, true);++ self.required_columns.row_count_column_expr(+ &self.column,+ &column_expr,+ row_count_field,+ )+ }}/// This function is designed to rewrite the column_expr to@@ -1320,14 +1457,56 @@ fn build_statistics_expr();}};+ let statistics_expr = wrap_case_expr(statistics_expr, expr_builder)?;Ok(statistics_expr)}+/// Wrap the statistics expression in a case expression.+/// This is necessary to handle the case where the column is known+/// to be all nulls.+///+/// For example:+///+/// `x_min <= 10 AND 10 <= x_max`+///+/// will become+///+/// ```sql+/// CASE+/// WHEN x_null_count = x_row_count THEN false+/// ELSE x_min <= 10 AND 10 <= x_max+/// END+/// ````+///+/// If the column is known to be all nulls, then the expression+/// `x_null_count = x_row_count` will be true, which will cause the+/// case expression to return false. Therefore, prune out the container.+fn wrap_case_expr(+ statistics_expr: Arc<dyn PhysicalExpr>,+ expr_builder: &mut PruningExpressionBuilder,+) -> Result<Arc<dyn PhysicalExpr>> {+ // x_null_count = x_row_count+ let when_null_count_eq_row_count = Arc::new(phys_expr::BinaryExpr::new(+ expr_builder.null_count_column_expr()?,+ Operator::Eq,+ expr_builder.row_count_column_expr()?,+ ));+ let then = Arc::new(phys_expr::Literal::new(ScalarValue::Boolean(Some(false))));++ // CASE WHEN x_null_count = x_row_count THEN false ELSE <statistics_expr> END+ Ok(Arc::new(phys_expr::CaseExpr::try_new(+ None,+ vec![(when_null_count_eq_row_count, then)],+ Some(statistics_expr),+ )?))+}+#[derive(Debug, Copy, Clone, PartialEq, Eq)]pub(crate) enum StatisticsType {Min,Max,NullCount,+ RowCount,}#[cfg(test)]@@ -1361,6 +1540,7 @@ mod tests {max: Option<ArrayRef>,/// Optional valuesnull_counts: Option<ArrayRef>,+ row_counts: Option<ArrayRef>,/// Optional known values (e.g. mimic a bloom filter)/// (value, contained)/// If present, all BooleanArrays must be the same size as min/max@@ -1440,6 +1620,10 @@ mod tests {self.null_counts.clone()}+ fn row_counts(&self) -> Option<ArrayRef> {+ self.row_counts.clone()+ }+/// return an iterator over all arrays in this statisticsfn arrays(&self) -> Vec<ArrayRef> {let contained_arrays = self@@ -1451,6 +1635,7 @@ mod tests {self.min.as_ref().cloned(),self.max.as_ref().cloned(),self.null_counts.as_ref().cloned(),+ self.row_counts.as_ref().cloned(),].into_iter().flatten()@@ -1509,6 +1694,20 @@ mod tests {self}+ /// Add row counts. There must be the same number of row counts as+ /// there are containers+ fn with_row_counts(+ mut self,+ counts: impl IntoIterator<Item = Option<i64>>,+ ) -> Self {+ let row_counts: ArrayRef =+ Arc::new(counts.into_iter().collect::<Int64Array>());++ self.assert_invariants();+ self.row_counts = Some(row_counts);+ self+ }+/// Add contained information.pub fn with_contained(mut self,@@ -1576,6 +1775,28 @@ mod tests {self}+ /// Add row counts for the specified columm.+ /// There must be the same number of row counts as+ /// there are containers+ fn with_row_counts(+ mut self,+ name: impl Into<String>,+ counts: impl IntoIterator<Item = Option<i64>>,+ ) -> Self {+ let col = Column::from_name(name.into());++ // take stats out and update them+ let container_stats = self+ .stats+ .remove(&col)+ .unwrap_or_default()+ .with_row_counts(counts);++ // put stats back in+ self.stats.insert(col, container_stats);+ self+ }+/// Add contained information for the specified columm.fn with_contained(mut self,@@ -1628,6 +1849,13 @@ mod tests {.unwrap_or(None)}+ fn row_counts(&self, column: &Column) -> Option<ArrayRef> {+ self.stats+ .get(column)+ .map(|container_stats| container_stats.row_counts())+ .unwrap_or(None)+ }+fn contained(&self,column: &Column,@@ -1663,6 +1891,10 @@ mod tests {None}+ fn row_counts(&self, _column: &Column) -> Option<ArrayRef> {+ None+ }+fn contained(&self,_column: &Column,@@ -1853,7 +2085,7 @@ mod tests {#[test]fn row_group_predicate_eq() -> Result<()> {let schema = Schema::new(vec![Field::new("c1", DataType::Int32, false)]);- let expected_expr = "c1_min@0 <= 1 AND 1 <= c1_max@1";+ let expected_expr = "CASE WHEN c1_null_count@2 = c1_row_count@3 THEN false ELSE c1_min@0 <= 1 AND 1 <= c1_max@1 END";// test column on the leftlet expr = col("c1").eq(lit(1));@@ -1873,7 +2105,7 @@ mod tests {#[test]fn row_group_predicate_not_eq() -> Result<()> {let schema = Schema::new(vec![Field::new("c1", DataType::Int32, false)]);- let expected_expr = "c1_min@0 != 1 OR 1 != c1_max@1";+ let expected_expr = "CASE WHEN c1_null_count@2 = c1_row_count@3 THEN false ELSE c1_min@0 != 1 OR 1 != c1_max@1 END";// test column on the leftlet expr = col("c1").not_eq(lit(1));@@ -1893,7 +2125,8 @@ mod tests {#[test]fn row_group_predicate_gt() -> Result<()> {let schema = Schema::new(vec![Field::new("c1", DataType::Int32, false)]);- let expected_expr = "c1_max@0 > 1";+ let expected_expr =+ "CASE WHEN c1_null_count@1 = c1_row_count@2 THEN false ELSE c1_max@0 > 1 END";// test column on the leftlet expr = col("c1").gt(lit(1));@@ -1913,7 +2146,7 @@ mod tests {#[test]fn row_group_predicate_gt_eq() -> Result<()> {let schema = Schema::new(vec![Field::new("c1", DataType::Int32, false)]);- let expected_expr = "c1_max@0 >= 1";+ let expected_expr = "CASE WHEN c1_null_count@1 = c1_row_count@2 THEN false ELSE c1_max@0 >= 1 END";// test column on the leftlet expr = col("c1").gt_eq(lit(1));@@ -1932,7 +2165,8 @@ mod tests {#[test]fn row_group_predicate_lt() -> Result<()> {let schema = Schema::new(vec![Field::new("c1", DataType::Int32, false)]);- let expected_expr = "c1_min@0 < 1";+ let expected_expr =+ "CASE WHEN c1_null_count@1 = c1_row_count@2 THEN false ELSE c1_min@0 < 1 END";// test column on the leftlet expr = col("c1").lt(lit(1));@@ -1952,7 +2186,7 @@ mod tests {#[test]fn row_group_predicate_lt_eq() -> Result<()> {let schema = Schema::new(vec![Field::new("c1", DataType::Int32, false)]);- let expected_expr = "c1_min@0 <= 1";+ let expected_expr = "CASE WHEN c1_null_count@1 = c1_row_count@2 THEN false ELSE c1_min@0 <= 1 END";// test column on the leftlet expr = col("c1").lt_eq(lit(1));@@ -1977,7 +2211,8 @@ mod tests {]);// test AND operator joining supported c1 < 1 expression and unsupported c2 > c3 expressionlet expr = col("c1").lt(lit(1)).and(col("c2").lt(col("c3")));- let expected_expr = "c1_min@0 < 1";+ let expected_expr =+ "CASE WHEN c1_null_count@1 = c1_row_count@2 THEN false ELSE c1_min@0 < 1 END";let predicate_expr =test_build_predicate_expression(&expr, &schema, &mut RequiredColumns::new());assert_eq!(predicate_expr.to_string(), expected_expr);@@ -2043,7 +2278,7 @@ mod tests {#[test]fn row_group_predicate_lt_bool() -> Result<()> {let schema = Schema::new(vec![Field::new("c1", DataType::Boolean, false)]);- let expected_expr = "c1_min@0 < true";+ let expected_expr = "CASE WHEN c1_null_count@1 = c1_row_count@2 THEN false ELSE c1_min@0 < true END";// DF doesn't support arithmetic on boolean columns so// this predicate will error when evaluated@@ -2066,7 +2301,21 @@ mod tests {let expr = col("c1").lt(lit(1)).and(col("c2").eq(lit(2)).or(col("c2").eq(lit(3))));- let expected_expr = "c1_min@0 < 1 AND (c2_min@1 <= 2 AND 2 <= c2_max@2 OR c2_min@1 <= 3 AND 3 <= c2_max@2)";+ let expected_expr = "\+ CASE \+ WHEN c1_null_count@1 = c1_row_count@2 THEN false \+ ELSE c1_min@0 < 1 \+ END \+ AND (\+ CASE \+ WHEN c2_null_count@5 = c2_row_count@6 THEN false \+ ELSE c2_min@3 <= 2 AND 2 <= c2_max@4 \+ END \+ OR CASE \+ WHEN c2_null_count@5 = c2_row_count@6 THEN false \+ ELSE c2_min@3 <= 3 AND 3 <= c2_max@4 \+ END\+ )";let predicate_expr =test_build_predicate_expression(&expr, &schema, &mut required_columns);assert_eq!(predicate_expr.to_string(), expected_expr);@@ -2080,10 +2329,30 @@ mod tests {c1_min_field.with_nullable(true) // could be nullable if stats are not present));+ // c1 < 1 should add c1_null_count+ let c1_null_count_field = Field::new("c1_null_count", DataType::UInt64, false);+ assert_eq!(+ required_columns.columns[1],+ (+ phys_expr::Column::new("c1", 0),+ StatisticsType::NullCount,+ c1_null_count_field.with_nullable(true) // could be nullable if stats are not present+ )+ );+ // c1 < 1 should add c1_row_count+ let c1_row_count_field = Field::new("c1_row_count", DataType::UInt64, false);+ assert_eq!(+ required_columns.columns[2],+ (+ phys_expr::Column::new("c1", 0),+ StatisticsType::RowCount,+ c1_row_count_field.with_nullable(true) // could be nullable if stats are not present+ )+ );// c2 = 2 should add c2_min and c2_maxlet c2_min_field = Field::new("c2_min", DataType::Int32, false);assert_eq!(- required_columns.columns[1],+ required_columns.columns[3],(phys_expr::Column::new("c2", 1),StatisticsType::Min,@@ -2092,15 +2361,35 @@ mod tests {);let c2_max_field = Field::new("c2_max", DataType::Int32, false);assert_eq!(- required_columns.columns[2],+ required_columns.columns[4],(phys_expr::Column::new("c2", 1),StatisticsType::Max,c2_max_field.with_nullable(true) // could be nullable if stats are not present));+ // c2 = 2 should add c2_null_count+ let c2_null_count_field = Field::new("c2_null_count", DataType::UInt64, false);+ assert_eq!(+ required_columns.columns[5],+ (+ phys_expr::Column::new("c2", 1),+ StatisticsType::NullCount,+ c2_null_count_field.with_nullable(true) // could be nullable if stats are not present+ )+ );+ // c2 = 2 should add c2_row_count+ let c2_row_count_field = Field::new("c2_row_count", DataType::UInt64, false);+ assert_eq!(+ required_columns.columns[6],+ (+ phys_expr::Column::new("c2", 1),+ StatisticsType::RowCount,+ c2_row_count_field.with_nullable(true) // could be nullable if stats are not present+ )+ );// c2 = 3 shouldn't add any new statistics fields- assert_eq!(required_columns.columns.len(), 3);+ assert_eq!(required_columns.columns.len(), 7);Ok(())}@@ -2117,7 +2406,18 @@ mod tests {vec![lit(1), lit(2), lit(3)],false,));- let expected_expr = "c1_min@0 <= 1 AND 1 <= c1_max@1 OR c1_min@0 <= 2 AND 2 <= c1_max@1 OR c1_min@0 <= 3 AND 3 <= c1_max@1";+ let expected_expr = "CASE \+ WHEN c1_null_count@2 = c1_row_count@3 THEN false \+ ELSE c1_min@0 <= 1 AND 1 <= c1_max@1 \+ END \+ OR CASE \+ WHEN c1_null_count@2 = c1_row_count@3 THEN false \+ ELSE c1_min@0 <= 2 AND 2 <= c1_max@1 \+ END \+ OR CASE \+ WHEN c1_null_count@2 = c1_row_count@3 THEN false \+ ELSE c1_min@0 <= 3 AND 3 <= c1_max@1 \+ END";let predicate_expr =test_build_predicate_expression(&expr, &schema, &mut RequiredColumns::new());assert_eq!(predicate_expr.to_string(), expected_expr);@@ -2153,9 +2453,19 @@ mod tests {vec![lit(1), lit(2), lit(3)],true,));- let expected_expr = "(c1_min@0 != 1 OR 1 != c1_max@1) \- AND (c1_min@0 != 2 OR 2 != c1_max@1) \- AND (c1_min@0 != 3 OR 3 != c1_max@1)";+ let expected_expr = "\+ CASE \+ WHEN c1_null_count@2 = c1_row_count@3 THEN false \+ ELSE c1_min@0 != 1 OR 1 != c1_max@1 \+ END \+ AND CASE \+ WHEN c1_null_count@2 = c1_row_count@3 THEN false \+ ELSE c1_min@0 != 2 OR 2 != c1_max@1 \+ END \+ AND CASE \+ WHEN c1_null_count@2 = c1_row_count@3 THEN false \+ ELSE c1_min@0 != 3 OR 3 != c1_max@1 \+ END";let predicate_expr =test_build_predicate_expression(&expr, &schema, &mut RequiredColumns::new());assert_eq!(predicate_expr.to_string(), expected_expr);@@ -2201,7 +2511,24 @@ mod tests {// test c1 in(1, 2) and c2 BETWEEN 4 AND 5let expr3 = expr1.and(expr2);- let expected_expr = "(c1_min@0 <= 1 AND 1 <= c1_max@1 OR c1_min@0 <= 2 AND 2 <= c1_max@1) AND c2_max@2 >= 4 AND c2_min@3 <= 5";+ let expected_expr = "\+ (\+ CASE \+ WHEN c1_null_count@2 = c1_row_count@3 THEN false \+ ELSE c1_min@0 <= 1 AND 1 <= c1_max@1 \+ END \+ OR CASE \+ WHEN c1_null_count@2 = c1_row_count@3 THEN false \+ ELSE c1_min@0 <= 2 AND 2 <= c1_max@1 \+ END\+ ) AND CASE \+ WHEN c2_null_count@5 = c2_row_count@6 THEN false \+ ELSE c2_max@4 >= 4 \+ END \+ AND CASE \+ WHEN c2_null_count@5 = c2_row_count@6 THEN false \+ ELSE c2_min@7 <= 5 \+ END";let predicate_expr =test_build_predicate_expression(&expr3, &schema, &mut RequiredColumns::new());assert_eq!(predicate_expr.to_string(), expected_expr);@@ -2228,9 +2555,12 @@ mod tests {#[test]fn row_group_predicate_cast() -> Result<()> {let schema = Schema::new(vec![Field::new("c1", DataType::Int32, false)]);- let expected_expr =- "CAST(c1_min@0 AS Int64) <= 1 AND 1 <= CAST(c1_max@1 AS Int64)";+ let expected_expr = "CASE \+ WHEN c1_null_count@2 = c1_row_count@3 THEN false \+ ELSE CAST(c1_min@0 AS Int64) <= 1 AND 1 <= CAST(c1_max@1 AS Int64) \+ END";+ // test cast(c1 as int64) = 1// test column on the leftlet expr = cast(col("c1"), DataType::Int64).eq(lit(ScalarValue::Int64(Some(1))));let predicate_expr =@@ -2243,7 +2573,10 @@ mod tests {test_build_predicate_expression(&expr, &schema, &mut RequiredColumns::new());assert_eq!(predicate_expr.to_string(), expected_expr);- let expected_expr = "TRY_CAST(c1_max@0 AS Int64) > 1";+ let expected_expr = "CASE \+ WHEN c1_null_count@1 = c1_row_count@2 THEN false \+ ELSE TRY_CAST(c1_max@0 AS Int64) > 1 \+ END";// test column on the leftlet expr =@@ -2275,7 +2608,18 @@ mod tests {],false,));- let expected_expr = "CAST(c1_min@0 AS Int64) <= 1 AND 1 <= CAST(c1_max@1 AS Int64) OR CAST(c1_min@0 AS Int64) <= 2 AND 2 <= CAST(c1_max@1 AS Int64) OR CAST(c1_min@0 AS Int64) <= 3 AND 3 <= CAST(c1_max@1 AS Int64)";+ let expected_expr = "CASE \+ WHEN c1_null_count@2 = c1_row_count@3 THEN false \+ ELSE CAST(c1_min@0 AS Int64) <= 1 AND 1 <= CAST(c1_max@1 AS Int64) \+ END \+ OR CASE \+ WHEN c1_null_count@2 = c1_row_count@3 THEN false \+ ELSE CAST(c1_min@0 AS Int64) <= 2 AND 2 <= CAST(c1_max@1 AS Int64) \+ END \+ OR CASE \+ WHEN c1_null_count@2 = c1_row_count@3 THEN false \+ ELSE CAST(c1_min@0 AS Int64) <= 3 AND 3 <= CAST(c1_max@1 AS Int64) \+ END";let predicate_expr =test_build_predicate_expression(&expr, &schema, &mut RequiredColumns::new());assert_eq!(predicate_expr.to_string(), expected_expr);@@ -2289,10 +2633,18 @@ mod tests {],true,));- let expected_expr =- "(CAST(c1_min@0 AS Int64) != 1 OR 1 != CAST(c1_max@1 AS Int64)) \- AND (CAST(c1_min@0 AS Int64) != 2 OR 2 != CAST(c1_max@1 AS Int64)) \- AND (CAST(c1_min@0 AS Int64) != 3 OR 3 != CAST(c1_max@1 AS Int64))";+ let expected_expr = "CASE \+ WHEN c1_null_count@2 = c1_row_count@3 THEN false \+ ELSE CAST(c1_min@0 AS Int64) != 1 OR 1 != CAST(c1_max@1 AS Int64) \+ END \+ AND CASE \+ WHEN c1_null_count@2 = c1_row_count@3 THEN false \+ ELSE CAST(c1_min@0 AS Int64) != 2 OR 2 != CAST(c1_max@1 AS Int64) \+ END \+ AND CASE \+ WHEN c1_null_count@2 = c1_row_count@3 THEN false \+ ELSE CAST(c1_min@0 AS Int64) != 3 OR 3 != CAST(c1_max@1 AS Int64) \+ END";let predicate_expr =test_build_predicate_expression(&expr, &schema, &mut RequiredColumns::new());assert_eq!(predicate_expr.to_string(), expected_expr);@@ -2819,7 +3171,7 @@ mod tests {let expected_ret = &[false, true, true, true, false];prune_with_expr(- // i IS NULL, with actual null statistcs+ // i IS NULL, with actual null statisticscol("i").is_null(),&schema,&statistics,@@ -2827,6 +3179,78 @@ mod tests {);}+ #[test]+ fn prune_int32_column_is_known_all_null() {+ let (schema, statistics) = int32_setup();++ // Expression "i < 0"+ // i [-5, 5] ==> some rows could pass (must keep)+ // i [1, 11] ==> no rows can pass (not keep)+ // i [-11, -1] ==> all rows must pass (must keep)+ // i [NULL, NULL] ==> unknown (must keep)+ // i [1, NULL] ==> no rows can pass (not keep)+ let expected_ret = &[true, false, true, true, false];++ prune_with_expr(+ // i < 0+ col("i").lt(lit(0)),+ &schema,+ &statistics,+ expected_ret,+ );++ // provide row counts for each column+ let statistics = statistics.with_row_counts(+ "i",+ vec![+ Some(10), // 10 rows of data+ Some(9), // 9 rows of data+ None, // unknown row counts+ Some(4),+ Some(10),+ ],+ );++ // pruning result is still the same if we only know row counts+ prune_with_expr(+ // i < 0, with only row counts statistics+ col("i").lt(lit(0)),+ &schema,+ &statistics,+ expected_ret,+ );++ // provide null counts for each column+ let statistics = statistics.with_null_counts(+ "i",+ vec![+ Some(0), // no nulls+ Some(1), // 1 null+ None, // unknown nulls+ Some(4), // 4 nulls, which is the same as the row counts, i.e. this column is all null (don't keep)+ Some(0), // 0 nulls (max=null too which means no known max)+ ],+ );++ // Expression "i < 0" with actual null and row counts statistics+ // col | min, max | row counts | null counts |+ // ----+--------------+------------+-------------++ // i | [-5, 5] | 10 | 0 | ==> Some rows could pass (must keep)+ // i | [1, 11] | 9 | 1 | ==> No rows can pass (not keep)+ // i | [-11,-1] | Unknown | Unknown | ==> All rows must pass (must keep)+ // i | [NULL, NULL] | 4 | 4 | ==> The column is all null (not keep)+ // i | [1, NULL] | 10 | 0 | ==> No rows can pass (not keep)+ let expected_ret = &[true, false, true, false, false];++ prune_with_expr(+ // i < 0, with actual null and row counts statistics+ col("i").lt(lit(0)),+ &schema,+ &statistics,+ expected_ret,+ );+ }+#[test]fn prune_cast_column_scalar() {// The data type of column i is INT32diff --git a/datafusion/sqllogictest/test_files/repartition_scan.slt b/datafusion/sqllogictest/test_files/repartition_scan.sltindex fe0f6c1e81..f9699a5fda 100644--- a/datafusion/sqllogictest/test_files/repartition_scan.slt+++ b/datafusion/sqllogictest/test_files/repartition_scan.slt@@ -61,7 +61,7 @@ Filter: parquet_table.column1 != Int32(42)physical_planCoalesceBatchesExec: target_batch_size=8192--FilterExec: column1@0 != 42-----ParquetExec: file_groups={4 groups: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/repartition_scan/parquet_table/2.parquet:0..104], [WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/repartition_scan/parquet_table/2.parquet:104..208], [WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/repartition_scan/parquet_table/2.parquet:208..312], [WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/repartition_scan/parquet_table/2.parquet:312..414]]}, projection=[column1], predicate=column1@0 != 42, pruning_predicate=column1_min@0 != 42 OR 42 != column1_max@1, required_guarantees=[column1 not in (42)]+----ParquetExec: file_groups={4 groups: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/repartition_scan/parquet_table/2.parquet:0..104], [WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/repartition_scan/parquet_table/2.parquet:104..208], [WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/repartition_scan/parquet_table/2.parquet:208..312], [WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/repartition_scan/parquet_table/2.parquet:312..414]]}, projection=[column1], predicate=column1@0 != 42, pruning_predicate=CASE WHEN column1_null_count@2 = column1_row_count@3 THEN false ELSE column1_min@0 != 42 OR 42 != column1_max@1 END, required_guarantees=[column1 not in (42)]# disable round robin repartitioningstatement ok@@ -77,7 +77,7 @@ Filter: parquet_table.column1 != Int32(42)physical_planCoalesceBatchesExec: target_batch_size=8192--FilterExec: column1@0 != 42-----ParquetExec: file_groups={4 groups: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/repartition_scan/parquet_table/2.parquet:0..104], [WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/repartition_scan/parquet_table/2.parquet:104..208], [WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/repartition_scan/parquet_table/2.parquet:208..312], [WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/repartition_scan/parquet_table/2.parquet:312..414]]}, projection=[column1], predicate=column1@0 != 42, pruning_predicate=column1_min@0 != 42 OR 42 != column1_max@1, required_guarantees=[column1 not in (42)]+----ParquetExec: file_groups={4 groups: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/repartition_scan/parquet_table/2.parquet:0..104], [WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/repartition_scan/parquet_table/2.parquet:104..208], [WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/repartition_scan/parquet_table/2.parquet:208..312], [WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/repartition_scan/parquet_table/2.parquet:312..414]]}, projection=[column1], predicate=column1@0 != 42, pruning_predicate=CASE WHEN column1_null_count@2 = column1_row_count@3 THEN false ELSE column1_min@0 != 42 OR 42 != column1_max@1 END, required_guarantees=[column1 not in (42)]# enable round robin repartitioning againstatement ok@@ -102,7 +102,7 @@ SortPreservingMergeExec: [column1@0 ASC NULLS LAST]--SortExec: expr=[column1@0 ASC NULLS LAST]----CoalesceBatchesExec: target_batch_size=8192------FilterExec: column1@0 != 42---------ParquetExec: file_groups={4 groups: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/repartition_scan/parquet_table/1.parquet:0..205], [WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/repartition_scan/parquet_table/1.parquet:205..405, WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/repartition_scan/parquet_table/2.parquet:0..5], [WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/repartition_scan/parquet_table/2.parquet:5..210], [WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/repartition_scan/parquet_table/2.parquet:210..414]]}, projection=[column1], predicate=column1@0 != 42, pruning_predicate=column1_min@0 != 42 OR 42 != column1_max@1, required_guarantees=[column1 not in (42)]+--------ParquetExec: file_groups={4 groups: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/repartition_scan/parquet_table/1.parquet:0..205], [WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/repartition_scan/parquet_table/1.parquet:205..405, WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/repartition_scan/parquet_table/2.parquet:0..5], [WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/repartition_scan/parquet_table/2.parquet:5..210], [WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/repartition_scan/parquet_table/2.parquet:210..414]]}, projection=[column1], predicate=column1@0 != 42, pruning_predicate=CASE WHEN column1_null_count@2 = column1_row_count@3 THEN false ELSE column1_min@0 != 42 OR 42 != column1_max@1 END, required_guarantees=[column1 not in (42)]## Read the files as though they are ordered@@ -138,7 +138,7 @@ physical_planSortPreservingMergeExec: [column1@0 ASC NULLS LAST]--CoalesceBatchesExec: target_batch_size=8192----FilterExec: column1@0 != 42-------ParquetExec: file_groups={4 groups: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/repartition_scan/parquet_table/1.parquet:0..202], [WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/repartition_scan/parquet_table/2.parquet:0..207], [WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/repartition_scan/parquet_table/2.parquet:207..414], [WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/repartition_scan/parquet_table/1.parquet:202..405]]}, projection=[column1], output_ordering=[column1@0 ASC NULLS LAST], predicate=column1@0 != 42, pruning_predicate=column1_min@0 != 42 OR 42 != column1_max@1, required_guarantees=[column1 not in (42)]+------ParquetExec: file_groups={4 groups: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/repartition_scan/parquet_table/1.parquet:0..202], [WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/repartition_scan/parquet_table/2.parquet:0..207], [WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/repartition_scan/parquet_table/2.parquet:207..414], [WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/repartition_scan/parquet_table/1.parquet:202..405]]}, projection=[column1], output_ordering=[column1@0 ASC NULLS LAST], predicate=column1@0 != 42, pruning_predicate=CASE WHEN column1_null_count@2 = column1_row_count@3 THEN false ELSE column1_min@0 != 42 OR 42 != column1_max@1 END, required_guarantees=[column1 not in (42)]# Cleanupstatement ok