datafusion_expr/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//! [`ContextProvider`] and [`ExprPlanner`] APIs to customize SQL query planning
6
7use std::fmt::Debug;
8use std::sync::Arc;
9
10use crate::expr::NullTreatment;
11#[cfg(feature = "sql")]
12use crate::logical_plan::LogicalPlan;
13use crate::{
14 AggregateUDF, Expr, GetFieldAccess, HigherOrderUDF, ScalarUDF, SortExpr, TableSource,
15 WindowFrame, WindowFunctionDefinition, WindowUDF,
16};
17use arrow::datatypes::{DataType, Field, FieldRef, SchemaRef};
18use datafusion_common::datatype::DataTypeExt;
19use datafusion_common::{
20 DFSchema, Result, TableReference, config::ConfigOptions,
21 file_options::file_type::FileType, not_impl_err,
22};
23#[cfg(feature = "sql")]
24use sqlparser::ast::{Expr as SQLExpr, Ident, ObjectName, TableAlias, TableFactor};
25
26/// Provides the `SQL` query planner meta-data about tables and
27/// functions referenced in SQL statements, without a direct dependency on the
28/// `datafusion` Catalog structures such as [`TableProvider`]
29///
30/// [`TableProvider`]: https://docs.rs/datafusion/latest/datafusion/catalog/trait.TableProvider.html
31pub trait ContextProvider {
32 /// Returns a table by reference, if it exists
33 fn get_table_source(&self, name: TableReference) -> Result<Arc<dyn TableSource>>;
34
35 /// Return the type of a file based on its extension (e.g. `.parquet`)
36 ///
37 /// This is used to plan `COPY` statements
38 fn get_file_type(&self, _ext: &str) -> Result<Arc<dyn FileType>> {
39 not_impl_err!("Registered file types are not supported")
40 }
41
42 /// Getter for a table function
43 fn get_table_function_source(
44 &self,
45 _name: &str,
46 _args: Vec<Expr>,
47 ) -> Result<Arc<dyn TableSource>> {
48 not_impl_err!("Table Functions are not supported")
49 }
50
51 /// Provides an intermediate table that is used to expose a recursive CTE
52 /// self-reference during planning and execution.
53 ///
54 /// CTE stands for "Common Table Expression"
55 ///
56 /// # Notes
57 /// We don't directly implement this in [`SqlToRel`] as implementing this function
58 /// often requires access to a table that contains
59 /// execution-related types that can't be a direct dependency
60 /// of the sql crate (for example [`CteWorkTable`]).
61 ///
62 /// The [`ContextProvider`] provides a way to "hide" this dependency.
63 /// The schema argument is the schema to expose for scans of the recursive
64 /// self-reference, which may be more conservative than the final recursive
65 /// query output schema.
66 ///
67 /// [`SqlToRel`]: https://docs.rs/datafusion/latest/datafusion/sql/planner/struct.SqlToRel.html
68 /// [`CteWorkTable`]: https://docs.rs/datafusion/latest/datafusion/datasource/cte_worktable/struct.CteWorkTable.html
69 fn create_cte_work_table(
70 &self,
71 _name: &str,
72 _schema: SchemaRef,
73 ) -> Result<Arc<dyn TableSource>> {
74 not_impl_err!("Recursive CTE is not implemented")
75 }
76
77 /// Return [`ExprPlanner`] extensions for planning expressions
78 fn get_expr_planners(&self) -> &[Arc<dyn ExprPlanner>] {
79 &[]
80 }
81
82 /// Return [`RelationPlanner`] extensions for planning table factors
83 #[cfg(feature = "sql")]
84 fn get_relation_planners(&self) -> &[Arc<dyn RelationPlanner>] {
85 &[]
86 }
87
88 /// Return [`TypePlanner`] extensions for planning data types
89 #[cfg(feature = "sql")]
90 fn get_type_planner(&self) -> Option<Arc<dyn TypePlanner>> {
91 None
92 }
93
94 /// Return the scalar function with a given name, if any
95 fn get_function_meta(&self, name: &str) -> Option<Arc<ScalarUDF>>;
96
97 /// Return the higher order function with a given name, if any
98 fn get_higher_order_meta(&self, name: &str) -> Option<Arc<HigherOrderUDF>>;
99
100 /// Return the aggregate function with a given name, if any
101 fn get_aggregate_meta(&self, name: &str) -> Option<Arc<AggregateUDF>>;
102
103 /// Return the window function with a given name, if any
104 fn get_window_meta(&self, name: &str) -> Option<Arc<WindowUDF>>;
105
106 /// Return the system/user-defined variable type, if any
107 ///
108 /// A user defined variable is typically accessed via `@var_name`
109 fn get_variable_type(&self, variable_names: &[String]) -> Option<DataType>;
110
111 /// Return metadata about a system/user-defined variable, if any.
112 ///
113 /// By default, this wraps [`Self::get_variable_type`] in an Arrow [`Field`]
114 /// with nullable set to `true` and no metadata. Implementations that can
115 /// provide richer information (such as nullability or extension metadata)
116 /// should override this method.
117 fn get_variable_field(&self, variable_names: &[String]) -> Option<FieldRef> {
118 self.get_variable_type(variable_names)
119 .map(|data_type| data_type.into_nullable_field_ref())
120 }
121
122 /// Return overall configuration options
123 fn options(&self) -> &ConfigOptions;
124
125 /// Return all scalar function names
126 fn udf_names(&self) -> Vec<String>;
127
128 /// Return all higher order function names
129 fn higher_order_function_names(&self) -> Vec<String>;
130
131 /// Return all aggregate function names
132 fn udaf_names(&self) -> Vec<String>;
133
134 /// Return all window function names
135 fn udwf_names(&self) -> Vec<String>;
136}
137
138/// Customize planning of SQL AST expressions to [`Expr`]s
139///
140/// For more background, please also see the [Extending SQL in DataFusion: from ->> to TABLESAMPLE blog]
141///
142/// [Extending SQL in DataFusion: from ->> to TABLESAMPLE blog]: https://datafusion.apache.org/blog/2026/01/12/extending-sql
143pub trait ExprPlanner: Debug + Send + Sync {
144 /// Plan the binary operation between two expressions, returns original
145 /// BinaryExpr if not possible
146 fn plan_binary_op(
147 &self,
148 expr: RawBinaryExpr,
149 _schema: &DFSchema,
150 ) -> Result<PlannerResult<RawBinaryExpr>> {
151 Ok(PlannerResult::Original(expr))
152 }
153
154 /// Plan the field access expression, such as `foo.bar`
155 ///
156 /// returns original [`RawFieldAccessExpr`] if not possible
157 fn plan_field_access(
158 &self,
159 expr: RawFieldAccessExpr,
160 _schema: &DFSchema,
161 ) -> Result<PlannerResult<RawFieldAccessExpr>> {
162 Ok(PlannerResult::Original(expr))
163 }
164
165 /// Plan an array literal, such as `[1, 2, 3]`
166 ///
167 /// Returns original expression arguments if not possible
168 fn plan_array_literal(
169 &self,
170 exprs: Vec<Expr>,
171 _schema: &DFSchema,
172 ) -> Result<PlannerResult<Vec<Expr>>> {
173 Ok(PlannerResult::Original(exprs))
174 }
175
176 /// Plan a `POSITION` expression, such as `POSITION(<expr> in <expr>)`
177 ///
178 /// Returns original expression arguments if not possible
179 fn plan_position(&self, args: Vec<Expr>) -> Result<PlannerResult<Vec<Expr>>> {
180 Ok(PlannerResult::Original(args))
181 }
182
183 /// Plan a dictionary literal, such as `{ key: value, ...}`
184 ///
185 /// Returns original expression arguments if not possible
186 fn plan_dictionary_literal(
187 &self,
188 expr: RawDictionaryExpr,
189 _schema: &DFSchema,
190 ) -> Result<PlannerResult<RawDictionaryExpr>> {
191 Ok(PlannerResult::Original(expr))
192 }
193
194 /// Plan an extract expression, such as`EXTRACT(month FROM foo)`
195 ///
196 /// Returns original expression arguments if not possible
197 fn plan_extract(&self, args: Vec<Expr>) -> Result<PlannerResult<Vec<Expr>>> {
198 Ok(PlannerResult::Original(args))
199 }
200
201 /// Plan an substring expression, such as `SUBSTRING(<expr> [FROM <expr>] [FOR <expr>])`
202 ///
203 /// Returns original expression arguments if not possible
204 fn plan_substring(&self, args: Vec<Expr>) -> Result<PlannerResult<Vec<Expr>>> {
205 Ok(PlannerResult::Original(args))
206 }
207
208 /// Plan `<expr> AT TIME ZONE '<tz>'`.
209 ///
210 /// `args` is `[Utf8 literal tz, expr]`, the argument order of the
211 /// PostgreSQL function form `timezone(zone, expr)`.
212 ///
213 /// The result type depends on whether the type of `expr` *after type
214 /// coercion* has a timezone, and the SQL planner runs before type
215 /// coercion. So an implementation must return an expression that decides
216 /// later, such as the `timezone` function of `datafusion-functions`.
217 ///
218 /// Returns original expression arguments if not possible
219 fn plan_at_time_zone(&self, args: Vec<Expr>) -> Result<PlannerResult<Vec<Expr>>> {
220 Ok(PlannerResult::Original(args))
221 }
222
223 /// Plans a struct literal, such as `{'field1' : expr1, 'field2' : expr2, ...}`
224 ///
225 /// This function takes a vector of expressions and a boolean flag
226 /// indicating whether the struct uses the optional name
227 ///
228 /// Returns the original input expressions if planning is not possible.
229 fn plan_struct_literal(
230 &self,
231 args: Vec<Expr>,
232 _is_named_struct: bool,
233 ) -> Result<PlannerResult<Vec<Expr>>> {
234 Ok(PlannerResult::Original(args))
235 }
236
237 /// Plans an overlay expression, such as `overlay(str PLACING substr FROM pos [FOR count])`
238 ///
239 /// Returns original expression arguments if not possible
240 fn plan_overlay(&self, args: Vec<Expr>) -> Result<PlannerResult<Vec<Expr>>> {
241 Ok(PlannerResult::Original(args))
242 }
243
244 /// Plans a `make_map` expression, such as `make_map(key1, value1, key2, value2, ...)`
245 ///
246 /// Returns original expression arguments if not possible
247 fn plan_make_map(&self, args: Vec<Expr>) -> Result<PlannerResult<Vec<Expr>>> {
248 Ok(PlannerResult::Original(args))
249 }
250
251 /// Plans compound identifier such as `db.schema.table` for non-empty nested names
252 ///
253 /// # Note:
254 /// Currently compound identifier for outer query schema is not supported.
255 ///
256 /// Returns original expression if not possible
257 fn plan_compound_identifier(
258 &self,
259 _field: &Field,
260 _qualifier: Option<&TableReference>,
261 _nested_names: &[String],
262 ) -> Result<PlannerResult<Vec<Expr>>> {
263 not_impl_err!(
264 "Default planner compound identifier hasn't been implemented for ExprPlanner"
265 )
266 }
267
268 /// Plans scalar functions, such as `ABS(<expr>)`
269 ///
270 /// Returns the original scalar function if not possible
271 fn plan_scalar(
272 &self,
273 expr: RawScalarExpr,
274 _schema: &DFSchema,
275 ) -> Result<PlannerResult<RawScalarExpr>> {
276 Ok(PlannerResult::Original(expr))
277 }
278
279 /// Plans aggregate functions, such as `COUNT(<expr>)`
280 ///
281 /// Returns original expression arguments if not possible
282 fn plan_aggregate(
283 &self,
284 expr: RawAggregateExpr,
285 ) -> Result<PlannerResult<RawAggregateExpr>> {
286 Ok(PlannerResult::Original(expr))
287 }
288
289 /// Plans window functions, such as `COUNT(<expr>)`
290 ///
291 /// Returns original expression arguments if not possible
292 fn plan_window(&self, expr: RawWindowExpr) -> Result<PlannerResult<RawWindowExpr>> {
293 Ok(PlannerResult::Original(expr))
294 }
295}
296
297/// An operator with two arguments to plan
298///
299/// Note `left` and `right` are DataFusion [`Expr`]s but the `op` is the SQL AST
300/// operator.
301///
302/// This structure is used by [`ExprPlanner`] to plan operators with
303/// custom expressions.
304#[derive(Debug, Clone)]
305pub struct RawBinaryExpr {
306 #[cfg(not(feature = "sql"))]
307 pub op: datafusion_expr_common::operator::Operator,
308 #[cfg(feature = "sql")]
309 pub op: sqlparser::ast::BinaryOperator,
310 pub left: Expr,
311 pub right: Expr,
312}
313
314/// An expression with GetFieldAccess to plan
315///
316/// This structure is used by [`ExprPlanner`] to plan operators with
317/// custom expressions.
318#[derive(Debug, Clone)]
319pub struct RawFieldAccessExpr {
320 pub field_access: GetFieldAccess,
321 pub expr: Expr,
322}
323
324/// A Dictionary literal expression `{ key: value, ...}`
325///
326/// This structure is used by [`ExprPlanner`] to plan operators with
327/// custom expressions.
328#[derive(Debug, Clone)]
329pub struct RawDictionaryExpr {
330 pub keys: Vec<Expr>,
331 pub values: Vec<Expr>,
332}
333
334/// A scalar function to plan with [`ExprPlanner`].
335#[derive(Debug, Clone)]
336pub struct RawScalarExpr {
337 pub func: Arc<ScalarUDF>,
338 pub args: Vec<Expr>,
339}
340
341/// This structure is used by `AggregateFunctionPlanner` to plan operators with
342/// custom expressions.
343#[derive(Debug, Clone)]
344pub struct RawAggregateExpr {
345 pub func: Arc<AggregateUDF>,
346 pub args: Vec<Expr>,
347 pub distinct: bool,
348 pub filter: Option<Box<Expr>>,
349 pub order_by: Vec<SortExpr>,
350 pub null_treatment: Option<NullTreatment>,
351}
352
353/// This structure is used by `WindowFunctionPlanner` to plan operators with
354/// custom expressions.
355#[derive(Debug, Clone)]
356pub struct RawWindowExpr {
357 pub func_def: WindowFunctionDefinition,
358 pub args: Vec<Expr>,
359 pub partition_by: Vec<Expr>,
360 pub order_by: Vec<SortExpr>,
361 pub window_frame: WindowFrame,
362 pub filter: Option<Box<Expr>>,
363 pub null_treatment: Option<NullTreatment>,
364 pub distinct: bool,
365}
366
367/// Result of planning a raw expr with [`ExprPlanner`]
368#[derive(Debug, Clone)]
369pub enum PlannerResult<T> {
370 /// The raw expression was successfully planned as a new [`Expr`]
371 Planned(Expr),
372 /// The raw expression could not be planned, and is returned unmodified
373 Original(T),
374}
375
376/// Result of planning a relation with [`RelationPlanner`]
377#[cfg(feature = "sql")]
378#[derive(Debug, Clone)]
379pub struct PlannedRelation {
380 /// The logical plan for the relation
381 pub plan: LogicalPlan,
382 /// Optional table alias for the relation
383 pub alias: Option<TableAlias>,
384}
385
386#[cfg(feature = "sql")]
387impl PlannedRelation {
388 /// Create a new `PlannedRelation` with the given plan and alias
389 pub fn new(plan: LogicalPlan, alias: Option<TableAlias>) -> Self {
390 Self { plan, alias }
391 }
392}
393
394/// Result of attempting to plan a relation with extension planners
395#[cfg(feature = "sql")]
396#[derive(Debug)]
397pub enum RelationPlanning {
398 /// The relation was successfully planned by an extension planner
399 Planned(Box<PlannedRelation>),
400 /// No extension planner handled the relation, return it for default processing
401 Original(Box<TableFactor>),
402}
403
404/// Customize planning SQL table factors to [`LogicalPlan`]s.
405#[cfg(feature = "sql")]
406/// For more background, please also see the [Extending SQL in DataFusion: from ->> to TABLESAMPLE blog]
407///
408/// [Extending SQL in DataFusion: from ->> to TABLESAMPLE blog]: https://datafusion.apache.org/blog/2026/01/12/extending-sql
409pub trait RelationPlanner: Debug + Send + Sync {
410 /// Plan a table factor into a [`LogicalPlan`].
411 ///
412 /// Returning [`RelationPlanning::Planned`] short-circuits further planning and uses the
413 /// provided plan. Returning [`RelationPlanning::Original`] allows the next registered planner,
414 /// or DataFusion's default logic, to handle the relation.
415 fn plan_relation(
416 &self,
417 relation: TableFactor,
418 context: &mut dyn RelationPlannerContext,
419 ) -> Result<RelationPlanning>;
420}
421
422/// Provides utilities for relation planners to interact with DataFusion's SQL
423/// planner.
424///
425/// This trait provides SQL planning utilities specific to relation planning,
426/// such as converting SQL expressions to logical expressions and normalizing
427/// identifiers. It uses composition to provide access to session context via
428/// [`ContextProvider`].
429#[cfg(feature = "sql")]
430pub trait RelationPlannerContext {
431 /// Provides access to the underlying context provider for reading session
432 /// configuration, accessing tables, functions, and other metadata.
433 fn context_provider(&self) -> &dyn ContextProvider;
434
435 /// Plans the specified relation through the full planner pipeline, starting
436 /// from the first registered relation planner.
437 fn plan(&mut self, relation: TableFactor) -> Result<LogicalPlan>;
438
439 /// Returns the common table expression (CTE) visible for the specified
440 /// table reference in the current query scope, if any.
441 ///
442 /// Relation planners run before DataFusion's built-in relation planning. A
443 /// planner that recognizes ordinary tables by name can use this method to
444 /// pass a same-named relation to the remaining planners. When every
445 /// ordinary name-based planner does so, built-in CTE resolution is
446 /// preserved. Use [`Self::object_name_to_table_reference`] to normalize an
447 /// [`ObjectName`] before looking it up.
448 ///
449 /// The lookup follows the same string-key matching as DataFusion's built-in
450 /// relation planning, including for qualified table references. Different
451 /// [`TableReference`] variants with the same string representation therefore
452 /// use the same CTE lookup key.
453 ///
454 /// The default implementation returns `None` for compatibility with custom
455 /// implementations of this context.
456 fn get_cte(&self, _name: &TableReference) -> Option<&LogicalPlan> {
457 None
458 }
459
460 /// Converts a SQL expression into a logical expression using the current
461 /// planner context.
462 fn sql_to_expr(&mut self, expr: SQLExpr, schema: &DFSchema) -> Result<Expr>;
463
464 /// Converts a SQL expression into a logical expression without DataFusion
465 /// rewrites.
466 fn sql_expr_to_logical_expr(
467 &mut self,
468 expr: SQLExpr,
469 schema: &DFSchema,
470 ) -> Result<Expr>;
471
472 /// Normalizes an identifier according to session settings.
473 fn normalize_ident(&self, ident: Ident) -> String;
474
475 /// Normalizes a SQL object name into a [`TableReference`].
476 fn object_name_to_table_reference(&self, name: ObjectName) -> Result<TableReference>;
477}
478
479/// Customize planning SQL types to DataFusion (Arrow) types.
480#[cfg(feature = "sql")]
481/// For more background, please also see the [Extending SQL in DataFusion: from ->> to TABLESAMPLE blog]
482///
483/// [Extending SQL in DataFusion: from ->> to TABLESAMPLE blog]: https://datafusion.apache.org/blog/2026/01/12/extending-sql
484pub trait TypePlanner: Debug + Send + Sync {
485 /// Plan SQL [`sqlparser::ast::DataType`] to DataFusion [`DataType`]
486 ///
487 /// Returns None if not possible
488 #[deprecated(since = "53.0.0", note = "Use plan_type_field()")]
489 fn plan_type(
490 &self,
491 _sql_type: &sqlparser::ast::DataType,
492 ) -> Result<Option<DataType>> {
493 Ok(None)
494 }
495
496 /// Plan SQL [`sqlparser::ast::DataType`] to DataFusion [`FieldRef`]
497 ///
498 /// Returns None if not possible. Unlike [`Self::plan_type`], `plan_type_field()`
499 /// makes it possible to express extension types (e.g., `arrow.uuid`) or otherwise
500 /// insert metadata into the DataFusion type representation. The default implementation
501 /// falls back on [`Self::plan_type`] for backward compatibility and wraps the result
502 /// in a nullable field reference.
503 fn plan_type_field(
504 &self,
505 sql_type: &sqlparser::ast::DataType,
506 ) -> Result<Option<FieldRef>> {
507 #[expect(deprecated)]
508 Ok(self
509 .plan_type(sql_type)?
510 .map(|data_type| data_type.into_nullable_field_ref()))
511 }
512}