adriangb commented on code in PR #21621:
URL: https://github.com/apache/datafusion/pull/21621#discussion_r3969160443
##########
datafusion/optimizer/src/push_down_limit.rs:
##########
@@ -47,146 +50,159 @@ impl OptimizerRule for PushDownLimit {
true
}
- #[expect(clippy::only_used_in_recursion)]
fn rewrite(
&self,
plan: LogicalPlan,
config: &dyn OptimizerConfig,
) -> Result<Transformed<LogicalPlan>> {
- let LogicalPlan::Limit(mut limit) = plan else {
- return Ok(Transformed::no(plan));
- };
+ match plan {
+ LogicalPlan::Limit(limit) => rewrite_limit(limit, config),
+ LogicalPlan::Sort(s) if s.fetch.is_some() => {
+ push_topk_through_join(LogicalPlan::Sort(s))
+ }
+ other => Ok(Transformed::no(other)),
+ }
+ }
- // Currently only rewrite if skip and fetch are both literals
- let SkipType::Literal(skip) = limit.get_skip_type()? else {
+ fn name(&self) -> &str {
+ "push_down_limit"
+ }
+
+ fn apply_order(&self) -> Option<ApplyOrder> {
+ Some(ApplyOrder::TopDown)
+ }
+}
+
+/// Limit-side dispatch (split out from `rewrite` so that the top-level
+/// match in `OptimizerRule::rewrite` reads as a parallel branch alongside
+/// the Sort-with-fetch handler).
+#[expect(clippy::only_used_in_recursion)]
Review Comment:
`rewrite_limit` is a free function now. It only passes `config` to itself.
Please remove the parameter and this `expect`.
##########
datafusion/optimizer/src/push_down_limit.rs:
##########
@@ -47,146 +50,159 @@ impl OptimizerRule for PushDownLimit {
true
}
- #[expect(clippy::only_used_in_recursion)]
fn rewrite(
&self,
plan: LogicalPlan,
config: &dyn OptimizerConfig,
) -> Result<Transformed<LogicalPlan>> {
- let LogicalPlan::Limit(mut limit) = plan else {
- return Ok(Transformed::no(plan));
- };
+ match plan {
+ LogicalPlan::Limit(limit) => rewrite_limit(limit, config),
+ LogicalPlan::Sort(s) if s.fetch.is_some() => {
Review Comment:
**Two optimizer passes are necessary.** This is a risk, not a bug. For
`ORDER BY x LIMIT n`, the planner makes `Limit` above `Sort`. The `Limit` arm
below merges them into `Sort(fetch=n)` and returns `Transformed::yes`. The
top-down walk in `optimizer.rs` (`rewrite_plan_in_place`) does not visit the
new node again. Thus the push happens in pass 2. The default `max_passes` is 3,
so it works. But the rule does nothing when `max_passes = 1`. And each `LIMIT`
query pays for one more full pass.
Please add a note in the code. Or call `push_topk_through_join` directly on
the `Sort` that the `Limit` arm produces.
##########
datafusion/optimizer/src/push_down_limit.rs:
##########
@@ -29,6 +29,9 @@ use datafusion_common::utils::combine_limit;
use datafusion_expr::logical_plan::{Join, JoinType, Limit, LogicalPlan};
use datafusion_expr::{FetchType, SkipType, lit};
+mod topk_through_join;
+use topk_through_join::push_topk_through_join;
+
/// Optimization rule that tries to push down `LIMIT`.
Review Comment:
This doc comment still says the rule pushes only `LIMIT`. The rule now
rewrites `Sort` nodes too. Please update it.
##########
datafusion/optimizer/src/push_down_limit/topk_through_join.rs:
##########
@@ -0,0 +1,1185 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Sort(fetch) → Join pushdown — a sub-module of `push_down_limit`.
+//!
+//! When a `Sort` with a fetch limit (TopK) sits above a join whose
+//! preserved side is known (LEFT / RIGHT / LeftMark / RightMark / CROSS)
+//! and all sort expressions come from the preserved side, we insert a
+//! copy of the `Sort(fetch)` onto that input to reduce rows entering
+//! the join. The outer `Sort` is kept because a 1-to-many join can
+//! produce more than N output rows from N preserved-side rows.
Review Comment:
`eliminate_outer_join` can turn a LEFT join into an INNER join. It needs a
`Filter` directly above the `Join`. After this rule runs, a `Filter` cannot
sink below the outer `Sort`, because `push_down_filter` does not move a filter
below a node with a fetch (`push_down_filter.rs`, the `fetch()?.is_some()`
guard). That guard keeps the pushed `Sort` correct. The dependency is implicit.
Please add a comment here that names it.
##########
datafusion/optimizer/src/push_down_limit/topk_through_join.rs:
##########
@@ -0,0 +1,1185 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Sort(fetch) → Join pushdown — a sub-module of `push_down_limit`.
+//!
+//! When a `Sort` with a fetch limit (TopK) sits above a join whose
+//! preserved side is known (LEFT / RIGHT / LeftMark / RightMark / CROSS)
+//! and all sort expressions come from the preserved side, we insert a
+//! copy of the `Sort(fetch)` onto that input to reduce rows entering
+//! the join. The outer `Sort` is kept because a 1-to-many join can
+//! produce more than N output rows from N preserved-side rows.
+//!
+//! Dispatched from `PushDownLimit::rewrite` when the plan node is
+//! `LogicalPlan::Sort` with `fetch.is_some()`.
+
+use std::collections::HashMap;
+use std::sync::Arc;
+
+use crate::utils::{has_all_column_refs, schema_columns};
+
+use datafusion_common::tree_node::{Transformed, TreeNode};
+use datafusion_common::{Column, Result, internal_err};
+use datafusion_expr::logical_plan::{
+ JoinType, LogicalPlan, Projection, Sort as SortPlan, SubqueryAlias,
+};
+use datafusion_expr::{Expr, SortExpr};
+
+/// Which child of a join is being treated as the preserved side.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Side {
+ Left,
+ Right,
+}
+
+/// Top-level pushdown for `Sort(fetch) → ... → Join` patterns. The plan
+/// passed in is guaranteed by the caller to be `LogicalPlan::Sort` with
+/// `fetch.is_some()`; we re-bind to a borrow inside.
+pub(super) fn push_topk_through_join(
+ plan: LogicalPlan,
+) -> Result<Transformed<LogicalPlan>> {
+ let LogicalPlan::Sort(sort) = &plan else {
+ return Ok(Transformed::no(plan));
+ };
+ let Some(fetch) = sort.fetch else {
+ return Ok(Transformed::no(plan));
+ };
+
+ // Don't push if any sort expression is non-deterministic (e.g.
+ // `random()`). Duplicating such expressions would produce different
+ // values at each evaluation point, potentially changing results.
+ if sort.expr.iter().any(|se| se.expr.is_volatile()) {
+ return Ok(Transformed::no(plan));
+ }
+
+ // Peel through transparent nodes (SubqueryAlias, Projection) to
+ // find the Join. Track intermediates so we can reconstruct the tree
+ // and resolve sort expressions through them.
+ let mut current = sort.input.as_ref();
+ let mut intermediates: Vec<&LogicalPlan> = Vec::new();
+ let join = loop {
+ match current {
+ LogicalPlan::Join(join) => break join,
+ LogicalPlan::Projection(proj) => {
+ intermediates.push(current);
+ current = proj.input.as_ref();
+ }
+ LogicalPlan::SubqueryAlias(sq) => {
+ intermediates.push(current);
+ current = sq.input.as_ref();
+ }
+ _ => return Ok(Transformed::no(plan)),
+ }
+ };
+
+ // Determine which side(s) of the join are preserved.
+ //
+ // - LEFT / LeftMark: only left preserved.
+ // - RIGHT / RightMark: symmetric.
+ // - CROSS JOIN (Inner with no `on` keys and no filter):
+ // every row from both sides appears in the output (Cartesian
+ // product), so we can push to whichever side has all the sort
+ // columns.
+ //
+ // For LEFT/RIGHT, non-equijoin filters in the ON clause are safe:
+ // outer joins guarantee all preserved-side rows appear in the
+ // output regardless of the filter. For Inner joins (cross-join
+ // detection), the filter check is strict (`filter.is_none()`) —
+ // any filter on Inner can drop rows from either side.
+ let preserved_candidates: &[Side] = match join.join_type {
+ JoinType::Left | JoinType::LeftMark => &[Side::Left],
+ JoinType::Right | JoinType::RightMark => &[Side::Right],
+ JoinType::Inner if join.on.is_empty() && join.filter.is_none() => {
+ &[Side::Left, Side::Right]
+ }
+ _ => return Ok(Transformed::no(plan)),
+ };
+
+ // Resolve sort expressions through all intermediate nodes
+ // (Projection, SubqueryAlias) so column references match the
+ // join's schema.
+ let mut resolved_sort_exprs = sort.expr.clone();
+ for node in &intermediates {
+ match node {
+ LogicalPlan::Projection(proj) => {
+ resolved_sort_exprs =
+
resolve_sort_exprs_through_projection(&resolved_sort_exprs, proj)?;
+ }
+ LogicalPlan::SubqueryAlias(sq) => {
+ resolved_sort_exprs =
+
resolve_sort_exprs_through_subquery_alias(&resolved_sort_exprs, sq)?;
+ }
+ _ => {
+ return internal_err!(
+ "push_topk_through_join: unexpected intermediate node: {}",
+ node.display()
+ );
+ }
+ }
+ }
+
+ // After resolving through projections, sort expressions may now
+ // contain volatile functions (e.g. `random() AS col`). Duplicating
+ // them would change results.
+ if resolved_sort_exprs.iter().any(|se| se.expr.is_volatile()) {
+ return Ok(Transformed::no(plan));
+ }
+
+ // Pick the first preserved-side candidate whose schema contains all
+ // referenced sort columns. For LEFT/RIGHT this is the fixed side;
+ // for CROSS we try both.
+ let Some(preserved_side) =
preserved_candidates.iter().copied().find(|&side| {
+ let schema = match side {
+ Side::Left => join.left.schema(),
+ Side::Right => join.right.schema(),
+ };
+ let cols = schema_columns(schema);
+ resolved_sort_exprs
+ .iter()
+ .all(|se| has_all_column_refs(&se.expr, &cols))
Review Comment:
`has_all_column_refs` returns true for an expression with zero column
references. Thus `ORDER BY 'x' LIMIT 3` pushes a `Sort` onto the preserved
child. The result is legal, but the work is wasted. Please skip the push when a
sort key has no column references.
##########
datafusion/optimizer/src/push_down_limit/topk_through_join.rs:
##########
@@ -0,0 +1,1185 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Sort(fetch) → Join pushdown — a sub-module of `push_down_limit`.
+//!
+//! When a `Sort` with a fetch limit (TopK) sits above a join whose
+//! preserved side is known (LEFT / RIGHT / LeftMark / RightMark / CROSS)
+//! and all sort expressions come from the preserved side, we insert a
+//! copy of the `Sort(fetch)` onto that input to reduce rows entering
+//! the join. The outer `Sort` is kept because a 1-to-many join can
+//! produce more than N output rows from N preserved-side rows.
+//!
+//! Dispatched from `PushDownLimit::rewrite` when the plan node is
+//! `LogicalPlan::Sort` with `fetch.is_some()`.
+
+use std::collections::HashMap;
+use std::sync::Arc;
+
+use crate::utils::{has_all_column_refs, schema_columns};
+
+use datafusion_common::tree_node::{Transformed, TreeNode};
+use datafusion_common::{Column, Result, internal_err};
+use datafusion_expr::logical_plan::{
+ JoinType, LogicalPlan, Projection, Sort as SortPlan, SubqueryAlias,
+};
+use datafusion_expr::{Expr, SortExpr};
+
+/// Which child of a join is being treated as the preserved side.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Side {
+ Left,
+ Right,
+}
+
+/// Top-level pushdown for `Sort(fetch) → ... → Join` patterns. The plan
+/// passed in is guaranteed by the caller to be `LogicalPlan::Sort` with
+/// `fetch.is_some()`; we re-bind to a borrow inside.
+pub(super) fn push_topk_through_join(
+ plan: LogicalPlan,
+) -> Result<Transformed<LogicalPlan>> {
+ let LogicalPlan::Sort(sort) = &plan else {
+ return Ok(Transformed::no(plan));
+ };
+ let Some(fetch) = sort.fetch else {
+ return Ok(Transformed::no(plan));
+ };
+
+ // Don't push if any sort expression is non-deterministic (e.g.
+ // `random()`). Duplicating such expressions would produce different
+ // values at each evaluation point, potentially changing results.
+ if sort.expr.iter().any(|se| se.expr.is_volatile()) {
+ return Ok(Transformed::no(plan));
+ }
+
+ // Peel through transparent nodes (SubqueryAlias, Projection) to
+ // find the Join. Track intermediates so we can reconstruct the tree
+ // and resolve sort expressions through them.
+ let mut current = sort.input.as_ref();
+ let mut intermediates: Vec<&LogicalPlan> = Vec::new();
+ let join = loop {
+ match current {
+ LogicalPlan::Join(join) => break join,
+ LogicalPlan::Projection(proj) => {
+ intermediates.push(current);
+ current = proj.input.as_ref();
+ }
+ LogicalPlan::SubqueryAlias(sq) => {
+ intermediates.push(current);
+ current = sq.input.as_ref();
+ }
+ _ => return Ok(Transformed::no(plan)),
+ }
+ };
+
+ // Determine which side(s) of the join are preserved.
+ //
+ // - LEFT / LeftMark: only left preserved.
+ // - RIGHT / RightMark: symmetric.
+ // - CROSS JOIN (Inner with no `on` keys and no filter):
+ // every row from both sides appears in the output (Cartesian
+ // product), so we can push to whichever side has all the sort
+ // columns.
+ //
+ // For LEFT/RIGHT, non-equijoin filters in the ON clause are safe:
+ // outer joins guarantee all preserved-side rows appear in the
+ // output regardless of the filter. For Inner joins (cross-join
+ // detection), the filter check is strict (`filter.is_none()`) —
+ // any filter on Inner can drop rows from either side.
+ let preserved_candidates: &[Side] = match join.join_type {
+ JoinType::Left | JoinType::LeftMark => &[Side::Left],
+ JoinType::Right | JoinType::RightMark => &[Side::Right],
+ JoinType::Inner if join.on.is_empty() && join.filter.is_none() => {
+ &[Side::Left, Side::Right]
+ }
+ _ => return Ok(Transformed::no(plan)),
+ };
+
+ // Resolve sort expressions through all intermediate nodes
+ // (Projection, SubqueryAlias) so column references match the
+ // join's schema.
+ let mut resolved_sort_exprs = sort.expr.clone();
+ for node in &intermediates {
+ match node {
+ LogicalPlan::Projection(proj) => {
+ resolved_sort_exprs =
+
resolve_sort_exprs_through_projection(&resolved_sort_exprs, proj)?;
+ }
+ LogicalPlan::SubqueryAlias(sq) => {
+ resolved_sort_exprs =
+
resolve_sort_exprs_through_subquery_alias(&resolved_sort_exprs, sq)?;
+ }
+ _ => {
+ return internal_err!(
+ "push_topk_through_join: unexpected intermediate node: {}",
+ node.display()
+ );
+ }
+ }
+ }
+
+ // After resolving through projections, sort expressions may now
+ // contain volatile functions (e.g. `random() AS col`). Duplicating
+ // them would change results.
+ if resolved_sort_exprs.iter().any(|se| se.expr.is_volatile()) {
+ return Ok(Transformed::no(plan));
+ }
+
+ // Pick the first preserved-side candidate whose schema contains all
+ // referenced sort columns. For LEFT/RIGHT this is the fixed side;
+ // for CROSS we try both.
+ let Some(preserved_side) =
preserved_candidates.iter().copied().find(|&side| {
+ let schema = match side {
+ Side::Left => join.left.schema(),
+ Side::Right => join.right.schema(),
+ };
+ let cols = schema_columns(schema);
Review Comment:
`schema_columns` adds an unqualified name for each field. An unqualified
sort column with the same name on both sides matches the preserved side. SQL
cannot make this plan, because the planner qualifies the columns. A hand-built
plan can. `push_down_filter` has the same caveat. Please add a comment.
##########
datafusion/optimizer/src/push_down_limit/topk_through_join.rs:
##########
@@ -0,0 +1,1185 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Sort(fetch) → Join pushdown — a sub-module of `push_down_limit`.
+//!
+//! When a `Sort` with a fetch limit (TopK) sits above a join whose
+//! preserved side is known (LEFT / RIGHT / LeftMark / RightMark / CROSS)
+//! and all sort expressions come from the preserved side, we insert a
+//! copy of the `Sort(fetch)` onto that input to reduce rows entering
+//! the join. The outer `Sort` is kept because a 1-to-many join can
+//! produce more than N output rows from N preserved-side rows.
+//!
+//! Dispatched from `PushDownLimit::rewrite` when the plan node is
+//! `LogicalPlan::Sort` with `fetch.is_some()`.
+
+use std::collections::HashMap;
+use std::sync::Arc;
+
+use crate::utils::{has_all_column_refs, schema_columns};
+
+use datafusion_common::tree_node::{Transformed, TreeNode};
+use datafusion_common::{Column, Result, internal_err};
+use datafusion_expr::logical_plan::{
+ JoinType, LogicalPlan, Projection, Sort as SortPlan, SubqueryAlias,
+};
+use datafusion_expr::{Expr, SortExpr};
+
+/// Which child of a join is being treated as the preserved side.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Side {
+ Left,
+ Right,
+}
+
+/// Top-level pushdown for `Sort(fetch) → ... → Join` patterns. The plan
+/// passed in is guaranteed by the caller to be `LogicalPlan::Sort` with
+/// `fetch.is_some()`; we re-bind to a borrow inside.
+pub(super) fn push_topk_through_join(
+ plan: LogicalPlan,
+) -> Result<Transformed<LogicalPlan>> {
+ let LogicalPlan::Sort(sort) = &plan else {
+ return Ok(Transformed::no(plan));
+ };
+ let Some(fetch) = sort.fetch else {
+ return Ok(Transformed::no(plan));
+ };
+
+ // Don't push if any sort expression is non-deterministic (e.g.
+ // `random()`). Duplicating such expressions would produce different
+ // values at each evaluation point, potentially changing results.
+ if sort.expr.iter().any(|se| se.expr.is_volatile()) {
+ return Ok(Transformed::no(plan));
+ }
+
+ // Peel through transparent nodes (SubqueryAlias, Projection) to
+ // find the Join. Track intermediates so we can reconstruct the tree
+ // and resolve sort expressions through them.
+ let mut current = sort.input.as_ref();
+ let mut intermediates: Vec<&LogicalPlan> = Vec::new();
+ let join = loop {
+ match current {
+ LogicalPlan::Join(join) => break join,
+ LogicalPlan::Projection(proj) => {
+ intermediates.push(current);
+ current = proj.input.as_ref();
+ }
+ LogicalPlan::SubqueryAlias(sq) => {
+ intermediates.push(current);
+ current = sq.input.as_ref();
+ }
+ _ => return Ok(Transformed::no(plan)),
+ }
+ };
+
+ // Determine which side(s) of the join are preserved.
+ //
+ // - LEFT / LeftMark: only left preserved.
+ // - RIGHT / RightMark: symmetric.
+ // - CROSS JOIN (Inner with no `on` keys and no filter):
+ // every row from both sides appears in the output (Cartesian
+ // product), so we can push to whichever side has all the sort
+ // columns.
+ //
+ // For LEFT/RIGHT, non-equijoin filters in the ON clause are safe:
+ // outer joins guarantee all preserved-side rows appear in the
+ // output regardless of the filter. For Inner joins (cross-join
+ // detection), the filter check is strict (`filter.is_none()`) —
+ // any filter on Inner can drop rows from either side.
+ let preserved_candidates: &[Side] = match join.join_type {
+ JoinType::Left | JoinType::LeftMark => &[Side::Left],
+ JoinType::Right | JoinType::RightMark => &[Side::Right],
+ JoinType::Inner if join.on.is_empty() && join.filter.is_none() => {
+ &[Side::Left, Side::Right]
+ }
+ _ => return Ok(Transformed::no(plan)),
+ };
+
+ // Resolve sort expressions through all intermediate nodes
+ // (Projection, SubqueryAlias) so column references match the
+ // join's schema.
+ let mut resolved_sort_exprs = sort.expr.clone();
+ for node in &intermediates {
+ match node {
+ LogicalPlan::Projection(proj) => {
+ resolved_sort_exprs =
+
resolve_sort_exprs_through_projection(&resolved_sort_exprs, proj)?;
+ }
+ LogicalPlan::SubqueryAlias(sq) => {
+ resolved_sort_exprs =
+
resolve_sort_exprs_through_subquery_alias(&resolved_sort_exprs, sq)?;
+ }
+ _ => {
+ return internal_err!(
+ "push_topk_through_join: unexpected intermediate node: {}",
+ node.display()
+ );
+ }
+ }
+ }
+
+ // After resolving through projections, sort expressions may now
+ // contain volatile functions (e.g. `random() AS col`). Duplicating
+ // them would change results.
+ if resolved_sort_exprs.iter().any(|se| se.expr.is_volatile()) {
+ return Ok(Transformed::no(plan));
+ }
+
+ // Pick the first preserved-side candidate whose schema contains all
+ // referenced sort columns. For LEFT/RIGHT this is the fixed side;
+ // for CROSS we try both.
+ let Some(preserved_side) =
preserved_candidates.iter().copied().find(|&side| {
+ let schema = match side {
+ Side::Left => join.left.schema(),
+ Side::Right => join.right.schema(),
+ };
+ let cols = schema_columns(schema);
+ resolved_sort_exprs
+ .iter()
+ .all(|se| has_all_column_refs(&se.expr, &cols))
+ }) else {
+ return Ok(Transformed::no(plan));
+ };
+
+ let preserved_child = match preserved_side {
+ Side::Left => &join.left,
+ Side::Right => &join.right,
+ };
+
+ // Scan deep inside the preserved child (through SubqueryAlias and
+ // Projection layers) to find an existing Sort. If found with same
+ // exprs, tighten its fetch in-place. Otherwise, insert a new Sort
+ // directly below the join as the preserved child's wrapper.
+ let mut inner_child = preserved_child.as_ref();
+ let mut deep_resolved_exprs = resolved_sort_exprs.clone();
+ loop {
+ match inner_child {
+ LogicalPlan::SubqueryAlias(sq) => {
+ deep_resolved_exprs =
+
resolve_sort_exprs_through_subquery_alias(&deep_resolved_exprs, sq)?;
+ inner_child = sq.input.as_ref();
+ }
+ LogicalPlan::Projection(proj) => {
+ deep_resolved_exprs =
+
resolve_sort_exprs_through_projection(&deep_resolved_exprs, proj)?;
+ inner_child = proj.input.as_ref();
+ }
+ _ => break,
+ }
+ }
+
+ // If the inner child is a Limit (PushDownLimit's own Limit handling
+ // hasn't merged it with the Sort yet), skip this iteration.
+ if matches!(inner_child, LogicalPlan::Limit(_)) {
Review Comment:
The comment says the `Limit` will merge with a `Sort` later. A `Limit` with
no `Sort` below it never merges. Thus `LEFT JOIN (SELECT * FROM t LIMIT 100)`
never gets the push. A `Sort(fetch=N)` above a `Limit` is sound. This is only a
missed optimization. Not blocking.
##########
datafusion/sqllogictest/test_files/push_down_topk_through_join.slt:
##########
@@ -1124,4 +1149,4 @@ statement ok
DROP TABLE t1;
Review Comment:
The slt coverage is good. Almost each `EXPLAIN` has a result check. These
cases are missing:
- `JoinConstraint::Using`, for example `LEFT JOIN t2 USING (a) ORDER BY t1.b
LIMIT 3`.
- A mark join from SQL, for example `WHERE EXISTS (...) OR ...` with `ORDER
BY ... LIMIT`. Only unit tests cover mark joins now.
- A sort key with no columns, for example `ORDER BY 'x' LIMIT 3` over a
1-to-many LEFT JOIN.
- `LIMIT 0`.
##########
datafusion/optimizer/src/push_down_limit/topk_through_join.rs:
##########
@@ -0,0 +1,1185 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Sort(fetch) → Join pushdown — a sub-module of `push_down_limit`.
+//!
+//! When a `Sort` with a fetch limit (TopK) sits above a join whose
+//! preserved side is known (LEFT / RIGHT / LeftMark / RightMark / CROSS)
+//! and all sort expressions come from the preserved side, we insert a
+//! copy of the `Sort(fetch)` onto that input to reduce rows entering
+//! the join. The outer `Sort` is kept because a 1-to-many join can
+//! produce more than N output rows from N preserved-side rows.
+//!
+//! Dispatched from `PushDownLimit::rewrite` when the plan node is
+//! `LogicalPlan::Sort` with `fetch.is_some()`.
+
+use std::collections::HashMap;
+use std::sync::Arc;
+
+use crate::utils::{has_all_column_refs, schema_columns};
+
+use datafusion_common::tree_node::{Transformed, TreeNode};
+use datafusion_common::{Column, Result, internal_err};
+use datafusion_expr::logical_plan::{
+ JoinType, LogicalPlan, Projection, Sort as SortPlan, SubqueryAlias,
+};
+use datafusion_expr::{Expr, SortExpr};
+
+/// Which child of a join is being treated as the preserved side.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Side {
+ Left,
+ Right,
+}
+
+/// Top-level pushdown for `Sort(fetch) → ... → Join` patterns. The plan
+/// passed in is guaranteed by the caller to be `LogicalPlan::Sort` with
+/// `fetch.is_some()`; we re-bind to a borrow inside.
+pub(super) fn push_topk_through_join(
+ plan: LogicalPlan,
+) -> Result<Transformed<LogicalPlan>> {
+ let LogicalPlan::Sort(sort) = &plan else {
+ return Ok(Transformed::no(plan));
+ };
+ let Some(fetch) = sort.fetch else {
+ return Ok(Transformed::no(plan));
+ };
+
+ // Don't push if any sort expression is non-deterministic (e.g.
+ // `random()`). Duplicating such expressions would produce different
+ // values at each evaluation point, potentially changing results.
+ if sort.expr.iter().any(|se| se.expr.is_volatile()) {
+ return Ok(Transformed::no(plan));
+ }
+
+ // Peel through transparent nodes (SubqueryAlias, Projection) to
+ // find the Join. Track intermediates so we can reconstruct the tree
+ // and resolve sort expressions through them.
+ let mut current = sort.input.as_ref();
+ let mut intermediates: Vec<&LogicalPlan> = Vec::new();
+ let join = loop {
+ match current {
+ LogicalPlan::Join(join) => break join,
+ LogicalPlan::Projection(proj) => {
+ intermediates.push(current);
+ current = proj.input.as_ref();
+ }
+ LogicalPlan::SubqueryAlias(sq) => {
+ intermediates.push(current);
+ current = sq.input.as_ref();
+ }
+ _ => return Ok(Transformed::no(plan)),
+ }
+ };
+
+ // Determine which side(s) of the join are preserved.
+ //
+ // - LEFT / LeftMark: only left preserved.
+ // - RIGHT / RightMark: symmetric.
+ // - CROSS JOIN (Inner with no `on` keys and no filter):
+ // every row from both sides appears in the output (Cartesian
+ // product), so we can push to whichever side has all the sort
+ // columns.
+ //
+ // For LEFT/RIGHT, non-equijoin filters in the ON clause are safe:
+ // outer joins guarantee all preserved-side rows appear in the
+ // output regardless of the filter. For Inner joins (cross-join
+ // detection), the filter check is strict (`filter.is_none()`) —
+ // any filter on Inner can drop rows from either side.
+ let preserved_candidates: &[Side] = match join.join_type {
+ JoinType::Left | JoinType::LeftMark => &[Side::Left],
+ JoinType::Right | JoinType::RightMark => &[Side::Right],
+ JoinType::Inner if join.on.is_empty() && join.filter.is_none() => {
+ &[Side::Left, Side::Right]
+ }
+ _ => return Ok(Transformed::no(plan)),
+ };
+
+ // Resolve sort expressions through all intermediate nodes
+ // (Projection, SubqueryAlias) so column references match the
+ // join's schema.
+ let mut resolved_sort_exprs = sort.expr.clone();
+ for node in &intermediates {
+ match node {
+ LogicalPlan::Projection(proj) => {
+ resolved_sort_exprs =
+
resolve_sort_exprs_through_projection(&resolved_sort_exprs, proj)?;
+ }
+ LogicalPlan::SubqueryAlias(sq) => {
+ resolved_sort_exprs =
+
resolve_sort_exprs_through_subquery_alias(&resolved_sort_exprs, sq)?;
+ }
+ _ => {
+ return internal_err!(
+ "push_topk_through_join: unexpected intermediate node: {}",
+ node.display()
+ );
+ }
+ }
+ }
+
+ // After resolving through projections, sort expressions may now
+ // contain volatile functions (e.g. `random() AS col`). Duplicating
+ // them would change results.
+ if resolved_sort_exprs.iter().any(|se| se.expr.is_volatile()) {
+ return Ok(Transformed::no(plan));
+ }
+
+ // Pick the first preserved-side candidate whose schema contains all
+ // referenced sort columns. For LEFT/RIGHT this is the fixed side;
+ // for CROSS we try both.
+ let Some(preserved_side) =
preserved_candidates.iter().copied().find(|&side| {
+ let schema = match side {
+ Side::Left => join.left.schema(),
+ Side::Right => join.right.schema(),
+ };
+ let cols = schema_columns(schema);
+ resolved_sort_exprs
+ .iter()
+ .all(|se| has_all_column_refs(&se.expr, &cols))
+ }) else {
+ return Ok(Transformed::no(plan));
+ };
+
+ let preserved_child = match preserved_side {
+ Side::Left => &join.left,
+ Side::Right => &join.right,
+ };
+
+ // Scan deep inside the preserved child (through SubqueryAlias and
+ // Projection layers) to find an existing Sort. If found with same
+ // exprs, tighten its fetch in-place. Otherwise, insert a new Sort
+ // directly below the join as the preserved child's wrapper.
+ let mut inner_child = preserved_child.as_ref();
+ let mut deep_resolved_exprs = resolved_sort_exprs.clone();
+ loop {
+ match inner_child {
+ LogicalPlan::SubqueryAlias(sq) => {
+ deep_resolved_exprs =
+
resolve_sort_exprs_through_subquery_alias(&deep_resolved_exprs, sq)?;
+ inner_child = sq.input.as_ref();
+ }
+ LogicalPlan::Projection(proj) => {
+ deep_resolved_exprs =
+
resolve_sort_exprs_through_projection(&deep_resolved_exprs, proj)?;
+ inner_child = proj.input.as_ref();
+ }
+ _ => break,
+ }
+ }
Review Comment:
This loop and the peel loop at lines 72-88 do the same walk. One helper can
replace both. That also removes the two unreachable `internal_err!` arms.
##########
datafusion/optimizer/src/push_down_limit/topk_through_join.rs:
##########
@@ -0,0 +1,1185 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Sort(fetch) → Join pushdown — a sub-module of `push_down_limit`.
+//!
+//! When a `Sort` with a fetch limit (TopK) sits above a join whose
+//! preserved side is known (LEFT / RIGHT / LeftMark / RightMark / CROSS)
+//! and all sort expressions come from the preserved side, we insert a
+//! copy of the `Sort(fetch)` onto that input to reduce rows entering
+//! the join. The outer `Sort` is kept because a 1-to-many join can
+//! produce more than N output rows from N preserved-side rows.
+//!
+//! Dispatched from `PushDownLimit::rewrite` when the plan node is
+//! `LogicalPlan::Sort` with `fetch.is_some()`.
+
+use std::collections::HashMap;
+use std::sync::Arc;
+
+use crate::utils::{has_all_column_refs, schema_columns};
+
+use datafusion_common::tree_node::{Transformed, TreeNode};
+use datafusion_common::{Column, Result, internal_err};
+use datafusion_expr::logical_plan::{
+ JoinType, LogicalPlan, Projection, Sort as SortPlan, SubqueryAlias,
+};
+use datafusion_expr::{Expr, SortExpr};
+
+/// Which child of a join is being treated as the preserved side.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Side {
+ Left,
+ Right,
+}
+
+/// Top-level pushdown for `Sort(fetch) → ... → Join` patterns. The plan
+/// passed in is guaranteed by the caller to be `LogicalPlan::Sort` with
+/// `fetch.is_some()`; we re-bind to a borrow inside.
+pub(super) fn push_topk_through_join(
+ plan: LogicalPlan,
+) -> Result<Transformed<LogicalPlan>> {
+ let LogicalPlan::Sort(sort) = &plan else {
+ return Ok(Transformed::no(plan));
+ };
+ let Some(fetch) = sort.fetch else {
+ return Ok(Transformed::no(plan));
+ };
+
+ // Don't push if any sort expression is non-deterministic (e.g.
+ // `random()`). Duplicating such expressions would produce different
+ // values at each evaluation point, potentially changing results.
+ if sort.expr.iter().any(|se| se.expr.is_volatile()) {
+ return Ok(Transformed::no(plan));
+ }
+
+ // Peel through transparent nodes (SubqueryAlias, Projection) to
+ // find the Join. Track intermediates so we can reconstruct the tree
+ // and resolve sort expressions through them.
+ let mut current = sort.input.as_ref();
+ let mut intermediates: Vec<&LogicalPlan> = Vec::new();
+ let join = loop {
+ match current {
+ LogicalPlan::Join(join) => break join,
+ LogicalPlan::Projection(proj) => {
+ intermediates.push(current);
+ current = proj.input.as_ref();
+ }
Review Comment:
Are projections always transparent? I see you do handle unwrapping
projections, could we add a test for that? Here's a proposal for
`datafusion/sqllogictest/test_files/push_down_topk_through_join.slt`:
```sql
###
### Sort key is a projected expression, not a plain column
###
# The outer ORDER BY references a projected expression built only from
# preserved-side columns. The rule resolves neg_b through the Projection to
# (- t1.b) and pushes a Sort on that expression below the join.
query TT
EXPLAIN SELECT * FROM (
SELECT t1.a, -t1.b AS neg_b, t2.y
FROM t1 LEFT JOIN t2 ON t1.a = t2.x
) sub
ORDER BY neg_b ASC LIMIT 3;
----
logical_plan
01)Sort: sub.neg_b ASC NULLS LAST, fetch=3
02)--SubqueryAlias: sub
03)----Projection: t1.a, (- t1.b) AS neg_b, t2.y
04)------Left Join: t1.a = t2.x
05)--------Sort: (- t1.b) ASC NULLS LAST, fetch=3
06)----------TableScan: t1 projection=[a, b]
07)--------TableScan: t2 projection=[x, y]
query III
SELECT * FROM (
SELECT t1.a, -t1.b AS neg_b, t2.y
FROM t1 LEFT JOIN t2 ON t1.a = t2.x
) sub
ORDER BY neg_b ASC LIMIT 3;
----
5 -50 NULL
4 -40 NULL
3 -30 300
# Negative case: the projected expression mixes both sides. After resolving
# through the Projection the key references t2.y, so nothing is pushed.
query TT
EXPLAIN SELECT * FROM (
SELECT t1.a, t1.b + coalesce(t2.y, 0) AS mixed
FROM t1 LEFT JOIN t2 ON t1.a = t2.x
) sub
ORDER BY mixed DESC LIMIT 3;
----
logical_plan
01)Sort: sub.mixed DESC NULLS FIRST, fetch=3
02)--SubqueryAlias: sub
03)----Projection: t1.a, CAST(t1.b AS Int64) + CASE WHEN __common_expr_1 IS
NOT NULL THEN __common_expr_1 ELSE Int64(0) END AS mixed
04)------Projection: CAST(t2.y AS Int64) AS __common_expr_1, t1.a, t1.b
05)--------Left Join: t1.a = t2.x
06)----------TableScan: t1 projection=[a, b]
07)----------TableScan: t2 projection=[x, y]
query II
SELECT * FROM (
SELECT t1.a, t1.b + coalesce(t2.y, 0) AS mixed
FROM t1 LEFT JOIN t2 ON t1.a = t2.x
) sub
ORDER BY mixed DESC LIMIT 3;
----
3 330
2 220
1 110
# Two stacked Projections: the key is computed in the inner one and
re-aliased
# in the outer one. Resolution must substitute through both layers.
query TT
EXPLAIN SELECT a, k2 FROM (
SELECT a, k1 AS k2 FROM (
SELECT t1.a, t1.b * 2 AS k1, t2.y
FROM t1 LEFT JOIN t2 ON t1.a = t2.x
) s1
) s2
ORDER BY k2 DESC LIMIT 2;
----
logical_plan
01)Sort: s2.k2 DESC NULLS FIRST, fetch=2
02)--SubqueryAlias: s2
03)----Projection: s1.a, s1.k1 AS k2
04)------SubqueryAlias: s1
05)--------Projection: t1.a, CAST(t1.b AS Int64) * Int64(2) AS k1
06)----------Left Join: t1.a = t2.x
07)------------Sort: CAST(t1.b AS Int64) * Int64(2) DESC NULLS FIRST, fetch=2
08)--------------TableScan: t1 projection=[a, b]
09)------------TableScan: t2 projection=[x]
query II
SELECT a, k2 FROM (
SELECT a, k1 AS k2 FROM (
SELECT t1.a, t1.b * 2 AS k1, t2.y
FROM t1 LEFT JOIN t2 ON t1.a = t2.x
) s1
) s2
ORDER BY k2 DESC LIMIT 2;
----
5 100
4 80
```
##########
datafusion/optimizer/src/push_down_limit/topk_through_join.rs:
##########
@@ -0,0 +1,1185 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Sort(fetch) → Join pushdown — a sub-module of `push_down_limit`.
+//!
+//! When a `Sort` with a fetch limit (TopK) sits above a join whose
+//! preserved side is known (LEFT / RIGHT / LeftMark / RightMark / CROSS)
+//! and all sort expressions come from the preserved side, we insert a
+//! copy of the `Sort(fetch)` onto that input to reduce rows entering
+//! the join. The outer `Sort` is kept because a 1-to-many join can
+//! produce more than N output rows from N preserved-side rows.
+//!
+//! Dispatched from `PushDownLimit::rewrite` when the plan node is
+//! `LogicalPlan::Sort` with `fetch.is_some()`.
+
+use std::collections::HashMap;
+use std::sync::Arc;
+
+use crate::utils::{has_all_column_refs, schema_columns};
+
+use datafusion_common::tree_node::{Transformed, TreeNode};
+use datafusion_common::{Column, Result, internal_err};
+use datafusion_expr::logical_plan::{
+ JoinType, LogicalPlan, Projection, Sort as SortPlan, SubqueryAlias,
+};
+use datafusion_expr::{Expr, SortExpr};
+
+/// Which child of a join is being treated as the preserved side.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Side {
+ Left,
+ Right,
+}
+
+/// Top-level pushdown for `Sort(fetch) → ... → Join` patterns. The plan
+/// passed in is guaranteed by the caller to be `LogicalPlan::Sort` with
+/// `fetch.is_some()`; we re-bind to a borrow inside.
+pub(super) fn push_topk_through_join(
+ plan: LogicalPlan,
+) -> Result<Transformed<LogicalPlan>> {
+ let LogicalPlan::Sort(sort) = &plan else {
+ return Ok(Transformed::no(plan));
+ };
+ let Some(fetch) = sort.fetch else {
+ return Ok(Transformed::no(plan));
+ };
+
+ // Don't push if any sort expression is non-deterministic (e.g.
+ // `random()`). Duplicating such expressions would produce different
+ // values at each evaluation point, potentially changing results.
+ if sort.expr.iter().any(|se| se.expr.is_volatile()) {
+ return Ok(Transformed::no(plan));
+ }
+
+ // Peel through transparent nodes (SubqueryAlias, Projection) to
+ // find the Join. Track intermediates so we can reconstruct the tree
+ // and resolve sort expressions through them.
+ let mut current = sort.input.as_ref();
+ let mut intermediates: Vec<&LogicalPlan> = Vec::new();
+ let join = loop {
+ match current {
+ LogicalPlan::Join(join) => break join,
+ LogicalPlan::Projection(proj) => {
+ intermediates.push(current);
+ current = proj.input.as_ref();
+ }
+ LogicalPlan::SubqueryAlias(sq) => {
+ intermediates.push(current);
+ current = sq.input.as_ref();
+ }
+ _ => return Ok(Transformed::no(plan)),
+ }
+ };
+
+ // Determine which side(s) of the join are preserved.
+ //
+ // - LEFT / LeftMark: only left preserved.
+ // - RIGHT / RightMark: symmetric.
+ // - CROSS JOIN (Inner with no `on` keys and no filter):
+ // every row from both sides appears in the output (Cartesian
+ // product), so we can push to whichever side has all the sort
+ // columns.
+ //
+ // For LEFT/RIGHT, non-equijoin filters in the ON clause are safe:
+ // outer joins guarantee all preserved-side rows appear in the
+ // output regardless of the filter. For Inner joins (cross-join
+ // detection), the filter check is strict (`filter.is_none()`) —
+ // any filter on Inner can drop rows from either side.
+ let preserved_candidates: &[Side] = match join.join_type {
+ JoinType::Left | JoinType::LeftMark => &[Side::Left],
+ JoinType::Right | JoinType::RightMark => &[Side::Right],
+ JoinType::Inner if join.on.is_empty() && join.filter.is_none() => {
+ &[Side::Left, Side::Right]
+ }
+ _ => return Ok(Transformed::no(plan)),
+ };
+
+ // Resolve sort expressions through all intermediate nodes
+ // (Projection, SubqueryAlias) so column references match the
+ // join's schema.
+ let mut resolved_sort_exprs = sort.expr.clone();
+ for node in &intermediates {
+ match node {
+ LogicalPlan::Projection(proj) => {
+ resolved_sort_exprs =
+
resolve_sort_exprs_through_projection(&resolved_sort_exprs, proj)?;
+ }
+ LogicalPlan::SubqueryAlias(sq) => {
+ resolved_sort_exprs =
+
resolve_sort_exprs_through_subquery_alias(&resolved_sort_exprs, sq)?;
+ }
+ _ => {
+ return internal_err!(
+ "push_topk_through_join: unexpected intermediate node: {}",
+ node.display()
+ );
+ }
+ }
+ }
+
+ // After resolving through projections, sort expressions may now
+ // contain volatile functions (e.g. `random() AS col`). Duplicating
+ // them would change results.
+ if resolved_sort_exprs.iter().any(|se| se.expr.is_volatile()) {
+ return Ok(Transformed::no(plan));
+ }
+
+ // Pick the first preserved-side candidate whose schema contains all
+ // referenced sort columns. For LEFT/RIGHT this is the fixed side;
+ // for CROSS we try both.
+ let Some(preserved_side) =
preserved_candidates.iter().copied().find(|&side| {
+ let schema = match side {
+ Side::Left => join.left.schema(),
+ Side::Right => join.right.schema(),
+ };
+ let cols = schema_columns(schema);
+ resolved_sort_exprs
+ .iter()
+ .all(|se| has_all_column_refs(&se.expr, &cols))
+ }) else {
+ return Ok(Transformed::no(plan));
+ };
+
+ let preserved_child = match preserved_side {
+ Side::Left => &join.left,
+ Side::Right => &join.right,
+ };
+
+ // Scan deep inside the preserved child (through SubqueryAlias and
+ // Projection layers) to find an existing Sort. If found with same
+ // exprs, tighten its fetch in-place. Otherwise, insert a new Sort
+ // directly below the join as the preserved child's wrapper.
+ let mut inner_child = preserved_child.as_ref();
+ let mut deep_resolved_exprs = resolved_sort_exprs.clone();
+ loop {
+ match inner_child {
+ LogicalPlan::SubqueryAlias(sq) => {
+ deep_resolved_exprs =
+
resolve_sort_exprs_through_subquery_alias(&deep_resolved_exprs, sq)?;
+ inner_child = sq.input.as_ref();
+ }
+ LogicalPlan::Projection(proj) => {
+ deep_resolved_exprs =
+
resolve_sort_exprs_through_projection(&deep_resolved_exprs, proj)?;
+ inner_child = proj.input.as_ref();
+ }
+ _ => break,
+ }
+ }
+
+ // If the inner child is a Limit (PushDownLimit's own Limit handling
+ // hasn't merged it with the Sort yet), skip this iteration.
+ if matches!(inner_child, LogicalPlan::Limit(_)) {
+ return Ok(Transformed::no(plan));
+ }
+
+ // Determine action based on existing inner Sort:
+ // - Same exprs, tighter fetch → skip (already optimal)
+ // - Same exprs, larger/no fetch → tighten in-place
+ // - Different exprs or no Sort → insert new Sort below the join
+ //
+ // If `deep_resolved_exprs` became volatile while resolving through
+ // projections inside the preserved child (e.g. `random() AS col`),
+ // structural equality with an existing inner Sort is unsound: two
+ // identical `random()` exprs evaluate to different values. Fall
+ // back to inserting a new Sort with `resolved_sort_exprs`.
+ let deep_exprs_volatile = deep_resolved_exprs.iter().any(|se|
se.expr.is_volatile());
+ let inner_sort = match inner_child {
+ LogicalPlan::Sort(s) if !deep_exprs_volatile => Some(s),
+ _ => None,
+ };
+ let new_preserved_child = if let Some(child_sort) = inner_sort {
+ let same_exprs = sort_exprs_equal(&child_sort.expr,
&deep_resolved_exprs);
+ let child_fetch_tighter = match child_sort.fetch {
+ Some(child_fetch) => child_fetch <= fetch,
+ None => false,
+ };
+ if same_exprs && child_fetch_tighter {
+ return Ok(Transformed::no(plan));
+ }
+ if same_exprs {
+ rebuild_with_tightened_sort(
+ preserved_child.as_ref(),
+ &deep_resolved_exprs,
+ fetch,
+ )?
+ } else {
+ // Different exprs — insert new Sort above the preserved
+ // child. If the inner Sort has no fetch, our pushed Sort
+ // is the only row reduction. If it has a fetch, re-sorting
+ // a small set is cheap and still reduces join input.
+ Arc::new(LogicalPlan::Sort(SortPlan {
+ expr: resolved_sort_exprs,
+ input: Arc::clone(preserved_child),
+ fetch: Some(fetch),
+ }))
+ }
+ } else {
+ Arc::new(LogicalPlan::Sort(SortPlan {
+ expr: resolved_sort_exprs,
+ input: Arc::clone(preserved_child),
+ fetch: Some(fetch),
+ }))
+ };
+
+ let mut new_join = join.clone();
+ match preserved_side {
+ Side::Left => new_join.left = new_preserved_child,
+ Side::Right => new_join.right = new_preserved_child,
+ }
+
+ // Rebuild the tree: join → intermediate nodes → top-level sort.
+ let mut new_sort_input = Arc::new(LogicalPlan::Join(new_join));
+ for node in intermediates.into_iter().rev() {
+ new_sort_input = Arc::new(match node {
+ LogicalPlan::Projection(proj) => {
+ let mut new_proj = proj.clone();
+ new_proj.input = new_sort_input;
+ LogicalPlan::Projection(new_proj)
+ }
+ LogicalPlan::SubqueryAlias(sq) => LogicalPlan::SubqueryAlias(
+ SubqueryAlias::try_new(new_sort_input, sq.alias.clone())?,
+ ),
+ _ => {
+ return internal_err!(
+ "push_topk_through_join: unexpected intermediate node: {}",
+ node.display()
+ );
+ }
+ });
+ }
+
+ Ok(Transformed::yes(LogicalPlan::Sort(SortPlan {
+ expr: sort.expr.clone(),
+ input: new_sort_input,
+ fetch: sort.fetch,
+ })))
+}
+
+/// Replace column references in sort expressions using a name→expr map.
+fn replace_columns_in_sort_exprs(
+ sort_exprs: &[SortExpr],
+ replace_map: &HashMap<String, Expr>,
+) -> Result<Vec<SortExpr>> {
+ sort_exprs
+ .iter()
+ .map(|sort_expr| {
+ let new_expr = sort_expr.expr.clone().transform(|expr| {
+ let replacement = match &expr {
+ Expr::Column(col) =>
replace_map.get(&col.flat_name()).cloned(),
+ _ => None,
+ };
+ Ok(replacement.map_or_else(|| Transformed::no(expr),
Transformed::yes))
+ })?;
+ Ok(SortExpr {
+ expr: new_expr.data,
+ ..*sort_expr
+ })
+ })
+ .collect()
+}
+
+/// Resolve sort expressions through a projection by replacing column
+/// references with the underlying projection expressions.
+fn resolve_sort_exprs_through_projection(
+ sort_exprs: &[SortExpr],
+ projection: &Projection,
+) -> Result<Vec<SortExpr>> {
+ let replace_map: HashMap<String, Expr> = projection
+ .schema
+ .iter()
+ .zip(projection.expr.iter())
+ .map(|((qualifier, field), expr)| {
+ let key = Column::from((qualifier, field)).flat_name();
+ (key, expr.clone().unalias())
+ })
+ .collect();
+
+ replace_columns_in_sort_exprs(sort_exprs, &replace_map)
+}
+
+/// Compare two slices of `SortExpr` for structural equality.
+fn sort_exprs_equal(a: &[SortExpr], b: &[SortExpr]) -> bool {
+ a.len() == b.len()
+ && a.iter().zip(b.iter()).all(|(left, right)| {
+ left.asc == right.asc
+ && left.nulls_first == right.nulls_first
+ && left.expr == right.expr
+ })
+}
+
+/// Resolve sort expressions through a `SubqueryAlias` by replacing the
+/// alias qualifier with the input schema's qualifier.
+fn resolve_sort_exprs_through_subquery_alias(
+ sort_exprs: &[SortExpr],
+ subquery_alias: &SubqueryAlias,
+) -> Result<Vec<SortExpr>> {
+ let replace_map: HashMap<String, Expr> = subquery_alias
+ .schema
+ .iter()
+ .zip(subquery_alias.input.schema().iter())
+ .map(|((alias_qual, alias_field), (input_qual, input_field))| {
+ let alias_col = Column::from((alias_qual, alias_field));
+ let input_col = Column::from((input_qual, input_field));
+ (alias_col.flat_name(), Expr::Column(input_col))
+ })
+ .collect();
+
+ replace_columns_in_sort_exprs(sort_exprs, &replace_map)
+}
+
+/// Rebuild the tree from `root` down to an existing Sort whose expressions
+/// match `target_exprs`, tightening its fetch to `new_fetch`.
+fn rebuild_with_tightened_sort(
+ root: &LogicalPlan,
+ target_exprs: &[SortExpr],
+ new_fetch: usize,
+) -> Result<Arc<LogicalPlan>> {
+ match root {
+ LogicalPlan::Sort(s) if sort_exprs_equal(&s.expr, target_exprs) => {
+ Ok(Arc::new(LogicalPlan::Sort(SortPlan {
+ expr: s.expr.clone(),
+ input: Arc::clone(&s.input),
+ fetch: Some(new_fetch),
+ })))
+ }
+ LogicalPlan::Projection(proj) => {
+ let new_input = rebuild_with_tightened_sort(
+ proj.input.as_ref(),
+ target_exprs,
+ new_fetch,
+ )?;
+ let mut new_proj = proj.clone();
+ new_proj.input = new_input;
+ Ok(Arc::new(LogicalPlan::Projection(new_proj)))
+ }
+ LogicalPlan::SubqueryAlias(sq) => {
+ let new_input =
+ rebuild_with_tightened_sort(sq.input.as_ref(), target_exprs,
new_fetch)?;
+ Ok(Arc::new(LogicalPlan::SubqueryAlias(
+ SubqueryAlias::try_new(new_input, sq.alias.clone())?,
+ )))
+ }
+ _ => internal_err!(
+ "rebuild_with_tightened_sort: unexpected node: {}",
+ root.display()
+ ),
+ }
+}
+
+#[cfg(test)]
+mod test {
+ use super::*;
+ use crate::OptimizerContext;
+ use crate::assert_optimized_plan_eq_snapshot;
+ use crate::push_down_limit::PushDownLimit;
+ use crate::test::*;
+
+ use datafusion_expr::col;
+ use datafusion_expr::logical_plan::builder::LogicalPlanBuilder;
+
+ macro_rules! assert_optimized_plan_equal {
+ (
+ $plan:expr,
+ @ $expected:literal $(,)?
+ ) => {{
+ let optimizer_ctx = OptimizerContext::new().with_max_passes(1);
Review Comment:
All unit tests use `with_max_passes(1)` and build `Sort(fetch)` directly. No
unit test runs the `Limit -> Sort -> Join` path that real SQL makes. See my
note on `push_down_limit.rs` about the second pass. Please add:
- One test with `.limit()` above `.sort()` and `max_passes(2)`.
- One test that runs the optimizer two times and asserts a stable plan.
- One test with `fetch = 0`.
- One test where the preserved child is a `Limit` with no `Sort`.
##########
datafusion/optimizer/src/push_down_limit/topk_through_join.rs:
##########
@@ -0,0 +1,1185 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Sort(fetch) → Join pushdown — a sub-module of `push_down_limit`.
+//!
+//! When a `Sort` with a fetch limit (TopK) sits above a join whose
+//! preserved side is known (LEFT / RIGHT / LeftMark / RightMark / CROSS)
+//! and all sort expressions come from the preserved side, we insert a
+//! copy of the `Sort(fetch)` onto that input to reduce rows entering
+//! the join. The outer `Sort` is kept because a 1-to-many join can
+//! produce more than N output rows from N preserved-side rows.
+//!
+//! Dispatched from `PushDownLimit::rewrite` when the plan node is
+//! `LogicalPlan::Sort` with `fetch.is_some()`.
+
+use std::collections::HashMap;
+use std::sync::Arc;
+
+use crate::utils::{has_all_column_refs, schema_columns};
+
+use datafusion_common::tree_node::{Transformed, TreeNode};
+use datafusion_common::{Column, Result, internal_err};
+use datafusion_expr::logical_plan::{
+ JoinType, LogicalPlan, Projection, Sort as SortPlan, SubqueryAlias,
+};
+use datafusion_expr::{Expr, SortExpr};
+
+/// Which child of a join is being treated as the preserved side.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Side {
+ Left,
+ Right,
+}
+
+/// Top-level pushdown for `Sort(fetch) → ... → Join` patterns. The plan
+/// passed in is guaranteed by the caller to be `LogicalPlan::Sort` with
+/// `fetch.is_some()`; we re-bind to a borrow inside.
+pub(super) fn push_topk_through_join(
+ plan: LogicalPlan,
+) -> Result<Transformed<LogicalPlan>> {
+ let LogicalPlan::Sort(sort) = &plan else {
+ return Ok(Transformed::no(plan));
+ };
+ let Some(fetch) = sort.fetch else {
+ return Ok(Transformed::no(plan));
+ };
Review Comment:
This function takes the plan by value and then borrows it. That forces
`sort.expr.clone()` at two places. The caller already destructures
`LogicalPlan::Sort(s)`. Please take `Sort` by value instead.
##########
datafusion/optimizer/src/push_down_limit/topk_through_join.rs:
##########
@@ -0,0 +1,1185 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Sort(fetch) → Join pushdown — a sub-module of `push_down_limit`.
+//!
+//! When a `Sort` with a fetch limit (TopK) sits above a join whose
+//! preserved side is known (LEFT / RIGHT / LeftMark / RightMark / CROSS)
+//! and all sort expressions come from the preserved side, we insert a
+//! copy of the `Sort(fetch)` onto that input to reduce rows entering
+//! the join. The outer `Sort` is kept because a 1-to-many join can
+//! produce more than N output rows from N preserved-side rows.
+//!
+//! Dispatched from `PushDownLimit::rewrite` when the plan node is
+//! `LogicalPlan::Sort` with `fetch.is_some()`.
+
+use std::collections::HashMap;
+use std::sync::Arc;
+
+use crate::utils::{has_all_column_refs, schema_columns};
+
+use datafusion_common::tree_node::{Transformed, TreeNode};
+use datafusion_common::{Column, Result, internal_err};
+use datafusion_expr::logical_plan::{
+ JoinType, LogicalPlan, Projection, Sort as SortPlan, SubqueryAlias,
+};
+use datafusion_expr::{Expr, SortExpr};
+
+/// Which child of a join is being treated as the preserved side.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Side {
+ Left,
+ Right,
+}
+
+/// Top-level pushdown for `Sort(fetch) → ... → Join` patterns. The plan
+/// passed in is guaranteed by the caller to be `LogicalPlan::Sort` with
+/// `fetch.is_some()`; we re-bind to a borrow inside.
+pub(super) fn push_topk_through_join(
+ plan: LogicalPlan,
+) -> Result<Transformed<LogicalPlan>> {
+ let LogicalPlan::Sort(sort) = &plan else {
+ return Ok(Transformed::no(plan));
+ };
+ let Some(fetch) = sort.fetch else {
+ return Ok(Transformed::no(plan));
+ };
+
+ // Don't push if any sort expression is non-deterministic (e.g.
+ // `random()`). Duplicating such expressions would produce different
+ // values at each evaluation point, potentially changing results.
+ if sort.expr.iter().any(|se| se.expr.is_volatile()) {
+ return Ok(Transformed::no(plan));
+ }
+
+ // Peel through transparent nodes (SubqueryAlias, Projection) to
+ // find the Join. Track intermediates so we can reconstruct the tree
+ // and resolve sort expressions through them.
+ let mut current = sort.input.as_ref();
+ let mut intermediates: Vec<&LogicalPlan> = Vec::new();
+ let join = loop {
+ match current {
+ LogicalPlan::Join(join) => break join,
+ LogicalPlan::Projection(proj) => {
+ intermediates.push(current);
+ current = proj.input.as_ref();
+ }
+ LogicalPlan::SubqueryAlias(sq) => {
+ intermediates.push(current);
+ current = sq.input.as_ref();
+ }
+ _ => return Ok(Transformed::no(plan)),
+ }
+ };
+
+ // Determine which side(s) of the join are preserved.
+ //
+ // - LEFT / LeftMark: only left preserved.
+ // - RIGHT / RightMark: symmetric.
+ // - CROSS JOIN (Inner with no `on` keys and no filter):
+ // every row from both sides appears in the output (Cartesian
+ // product), so we can push to whichever side has all the sort
+ // columns.
+ //
+ // For LEFT/RIGHT, non-equijoin filters in the ON clause are safe:
+ // outer joins guarantee all preserved-side rows appear in the
+ // output regardless of the filter. For Inner joins (cross-join
+ // detection), the filter check is strict (`filter.is_none()`) —
+ // any filter on Inner can drop rows from either side.
+ let preserved_candidates: &[Side] = match join.join_type {
+ JoinType::Left | JoinType::LeftMark => &[Side::Left],
+ JoinType::Right | JoinType::RightMark => &[Side::Right],
+ JoinType::Inner if join.on.is_empty() && join.filter.is_none() => {
+ &[Side::Left, Side::Right]
+ }
+ _ => return Ok(Transformed::no(plan)),
+ };
+
+ // Resolve sort expressions through all intermediate nodes
+ // (Projection, SubqueryAlias) so column references match the
+ // join's schema.
+ let mut resolved_sort_exprs = sort.expr.clone();
+ for node in &intermediates {
+ match node {
+ LogicalPlan::Projection(proj) => {
+ resolved_sort_exprs =
+
resolve_sort_exprs_through_projection(&resolved_sort_exprs, proj)?;
+ }
+ LogicalPlan::SubqueryAlias(sq) => {
+ resolved_sort_exprs =
+
resolve_sort_exprs_through_subquery_alias(&resolved_sort_exprs, sq)?;
+ }
+ _ => {
+ return internal_err!(
+ "push_topk_through_join: unexpected intermediate node: {}",
+ node.display()
+ );
+ }
+ }
+ }
+
+ // After resolving through projections, sort expressions may now
+ // contain volatile functions (e.g. `random() AS col`). Duplicating
+ // them would change results.
+ if resolved_sort_exprs.iter().any(|se| se.expr.is_volatile()) {
+ return Ok(Transformed::no(plan));
+ }
+
+ // Pick the first preserved-side candidate whose schema contains all
+ // referenced sort columns. For LEFT/RIGHT this is the fixed side;
+ // for CROSS we try both.
+ let Some(preserved_side) =
preserved_candidates.iter().copied().find(|&side| {
+ let schema = match side {
+ Side::Left => join.left.schema(),
+ Side::Right => join.right.schema(),
+ };
+ let cols = schema_columns(schema);
+ resolved_sort_exprs
+ .iter()
+ .all(|se| has_all_column_refs(&se.expr, &cols))
+ }) else {
+ return Ok(Transformed::no(plan));
+ };
+
+ let preserved_child = match preserved_side {
+ Side::Left => &join.left,
+ Side::Right => &join.right,
+ };
+
+ // Scan deep inside the preserved child (through SubqueryAlias and
+ // Projection layers) to find an existing Sort. If found with same
+ // exprs, tighten its fetch in-place. Otherwise, insert a new Sort
+ // directly below the join as the preserved child's wrapper.
+ let mut inner_child = preserved_child.as_ref();
+ let mut deep_resolved_exprs = resolved_sort_exprs.clone();
+ loop {
+ match inner_child {
+ LogicalPlan::SubqueryAlias(sq) => {
+ deep_resolved_exprs =
+
resolve_sort_exprs_through_subquery_alias(&deep_resolved_exprs, sq)?;
+ inner_child = sq.input.as_ref();
+ }
+ LogicalPlan::Projection(proj) => {
+ deep_resolved_exprs =
+
resolve_sort_exprs_through_projection(&deep_resolved_exprs, proj)?;
+ inner_child = proj.input.as_ref();
+ }
+ _ => break,
+ }
+ }
+
+ // If the inner child is a Limit (PushDownLimit's own Limit handling
+ // hasn't merged it with the Sort yet), skip this iteration.
+ if matches!(inner_child, LogicalPlan::Limit(_)) {
+ return Ok(Transformed::no(plan));
+ }
+
+ // Determine action based on existing inner Sort:
+ // - Same exprs, tighter fetch → skip (already optimal)
+ // - Same exprs, larger/no fetch → tighten in-place
+ // - Different exprs or no Sort → insert new Sort below the join
+ //
+ // If `deep_resolved_exprs` became volatile while resolving through
+ // projections inside the preserved child (e.g. `random() AS col`),
+ // structural equality with an existing inner Sort is unsound: two
+ // identical `random()` exprs evaluate to different values. Fall
+ // back to inserting a new Sort with `resolved_sort_exprs`.
+ let deep_exprs_volatile = deep_resolved_exprs.iter().any(|se|
se.expr.is_volatile());
+ let inner_sort = match inner_child {
+ LogicalPlan::Sort(s) if !deep_exprs_volatile => Some(s),
+ _ => None,
+ };
+ let new_preserved_child = if let Some(child_sort) = inner_sort {
+ let same_exprs = sort_exprs_equal(&child_sort.expr,
&deep_resolved_exprs);
+ let child_fetch_tighter = match child_sort.fetch {
+ Some(child_fetch) => child_fetch <= fetch,
+ None => false,
+ };
+ if same_exprs && child_fetch_tighter {
+ return Ok(Transformed::no(plan));
+ }
+ if same_exprs {
+ rebuild_with_tightened_sort(
+ preserved_child.as_ref(),
+ &deep_resolved_exprs,
+ fetch,
+ )?
+ } else {
+ // Different exprs — insert new Sort above the preserved
+ // child. If the inner Sort has no fetch, our pushed Sort
+ // is the only row reduction. If it has a fetch, re-sorting
+ // a small set is cheap and still reduces join input.
+ Arc::new(LogicalPlan::Sort(SortPlan {
+ expr: resolved_sort_exprs,
+ input: Arc::clone(preserved_child),
+ fetch: Some(fetch),
+ }))
+ }
+ } else {
+ Arc::new(LogicalPlan::Sort(SortPlan {
+ expr: resolved_sort_exprs,
+ input: Arc::clone(preserved_child),
+ fetch: Some(fetch),
+ }))
Review Comment:
These two blocks are the same as lines 226-230. Please merge them. Only the
`same_exprs` tighten path is special.
##########
datafusion/core/src/optimizer_rule_reference.md:
##########
@@ -35,33 +35,34 @@ Rule order matters. The default pipeline may change between
releases.
### Logical Optimizer Rules
-| order | rule | summary
|
-| ----- | ----------------------------------------- |
---------------------------------------------------------------------------------------------------------------------------
|
-| 1 | `rewrite_set_comparison` | Rewrites `ANY` and `ALL`
set-comparison subqueries into `EXISTS`-based boolean expressions with correct
SQL NULL semantics. |
-| 2 | `optimize_unions` | Flattens nested unions
and removes unions with a single input.
|
-| 3 | `unions_to_filter` | Merges `UNION DISTINCT`
branches that share the same source into a single filtered branch with a
disjunctive predicate. |
-| 4 | `simplify_expressions` | Constant-folds and
simplifies expressions while preserving output names.
|
-| 5 | `replace_distinct_aggregate` | Rewrites `DISTINCT` and
`DISTINCT ON` operators into aggregate-based plans that later rules can
optimize further. |
-| 6 | `eliminate_join` | Replaces keyless inner
joins with a literal `false` filter by an empty relation.
|
-| 7 | `decorrelate_predicate_subquery` | Converts eligible `IN`
and `EXISTS` predicate subqueries into semi or anti joins.
|
-| 8 | `scalar_subquery_to_join` | Rewrites eligible scalar
subqueries into joins and adds schema-preserving projections.
|
-| 9 | `decorrelate_lateral_join` | Rewrites eligible
lateral joins into regular joins.
|
-| 10 | `extract_equijoin_predicate` | Splits join filters into
equijoin keys and residual predicates.
|
-| 11 | `eliminate_duplicated_expr` | Removes duplicate
expressions from projections, aggregates, and similar operators.
|
-| 12 | `eliminate_filter` | Drops always-true
filters and replaces always-false or NULL filters with empty relations.
|
-| 13 | `eliminate_cross_join` | Uses filter predicates
to replace cross joins with inner joins when join keys can be found.
|
-| 14 | `eliminate_limit` | Removes no-op limits and
simplifies trivial limit shapes.
|
-| 15 | `propagate_empty_relation` | Pushes empty-relation
knowledge upward so operators fed by no rows collapse early.
|
-| 16 | `filter_null_join_keys` | Adds `IS NOT NULL`
filters to nullable equijoin keys that can never match.
|
-| 17 | `eliminate_outer_join` | Rewrites outer joins to
inner joins when later filters reject the NULL-extended rows.
|
-| 18 | `push_down_limit` | Moves literal limits
closer to scans and unions and merges adjacent limits.
|
-| 19 | `push_down_filter` | Moves filters as early
as possible through filter-commutative operators.
|
-| 20 | `single_distinct_aggregation_to_group_by` | Rewrites single-column
`DISTINCT` aggregations into two-stage `GROUP BY` plans.
|
-| 21 | `eliminate_group_by_constant` | Removes constant or
functionally redundant expressions from `GROUP BY`.
|
-| 22 | `common_sub_expression_eliminate` | Computes repeated
subexpressions once and reuses the result.
|
-| 23 | `extract_leaf_expressions` | Pulls cheap leaf
expressions closer to data sources so later pruning and filter rules can act
earlier. |
-| 24 | `push_down_leaf_projections` | Pushes the helper
projections created by leaf extraction toward leaf inputs.
|
-| 25 | `optimize_projections` | Prunes unused columns
and removes unnecessary logical projections.
|
+| order
| rule | summary
|
+|
-----------------------------------------------------------------------------------
| ----------------------------------------- |
---------------------------------------------------------------------------------------------------------------------------
|
+| 1
| `rewrite_set_comparison` | Rewrites `ANY` and `ALL`
set-comparison subqueries into `EXISTS`-based boolean expressions with correct
SQL NULL semantics. |
+| 2
| `optimize_unions` | Flattens nested unions and
removes unions with a single input.
|
+| 3
| `unions_to_filter` | Merges `UNION DISTINCT`
branches that share the same source into a single filtered branch with a
disjunctive predicate. |
+| 4
| `simplify_expressions` | Constant-folds and
simplifies expressions while preserving output names.
|
+| 5
| `replace_distinct_aggregate` | Rewrites `DISTINCT` and
`DISTINCT ON` operators into aggregate-based plans that later rules can
optimize further. |
+| 6
| `eliminate_join` | Replaces keyless inner
joins with a literal `false` filter by an empty relation.
|
+| 7
| `decorrelate_predicate_subquery` | Converts eligible `IN` and
`EXISTS` predicate subqueries into semi or anti joins.
|
+| 8
| `scalar_subquery_to_join` | Rewrites eligible scalar
subqueries into joins and adds schema-preserving projections.
|
+| 9
| `decorrelate_lateral_join` | Rewrites eligible lateral
joins into regular joins.
|
+| 10
| `extract_equijoin_predicate` | Splits join filters into
equijoin keys and residual predicates.
|
+| 11
| `eliminate_duplicated_expr` | Removes duplicate
expressions from projections, aggregates, and similar operators.
|
+| 12
| `eliminate_filter` | Drops always-true filters
and replaces always-false or NULL filters with empty relations.
|
+| 13
| `eliminate_cross_join` | Uses filter predicates to
replace cross joins with inner joins when join keys can be found.
|
+| 14
| `eliminate_limit` | Removes no-op limits and
simplifies trivial limit shapes.
|
+| 15
| `propagate_empty_relation` | Pushes empty-relation
knowledge upward so operators fed by no rows collapse early.
|
+| 16
| `filter_null_join_keys` | Adds `IS NOT NULL` filters
to nullable equijoin keys that can never match.
|
+| 17
| `eliminate_outer_join` | Rewrites outer joins to
inner joins when later filters reject the NULL-extended rows.
|
+| 18
| `push_down_limit` | Moves literal limits
closer to scans and unions and merges adjacent limits, and pushes
|
+| `Sort(fetch=N)` onto a join's preserved-side child for LEFT/RIGHT/CROSS/MARK
joins. |
Review Comment:
This table row is broken. The summary text has a newline. This splits row 18
and makes a second row with one cell. The other 53 changed lines in this file
are column padding that follows from the split. Please put the summary on one
line. The diff then becomes one line.
Please also say two things in the summary. The outer `Sort` stays. The push
happens only when all sort keys come from the preserved side. The module doc in
`topk_through_join.rs` says both.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]