datafusion_physical_plan/tree_node.rs
1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements. See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership. The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License. You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied. See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18//! This module provides common traits for visiting or rewriting tree nodes easily.
19
20use std::fmt::{self, Display, Formatter};
21use std::sync::Arc;
22
23use crate::execution_plan::replace_children_if_necessary;
24use crate::{ExecutionPlan, displayable};
25
26use datafusion_common::Result;
27use datafusion_common::tree_node::{ConcreteTreeNode, DynTreeNode};
28
29impl DynTreeNode for dyn ExecutionPlan {
30 fn arc_children(&self) -> Vec<&Arc<Self>> {
31 self.children()
32 }
33
34 fn with_new_arc_children(
35 &self,
36 arc_self: Arc<Self>,
37 new_children: Vec<Arc<Self>>,
38 ) -> Result<Arc<Self>> {
39 replace_children_if_necessary(arc_self, new_children)
40 }
41}
42
43/// A node context object beneficial for writing optimizer rules.
44/// This context encapsulating an [`ExecutionPlan`] node with a payload.
45///
46/// Since each wrapped node has it's children within both the `PlanContext.plan.children()`,
47/// as well as separately within the `PlanContext.children` (which are child nodes wrapped in the context),
48/// it's important to keep these child plans in sync when performing mutations.
49///
50/// Since there are two ways to access child plans directly -— it's recommended
51/// to perform mutable operations via [`Self::update_plan_from_children`].
52/// After mutating the `PlanContext.children`, or after creating the `PlanContext`,
53/// call `update_plan_from_children` to sync.
54#[derive(Debug)]
55pub struct PlanContext<T: Sized> {
56 /// The execution plan associated with this context.
57 pub plan: Arc<dyn ExecutionPlan>,
58 /// Custom data payload of the node.
59 pub data: T,
60 /// Child contexts of this node.
61 pub children: Vec<Self>,
62}
63
64impl<T> PlanContext<T> {
65 pub fn new(plan: Arc<dyn ExecutionPlan>, data: T, children: Vec<Self>) -> Self {
66 Self {
67 plan,
68 data,
69 children,
70 }
71 }
72
73 /// Update the `PlanContext.plan.children()` from the `PlanContext.children`,
74 /// if the `PlanContext.children` have been changed.
75 pub fn update_plan_from_children(mut self) -> Result<Self> {
76 let children_plans = self.children.iter().map(|c| Arc::clone(&c.plan)).collect();
77 self.plan = replace_children_if_necessary(self.plan, children_plans)?;
78
79 Ok(self)
80 }
81}
82
83impl<T: Default> PlanContext<T> {
84 pub fn new_default(plan: Arc<dyn ExecutionPlan>) -> Self {
85 let children = plan
86 .children()
87 .into_iter()
88 .cloned()
89 .map(Self::new_default)
90 .collect();
91 Self::new(plan, Default::default(), children)
92 }
93}
94
95impl<T: Display> Display for PlanContext<T> {
96 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
97 let node_string = displayable(self.plan.as_ref()).one_line();
98 write!(f, "Node plan: {node_string}")?;
99 write!(f, "Node data: {}", self.data)?;
100 write!(f, "")
101 }
102}
103
104impl<T> ConcreteTreeNode for PlanContext<T> {
105 fn children(&self) -> &[Self] {
106 &self.children
107 }
108
109 fn take_children(mut self) -> (Self, Vec<Self>) {
110 let children = std::mem::take(&mut self.children);
111 (self, children)
112 }
113
114 fn with_new_children(mut self, children: Vec<Self>) -> Result<Self> {
115 self.children = children;
116 self.update_plan_from_children()
117 }
118}