diff --git a/datafusion/expr/src/logical_plan/plan.rs b/datafusion/expr/src/logical_plan/plan.rs index d2467e2346c44..8bc9be1227b49 100644 --- a/datafusion/expr/src/logical_plan/plan.rs +++ b/datafusion/expr/src/logical_plan/plan.rs @@ -1702,8 +1702,9 @@ impl LogicalPlan { /// Returns the skip (offset) of this plan node, if it has one. /// - /// Only [`LogicalPlan::Limit`] carries a skip value; all other variants - /// return `Ok(None)`. Returns `Ok(None)` for a zero skip. + /// [`LogicalPlan::Limit`] and [`LogicalPlan::TableScan`] may carry a skip + /// value. All other variants return `Ok(None)`. Returns `Ok(None)` for a + /// zero skip. pub fn skip(&self) -> Result> { match self { LogicalPlan::Limit(limit) => match limit.get_skip_type()? { @@ -1712,7 +1713,7 @@ impl LogicalPlan { SkipType::UnsupportedExpr => Ok(None), }, LogicalPlan::Sort(_) => Ok(None), - LogicalPlan::TableScan(_) => Ok(None), + LogicalPlan::TableScan(TableScan { skip, .. }) => Ok(skip.filter(|&n| n > 0)), LogicalPlan::Projection(_) => Ok(None), LogicalPlan::Filter(_) => Ok(None), LogicalPlan::Window(_) => Ok(None), @@ -3264,6 +3265,31 @@ impl PartialOrd for Window { } /// Produces rows from a table provider by reference or from the context +/// +/// # Row order +/// +/// A `TableScan` combines several operators in one node. It produces rows in +/// this order: +/// +/// ```text +/// source rows -> filters -> skip -> fetch -> projection +/// ``` +/// +/// The filters step means the filters that the source applies exactly (see +/// [`TableProviderFilterPushDown::Exact`]). The skip and the fetch apply to +/// the rows that pass these filters. +/// +/// This order goes in one direction only: +/// +/// * `Limit(Filter(scan))` can fold into one scan with filters and a fetch. +/// * `Filter(scan)` cannot move into the scan when the scan has a skip or a +/// fetch. Inside the scan, the filter runs before the skip and the fetch, +/// so the scan keeps different rows. +/// +/// Use [`TableScan::try_with_filters`] to add filters to a scan. It refuses +/// a scan with a skip or a fetch. +/// +/// [`TableProviderFilterPushDown::Exact`]: crate::TableProviderFilterPushDown::Exact #[derive(Clone)] pub struct TableScan { /// The name of the table @@ -3276,9 +3302,11 @@ pub struct TableScan { pub projected_schema: DFSchemaRef, /// Optional expressions to be used as filters by the table provider pub filters: Vec, - /// Optional number of rows to read + /// Optional number of rows to read. The fetch applies after the filters + /// and the skip. See [Row order](TableScan#row-order). pub fetch: Option, - /// Optional number of rows to skip + /// Optional number of rows to skip. The skip applies after the filters + /// and before the fetch. See [Row order](TableScan#row-order). pub skip: Option, /// Statistics the planner would like the provider to answer for this /// scan, typically attached by a custom optimizer rule from the @@ -3313,6 +3341,7 @@ impl PartialEq for TableScan { && self.projected_schema == other.projected_schema && self.filters == other.filters && self.fetch == other.fetch + && self.skip == other.skip } } @@ -3332,18 +3361,22 @@ impl PartialOrd for TableScan { pub filters: &'a Vec, /// Optional number of rows to read pub fetch: &'a Option, + /// Optional number of rows to skip + pub skip: &'a Option, } let comparable_self = ComparableTableScan { table_name: &self.table_name, projection: &self.projection, filters: &self.filters, fetch: &self.fetch, + skip: &self.skip, }; let comparable_other = ComparableTableScan { table_name: &other.table_name, projection: &other.projection, filters: &other.filters, fetch: &other.fetch, + skip: &other.skip, }; comparable_self .partial_cmp(&comparable_other) @@ -3359,6 +3392,7 @@ impl Hash for TableScan { self.projected_schema.hash(state); self.filters.hash(state); self.fetch.hash(state); + self.skip.hash(state); } } @@ -3379,6 +3413,23 @@ impl TableScan { .with_fetch(fetch) .build() } + + /// Returns this scan with its filters replaced by `filters`. + /// + /// Returns `Err(self)` unchanged when the scan has a nonzero skip or any + /// fetch, because the filters apply before both. See + /// [Row order](TableScan#row-order). + #[expect(clippy::result_large_err)] + pub fn try_with_filters( + mut self, + filters: Vec, + ) -> std::result::Result { + if self.fetch.is_some() || self.skip.is_some_and(|n| n > 0) { + return Err(self); + } + self.filters = filters; + Ok(self) + } } /// Builder for [`TableScan`]. @@ -7803,4 +7854,74 @@ mod tests { } Ok(()) } + + fn employee_scan() -> Result { + let LogicalPlan::TableScan(scan) = + table_scan(Some("employee_csv"), &employee_schema(), None)?.build()? + else { + unreachable!() + }; + Ok(scan) + } + + #[test] + fn table_scan_skip() -> Result<()> { + for (skip, expected) in [(None, None), (Some(0), None), (Some(3), Some(3))] { + let scan = TableScan { + skip, + ..employee_scan()? + }; + assert_eq!(LogicalPlan::TableScan(scan).skip()?, expected); + } + Ok(()) + } + + #[test] + fn table_scan_skip_in_eq_ord_and_hash() -> Result<()> { + fn hash_of(scan: &TableScan) -> u64 { + let mut hasher = DefaultHasher::new(); + scan.hash(&mut hasher); + hasher.finish() + } + let no_skip = employee_scan()?; + let skip = TableScan { + skip: Some(3), + ..employee_scan()? + }; + + assert_ne!(no_skip, skip); + assert_eq!(no_skip.partial_cmp(&skip), Some(Ordering::Less)); + assert_ne!(hash_of(&no_skip), hash_of(&skip)); + assert_eq!(skip, skip.clone()); + assert_eq!(hash_of(&skip), hash_of(&skip.clone())); + Ok(()) + } + + #[test] + fn table_scan_try_with_filters() -> Result<()> { + let filters = vec![col("id").gt(lit(1))]; + + let scan = employee_scan()?.try_with_filters(filters.clone()).unwrap(); + assert_eq!(scan.filters, filters); + + // A zero skip removes no rows, so the filters can move in. + let scan = TableScan { + skip: Some(0), + ..employee_scan()? + }; + let scan = scan.try_with_filters(filters.clone()).unwrap(); + assert_eq!(scan.filters, filters); + + for (skip, fetch) in [(Some(3), None), (None, Some(5)), (None, Some(0))] { + let scan = TableScan { + fetch, + skip, + ..employee_scan()? + }; + let scan = scan.try_with_filters(filters.clone()).unwrap_err(); + assert!(scan.filters.is_empty()); + assert_eq!((scan.skip, scan.fetch), (skip, fetch)); + } + Ok(()) + } } diff --git a/datafusion/optimizer/src/push_down_filter.rs b/datafusion/optimizer/src/push_down_filter.rs index efaea281a14e2..892941d66d6b8 100644 --- a/datafusion/optimizer/src/push_down_filter.rs +++ b/datafusion/optimizer/src/push_down_filter.rs @@ -1313,7 +1313,7 @@ impl OptimizerRule for PushDownFilter { result.map_data(|plan| Ok(with_filters(keep_predicates, plan))) } - LogicalPlan::TableScan(mut scan) => { + LogicalPlan::TableScan(scan) => { let filter_predicates = split_conjunction(&filter.predicate); // Filters containing scalar subqueries cannot be pushed to // providers because the subquery result is not available @@ -1380,9 +1380,20 @@ impl OptimizerRule for PushDownFilter { predicates_changed || reorder_changed, TreeNodeRecursion::Continue, )); - } else { - scan.filters = new_scan_filters; } + let scan = match scan.try_with_filters(new_scan_filters) { + Ok(scan) => scan, + // The fetch and skip guard above returns before this point + // today. This arm keeps the plan correct if that guard moves. + Err(scan) => { + filter.input = Arc::new(LogicalPlan::TableScan(scan)); + return Ok(Transformed::new( + LogicalPlan::Filter(filter), + predicates_changed || reorder_changed, + TreeNodeRecursion::Continue, + )); + } + }; // Compose predicates to be of `Unsupported` or `Inexact` pushdown type, // and also include volatile and subquery-containing filters @@ -4985,6 +4996,27 @@ mod tests { ) } + #[test] + fn filter_not_pushed_down_through_table_scan_with_skip() -> Result<()> { + let LogicalPlan::TableScan(scan) = test_table_scan()? else { + unreachable!() + }; + let scan_with_skip = LogicalPlan::TableScan(TableScan { + skip: Some(3), + ..scan + }); + let plan = LogicalPlanBuilder::from(scan_with_skip) + .filter(col("a").gt(lit(10i64)))? + .build()?; + assert_optimized_plan_equal!( + plan, + @r" + Filter: test.a > Int64(10) + TableScan: test, skip=3 + " + ) + } + #[test] fn filter_push_down_through_sort_without_fetch() -> Result<()> { let table_scan = test_table_scan()?;