datafusion_expr/logical_plan/extension.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//! This module defines the interface for logical nodes
6use crate::{Expr, LogicalPlan};
7use datafusion_common::{DFSchema, DFSchemaRef, Result};
8use std::cmp::Ordering;
9use std::hash::{Hash, Hasher};
10use std::{any::Any, collections::HashSet, fmt, sync::Arc};
11
12use super::InvariantLevel;
13
14/// This defines the interface for [`LogicalPlan`] nodes that can be
15/// used to extend DataFusion with custom relational operators.
16///
17/// The [`UserDefinedLogicalNodeCore`] trait is *the recommended way to implement*
18/// this trait and avoids having implementing some required boiler plate code.
19pub trait UserDefinedLogicalNode: fmt::Debug + Send + Sync {
20 /// Return a reference to self as Any, to support dynamic downcasting
21 ///
22 /// Typically this will look like:
23 ///
24 /// ```
25 /// # use std::any::Any;
26 /// # struct Dummy { }
27 ///
28 /// # impl Dummy {
29 /// // canonical boiler plate
30 /// fn as_any(&self) -> &dyn Any {
31 /// self
32 /// }
33 /// # }
34 /// ```
35 fn as_any(&self) -> &dyn Any;
36
37 /// Return the plan's name.
38 fn name(&self) -> &str;
39
40 /// Return the logical plan's inputs.
41 fn inputs(&self) -> Vec<&LogicalPlan>;
42
43 /// Return the output schema of this logical plan node.
44 fn schema(&self) -> &DFSchemaRef;
45
46 /// Perform check of invariants for the extension node.
47 fn check_invariants(&self, check: InvariantLevel) -> Result<()>;
48
49 /// Returns all expressions in the current logical plan node. This should
50 /// not include expressions of any inputs (aka non-recursively).
51 ///
52 /// These expressions are used for optimizer
53 /// passes and rewrites. See [`LogicalPlan::expressions`] for more details.
54 fn expressions(&self) -> Vec<Expr>;
55
56 /// A list of output columns (e.g. the names of columns in
57 /// self.schema()) for which predicates can not be pushed below
58 /// this node without changing the output.
59 ///
60 /// By default, this returns all columns and thus prevents any
61 /// predicates from being pushed below this node.
62 fn prevent_predicate_push_down_columns(&self) -> HashSet<String> {
63 // default (safe) is all columns in the schema.
64 get_all_columns_from_schema(self.schema())
65 }
66
67 /// Write a single line, human readable string to `f` for use in explain plan.
68 ///
69 /// For example: `TopK: k=10`
70 fn fmt_for_explain(&self, f: &mut fmt::Formatter) -> fmt::Result;
71
72 /// Create a new `UserDefinedLogicalNode` with the specified children
73 /// and expressions. This function is used during optimization
74 /// when the plan is being rewritten and a new instance of the
75 /// `UserDefinedLogicalNode` must be created.
76 ///
77 /// Note that exprs and inputs are in the same order as the result
78 /// of self.inputs and self.exprs.
79 ///
80 /// So, `self.with_exprs_and_inputs(exprs, ..).expressions() == exprs
81 fn with_exprs_and_inputs(
82 &self,
83 exprs: Vec<Expr>,
84 inputs: Vec<LogicalPlan>,
85 ) -> Result<Arc<dyn UserDefinedLogicalNode>>;
86
87 /// Returns the necessary input columns for this node required to compute
88 /// the columns in the output schema
89 ///
90 /// This is used for projection push-down when DataFusion has determined that
91 /// only a subset of the output columns of this node are needed by its parents.
92 /// This API is used to tell DataFusion which, if any, of the input columns are no longer
93 /// needed.
94 ///
95 /// Return `None`, the default, if this information can not be determined.
96 /// Returns `Some(_)` with the column indices for each child of this node that are
97 /// needed to compute `output_columns`
98 fn necessary_children_exprs(
99 &self,
100 _output_columns: &[usize],
101 ) -> Option<Vec<Vec<usize>>> {
102 None
103 }
104
105 /// Update the hash `state` with this node requirements from
106 /// [`Hash`].
107 ///
108 /// Note: consider using [`UserDefinedLogicalNodeCore`] instead of
109 /// [`UserDefinedLogicalNode`] directly.
110 ///
111 /// This method is required to support hashing [`LogicalPlan`]s. To
112 /// implement it, typically the type implementing
113 /// [`UserDefinedLogicalNode`] typically implements [`Hash`] and
114 /// then the following boiler plate is used:
115 ///
116 /// # Example:
117 /// ```
118 /// // User defined node that derives Hash
119 /// #[derive(Hash, Debug, PartialEq, Eq)]
120 /// struct MyNode {
121 /// val: u64,
122 /// }
123 ///
124 /// // impl UserDefinedLogicalNode {
125 /// // ...
126 /// # impl MyNode {
127 /// // Boiler plate to call the derived Hash impl
128 /// fn dyn_hash(&self, state: &mut dyn std::hash::Hasher) {
129 /// use std::hash::Hash;
130 /// let mut s = state;
131 /// self.hash(&mut s);
132 /// }
133 /// // }
134 /// # }
135 /// ```
136 /// Note: [`UserDefinedLogicalNode`] is not constrained by [`Hash`]
137 /// directly because it must remain object safe.
138 fn dyn_hash(&self, state: &mut dyn Hasher);
139
140 /// Compare `other`, respecting requirements from [Eq].
141 ///
142 /// Note: consider using [`UserDefinedLogicalNodeCore`] instead of
143 /// [`UserDefinedLogicalNode`] directly.
144 ///
145 /// When `other` has an another type than `self`, then the values
146 /// are *not* equal.
147 ///
148 /// This method is required to support Eq on [`LogicalPlan`]s. To
149 /// implement it, typically the type implementing
150 /// [`UserDefinedLogicalNode`] typically implements [`Eq`] and
151 /// then the following boiler plate is used:
152 ///
153 /// # Example:
154 /// ```
155 /// # use datafusion_expr::UserDefinedLogicalNode;
156 /// // User defined node that derives Eq
157 /// #[derive(Hash, Debug, PartialEq, Eq)]
158 /// struct MyNode {
159 /// val: u64,
160 /// }
161 ///
162 /// // impl UserDefinedLogicalNode {
163 /// // ...
164 /// # impl MyNode {
165 /// // Boiler plate to call the derived Eq impl
166 /// fn dyn_eq(&self, other: &dyn UserDefinedLogicalNode) -> bool {
167 /// match other.as_any().downcast_ref::<Self>() {
168 /// Some(o) => self == o,
169 /// None => false,
170 /// }
171 /// }
172 /// // }
173 /// # }
174 /// ```
175 /// Note: [`UserDefinedLogicalNode`] is not constrained by [`Eq`]
176 /// directly because it must remain object safe.
177 fn dyn_eq(&self, other: &dyn UserDefinedLogicalNode) -> bool;
178
179 /// Compare `other`, respecting requirements from [PartialOrd].
180 /// Must return `Some(Equal)` if and only if `self.dyn_eq(other)`.
181 fn dyn_ord(&self, other: &dyn UserDefinedLogicalNode) -> Option<Ordering>;
182
183 /// Returns `true` if a limit can be safely pushed down through this
184 /// `UserDefinedLogicalNode` node.
185 ///
186 /// If this method returns `true`, and the query plan contains a limit at
187 /// the output of this node, DataFusion will push the limit to the input
188 /// of this node.
189 fn supports_limit_pushdown(&self) -> bool {
190 false
191 }
192}
193
194impl Hash for dyn UserDefinedLogicalNode {
195 fn hash<H: Hasher>(&self, state: &mut H) {
196 self.dyn_hash(state);
197 }
198}
199
200impl PartialEq for dyn UserDefinedLogicalNode {
201 fn eq(&self, other: &Self) -> bool {
202 self.dyn_eq(other)
203 }
204}
205
206impl PartialOrd for dyn UserDefinedLogicalNode {
207 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
208 self.dyn_ord(other)
209 }
210}
211
212impl Eq for dyn UserDefinedLogicalNode {}
213
214/// This trait facilitates implementation of the [`UserDefinedLogicalNode`].
215///
216/// See the example in
217/// [user_defined_plan.rs](https://github.com/apache/datafusion/blob/main/datafusion/core/tests/user_defined/user_defined_plan.rs)
218/// file for an example of how to use this extension API.
219pub trait UserDefinedLogicalNodeCore:
220 fmt::Debug + Eq + PartialOrd + Hash + Sized + Send + Sync + 'static
221{
222 /// Return the plan's name.
223 fn name(&self) -> &str;
224
225 /// Return the logical plan's inputs.
226 fn inputs(&self) -> Vec<&LogicalPlan>;
227
228 /// Return the output schema of this logical plan node.
229 fn schema(&self) -> &DFSchemaRef;
230
231 /// Perform check of invariants for the extension node.
232 ///
233 /// This is the default implementation for extension nodes.
234 fn check_invariants(&self, _check: InvariantLevel) -> Result<()> {
235 Ok(())
236 }
237
238 /// Returns all expressions in the current logical plan node. This
239 /// should not include expressions of any inputs (aka
240 /// non-recursively). These expressions are used for optimizer
241 /// passes and rewrites.
242 fn expressions(&self) -> Vec<Expr>;
243
244 /// A list of output columns (e.g. the names of columns in
245 /// self.schema()) for which predicates can not be pushed below
246 /// this node without changing the output.
247 ///
248 /// By default, this returns all columns and thus prevents any
249 /// predicates from being pushed below this node.
250 fn prevent_predicate_push_down_columns(&self) -> HashSet<String> {
251 // default (safe) is all columns in the schema.
252 get_all_columns_from_schema(self.schema())
253 }
254
255 /// Write a single line, human readable string to `f` for use in explain plan.
256 ///
257 /// For example: `TopK: k=10`
258 fn fmt_for_explain(&self, f: &mut fmt::Formatter) -> fmt::Result;
259
260 /// Create a new `UserDefinedLogicalNode` with the specified children
261 /// and expressions. This function is used during optimization
262 /// when the plan is being rewritten and a new instance of the
263 /// `UserDefinedLogicalNode` must be created.
264 ///
265 /// Note that exprs and inputs are in the same order as the result
266 /// of self.inputs and self.exprs.
267 ///
268 /// So, `self.with_exprs_and_inputs(exprs, ..).expressions() == exprs
269 fn with_exprs_and_inputs(
270 &self,
271 exprs: Vec<Expr>,
272 inputs: Vec<LogicalPlan>,
273 ) -> Result<Self>;
274
275 /// Returns the necessary input columns for this node required to compute
276 /// the columns in the output schema
277 ///
278 /// This is used for projection push-down when DataFusion has determined that
279 /// only a subset of the output columns of this node are needed by its parents.
280 /// This API is used to tell DataFusion which, if any, of the input columns are no longer
281 /// needed.
282 ///
283 /// Return `None`, the default, if this information can not be determined.
284 /// Returns `Some(_)` with the column indices for each child of this node that are
285 /// needed to compute `output_columns`
286 fn necessary_children_exprs(
287 &self,
288 _output_columns: &[usize],
289 ) -> Option<Vec<Vec<usize>>> {
290 None
291 }
292
293 /// Returns `true` if a limit can be safely pushed down through this
294 /// `UserDefinedLogicalNode` node.
295 ///
296 /// If this method returns `true`, and the query plan contains a limit at
297 /// the output of this node, DataFusion will push the limit to the input
298 /// of this node.
299 fn supports_limit_pushdown(&self) -> bool {
300 false // Disallow limit push-down by default
301 }
302}
303
304/// Automatically derive `UserDefinedLogicalNode` from `UserDefinedLogicalNodeCore`
305/// to avoid boiler plate for implementing `as_any`, `Hash`, `PartialEq` and `PartialOrd`.
306impl<T: UserDefinedLogicalNodeCore> UserDefinedLogicalNode for T {
307 fn as_any(&self) -> &dyn Any {
308 self
309 }
310
311 fn name(&self) -> &str {
312 self.name()
313 }
314
315 fn inputs(&self) -> Vec<&LogicalPlan> {
316 self.inputs()
317 }
318
319 fn schema(&self) -> &DFSchemaRef {
320 self.schema()
321 }
322
323 fn check_invariants(&self, check: InvariantLevel) -> Result<()> {
324 self.check_invariants(check)
325 }
326
327 fn expressions(&self) -> Vec<Expr> {
328 self.expressions()
329 }
330
331 fn prevent_predicate_push_down_columns(&self) -> HashSet<String> {
332 self.prevent_predicate_push_down_columns()
333 }
334
335 fn fmt_for_explain(&self, f: &mut fmt::Formatter) -> fmt::Result {
336 self.fmt_for_explain(f)
337 }
338
339 fn with_exprs_and_inputs(
340 &self,
341 exprs: Vec<Expr>,
342 inputs: Vec<LogicalPlan>,
343 ) -> Result<Arc<dyn UserDefinedLogicalNode>> {
344 Ok(Arc::new(self.with_exprs_and_inputs(exprs, inputs)?))
345 }
346
347 fn necessary_children_exprs(
348 &self,
349 output_columns: &[usize],
350 ) -> Option<Vec<Vec<usize>>> {
351 self.necessary_children_exprs(output_columns)
352 }
353
354 fn dyn_hash(&self, state: &mut dyn Hasher) {
355 let mut s = state;
356 self.hash(&mut s);
357 }
358
359 fn dyn_eq(&self, other: &dyn UserDefinedLogicalNode) -> bool {
360 match other.as_any().downcast_ref::<Self>() {
361 Some(o) => self == o,
362 None => false,
363 }
364 }
365
366 fn dyn_ord(&self, other: &dyn UserDefinedLogicalNode) -> Option<Ordering> {
367 other
368 .as_any()
369 .downcast_ref::<Self>()
370 .and_then(|other| self.partial_cmp(other))
371 }
372
373 fn supports_limit_pushdown(&self) -> bool {
374 self.supports_limit_pushdown()
375 }
376}
377
378fn get_all_columns_from_schema(schema: &DFSchema) -> HashSet<String> {
379 schema.fields().iter().map(|f| f.name().clone()).collect()
380}