datafusion_session/planner.rs
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! Query planner interfaces.
6
7use std::any::Any;
8use std::fmt::Debug;
9use std::sync::Arc;
10
11use async_trait::async_trait;
12use datafusion_common::{DFSchema, Result, not_impl_err};
13use datafusion_expr::physical_planning_context::PhysicalPlanningContext;
14use datafusion_expr::{Expr, LogicalPlan, TableScan, UserDefinedLogicalNode};
15use datafusion_physical_plan::{ExecutionPlan, PhysicalExpr};
16
17use crate::Session;
18
19/// A planner that creates a physical plan for a query.
20#[async_trait]
21pub trait QueryPlanner: Any + Debug {
22 /// Given a [`LogicalPlan`], create an [`ExecutionPlan`] suitable for execution
23 async fn create_physical_plan(
24 &self,
25 logical_plan: &LogicalPlan,
26 session: &dyn Session,
27 ) -> Result<Arc<dyn ExecutionPlan>>;
28}
29
30/// A query planner that reports that planning is not implemented.
31///
32/// [`Session`] implementations that do not expose a query planner can return
33/// this planner explicitly.
34#[derive(Debug, Default)]
35pub struct UnsupportedQueryPlanner;
36
37#[async_trait]
38impl QueryPlanner for UnsupportedQueryPlanner {
39 async fn create_physical_plan(
40 &self,
41 _logical_plan: &LogicalPlan,
42 _session: &dyn Session,
43 ) -> Result<Arc<dyn ExecutionPlan>> {
44 not_impl_err!("This session does not expose its query planner")
45 }
46}
47
48/// Physical query planner that converts a [`LogicalPlan`] to an
49/// [`ExecutionPlan`] suitable for execution.
50#[async_trait]
51pub trait PhysicalPlanner: Send + Sync {
52 /// Create a physical plan from a logical plan
53 async fn create_physical_plan(
54 &self,
55 logical_plan: &LogicalPlan,
56 session: &dyn Session,
57 ) -> Result<Arc<dyn ExecutionPlan>>;
58
59 /// Create a physical expression from a logical expression
60 /// suitable for evaluation
61 ///
62 /// `expr`: the expression to convert
63 ///
64 /// `input_dfschema`: the logical plan schema for evaluating `expr`
65 ///
66 /// `planning_ctx`: the [`PhysicalPlanningContext`] used to resolve
67 /// `Expr::ScalarSubquery` nodes. During physical planning the planner
68 /// threads the context of the plan currently being converted to a physical
69 /// plan (for example into [`ExtensionPlanner::plan_extension`], which
70 /// should forward it here). Callers creating physical expressions outside
71 /// of a plan should pass `&PhysicalPlanningContext::default()`.
72 fn create_physical_expr(
73 &self,
74 expr: &Expr,
75 input_dfschema: &DFSchema,
76 session: &dyn Session,
77 planning_ctx: &PhysicalPlanningContext,
78 ) -> Result<Arc<dyn PhysicalExpr>>;
79}
80
81/// This trait exposes the ability to plan an [`ExecutionPlan`] out of a [`LogicalPlan`].
82#[async_trait]
83pub trait ExtensionPlanner {
84 /// Create a physical plan for a [`UserDefinedLogicalNode`].
85 ///
86 /// `input_dfschema`: the logical plan schema for the inputs to this node
87 ///
88 /// Returns an error when the planner knows how to plan the concrete
89 /// implementation of `node` but errors while doing so.
90 ///
91 /// Returns `None` when the planner does not know how to plan the
92 /// `node` and wants to delegate the planning to another
93 /// [`ExtensionPlanner`].
94 ///
95 /// `planning_ctx` is the [`PhysicalPlanningContext`] of the plan subtree
96 /// currently being converted to a physical plan. Forward it to
97 /// [`PhysicalPlanner::create_physical_expr`] when creating this node's
98 /// physical expressions so that scalar subqueries resolve against the same
99 /// subquery state as the rest of the plan.
100 async fn plan_extension(
101 &self,
102 planner: &dyn PhysicalPlanner,
103 node: &dyn UserDefinedLogicalNode,
104 logical_inputs: &[&LogicalPlan],
105 physical_inputs: &[Arc<dyn ExecutionPlan>],
106 session: &dyn Session,
107 planning_ctx: &PhysicalPlanningContext,
108 ) -> Result<Option<Arc<dyn ExecutionPlan>>>;
109
110 /// Create a physical plan for a [`LogicalPlan::TableScan`].
111 ///
112 /// This is useful for planning valid [`TableSource`]s that are not `TableProvider`s.
113 ///
114 /// Returns:
115 /// * `Ok(Some(plan))` if the planner knows how to plan the `scan`
116 /// * `Ok(None)` if the planner does not know how to plan the `scan` and wants to delegate the planning to another [`ExtensionPlanner`]
117 /// * `Err` if the planner knows how to plan the `scan` but errors while doing so
118 ///
119 /// # Example
120 ///
121 /// ```rust,ignore
122 /// use std::sync::Arc;
123 /// use datafusion::physical_plan::ExecutionPlan;
124 /// use datafusion::logical_expr::TableScan;
125 /// use datafusion::catalog::Session;
126 /// use datafusion::error::Result;
127 /// use datafusion_session::{ExtensionPlanner, PhysicalPlanner};
128 /// use async_trait::async_trait;
129 ///
130 /// // Your custom table source type
131 /// struct MyCustomTableSource { /* ... */ }
132 ///
133 /// // Your custom execution plan
134 /// struct MyCustomExec { /* ... */ }
135 ///
136 /// struct MyExtensionPlanner;
137 ///
138 /// #[async_trait]
139 /// impl ExtensionPlanner for MyExtensionPlanner {
140 /// async fn plan_extension(
141 /// &self,
142 /// _planner: &dyn PhysicalPlanner,
143 /// _node: &dyn UserDefinedLogicalNode,
144 /// _logical_inputs: &[&LogicalPlan],
145 /// _physical_inputs: &[Arc<dyn ExecutionPlan>],
146 /// _session: &dyn Session,
147 /// _planning_ctx: &PhysicalPlanningContext,
148 /// ) -> Result<Option<Arc<dyn ExecutionPlan>>> {
149 /// Ok(None)
150 /// }
151 ///
152 /// async fn plan_table_scan(
153 /// &self,
154 /// _planner: &dyn PhysicalPlanner,
155 /// scan: &TableScan,
156 /// _session: &dyn Session,
157 /// _planning_ctx: &PhysicalPlanningContext,
158 /// ) -> Result<Option<Arc<dyn ExecutionPlan>>> {
159 /// // Check if this is your custom table source
160 /// if scan.source.is::<MyCustomTableSource>() {
161 /// // Create a custom execution plan for your table source
162 /// let exec = MyCustomExec::new(
163 /// scan.table_name.clone(),
164 /// Arc::clone(scan.projected_schema.inner()),
165 /// );
166 /// Ok(Some(Arc::new(exec)))
167 /// } else {
168 /// // Return None to let other extension planners handle it
169 /// Ok(None)
170 /// }
171 /// }
172 /// }
173 /// ```
174 ///
175 /// [`TableSource`]: datafusion_expr::TableSource
176 async fn plan_table_scan(
177 &self,
178 _planner: &dyn PhysicalPlanner,
179 _scan: &TableScan,
180 _session: &dyn Session,
181 _planning_ctx: &PhysicalPlanningContext,
182 ) -> Result<Option<Arc<dyn ExecutionPlan>>> {
183 Ok(None)
184 }
185}