geoffreyclaude commented on code in PR #26118: URL: https://github.com/apache/datafusion/pull/26118#discussion_r4378994493
########## datafusion/sqllogictest/src/test_context/custom_sort_pushdown.rs: ########## @@ -0,0 +1,231 @@ +// 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. + +use std::fmt::{self, Formatter}; +use std::sync::Arc; + +use arrow::array::record_batch; +use arrow::datatypes::{self as arrow_schema, SchemaRef}; +use async_trait::async_trait; +use datafusion::catalog::{Session, TableProvider}; +use datafusion::common::Result; +use datafusion::common::config::ConfigOptions; +use datafusion::common::tree_node::{Transformed, TreeNode, TreeNodeRecursion}; +use datafusion::execution::{SendableRecordBatchStream, TaskContext}; +use datafusion::logical_expr::{Expr, Operator, TableType}; +use datafusion::physical_expr::expressions::{binary, col, lit, negative}; +use datafusion::physical_expr::projection::ProjectionExprs; +use datafusion::physical_expr::{PhysicalExpr, PhysicalSortExpr}; +use datafusion::physical_optimizer::PhysicalOptimizerRule; +use datafusion::physical_plan::filter::FilterExec; +use datafusion::physical_plan::limit::LocalLimitExec; +use datafusion::physical_plan::projection::ProjectionExec; +use datafusion::physical_plan::sorts::sort::SortExec; +use datafusion::physical_plan::test::TestMemoryExec; +use datafusion::physical_plan::{ + ChildrenPropertiesMode, DisplayAs, DisplayFormatType, ExecutionPlan, + ExecutionPlanProperties, PlanProperties, ReplaceChildrenOptions, +}; +use datafusion::prelude::SessionContext; + +/// Register custom plans whose native implementations are hidden from the optimizer. +pub(super) fn register_custom_sort_pushdown(ctx: &SessionContext) -> Result<()> { + let batch = record_batch!(("a", Int32, [2, 1, 3]))?; + let schema = batch.schema(); + let input = TestMemoryExec::try_new_exec(&[vec![batch]], Arc::clone(&schema), None)?; + let projection = ProjectionExec::try_new( + [(negative(col("a", &schema)?, &schema)?, "a".to_string())], + input, + )?; + ctx.register_table( + "custom_negated_projection", + Arc::new(CustomExec(Arc::new(projection))), + )?; + + let batch = record_batch!(("a", Int32, [2, 1, 3]), ("b", Int32, [10, 30, 20]))?; + let schema = batch.schema(); + let input = TestMemoryExec::try_new_exec(&[vec![batch]], Arc::clone(&schema), None)?; + let projection = ProjectionExec::try_new( + [ + (col("b", &schema)?, "a".to_string()), + (col("a", &schema)?, "b".to_string()), + ], + input, + )?; + ctx.register_table( + "custom_reordered_projection", + Arc::new(CustomExec(Arc::new(projection))), + )?; + + let batch = record_batch!(("t", Int32, [1, 2, 3]), ("x", Int32, [0, 2, 4]))?; + let schema = batch.schema(); + let input = TestMemoryExec::try_new_exec(&[vec![batch]], Arc::clone(&schema), None)?; + let predicate = binary(col("x", &schema)?, Operator::NotEq, lit(0i32), &schema)?; + ctx.register_table( + "custom_filtered_input", + Arc::new(CustomExec(Arc::new(FilterExec::try_new(predicate, input)?))), + )?; + + let batch = record_batch!(("a", Int32, [1, 2, 3]), ("b", Int32, [30, 20, 10]))?; + let schema = batch.schema(); + let ordering = + [PhysicalSortExpr::new_default(col("a", &schema)?).nulls_last()].into(); + let input = Arc::new( + TestMemoryExec::try_new(&[vec![batch]], Arc::clone(&schema), None)? + .try_with_sort_information(vec![ordering])?, + ); + ctx.register_table("custom_ordered_input", Arc::new(CustomExec(input)))?; + Ok(()) +} + +/// Plans `ORDER BY ... LIMIT` as a custom node to test generic sort pushdown. +#[derive(Debug)] +pub(super) struct CustomLimitRule; + +impl PhysicalOptimizerRule for CustomLimitRule { + fn optimize( + &self, + plan: Arc<dyn ExecutionPlan>, + _: &ConfigOptions, + ) -> Result<Arc<dyn ExecutionPlan>> { + plan.transform_up(|plan| { + let Some(sort) = plan.downcast_ref::<SortExec>() else { + return Ok(Transformed::no(plan)); + }; + let Some(fetch) = sort.fetch() else { + return Ok(Transformed::no(plan)); + }; + let input = sort.input(); + let source = input + .downcast_ref::<ProjectionExec>() + .map_or(input, |projection| projection.input()); + let Some(source) = source.downcast_ref::<CustomExec>() else { + return Ok(Transformed::no(plan)); + }; + // Only the dedicated ordered source is a wrapped memory scan. + if !source.0.is::<TestMemoryExec>() + || input.output_partitioning().partition_count() != 1 + || !input + .equivalence_properties() + .ordering_satisfy(sort.expr().clone())? + { + return Ok(Transformed::no(plan)); + } + let limit = LocalLimitExec::new(Arc::clone(input), fetch); + let plan: Arc<dyn ExecutionPlan> = Arc::new(CustomExec(Arc::new(limit))); + Ok(Transformed::yes(plan)) + }) + .map(|transformed| transformed.data) + } + + fn name(&self) -> &str { + "CustomLimitRule" + } + + fn schema_check(&self) -> bool { + true + } +} + +/// Exposes a native plan's children and properties under a distinct plan type, +/// exercising the generic custom-plan sort pushdown path. +#[derive(Debug, Clone)] +struct CustomExec(Arc<dyn ExecutionPlan>); + +#[async_trait] +impl TableProvider for CustomExec { + fn schema(&self) -> SchemaRef { + self.0.schema() + } + + fn table_type(&self) -> TableType { + TableType::Base + } + + async fn scan( + &self, + _: &dyn Session, + projection: Option<&[usize]>, + _: &[Expr], + _: Option<usize>, + ) -> Result<Arc<dyn ExecutionPlan>> { + let plan: Arc<dyn ExecutionPlan> = Arc::new(self.clone()); + if let Some(projection) = projection { Review Comment: Good catch, I’ve skipped the identity projection as suggested. Removing the guard now makes the query fail with division by zero. -- 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]
