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::{displayable, with_new_children_if_necessary, ExecutionPlan};
24
25use datafusion_common::tree_node::{ConcreteTreeNode, DynTreeNode};
26use datafusion_common::Result;
27
28impl DynTreeNode for dyn ExecutionPlan {
29    fn arc_children(&self) -> Vec<&Arc<Self>> {
30        self.children()
31    }
32
33    fn with_new_arc_children(
34        &self,
35        arc_self: Arc<Self>,
36        new_children: Vec<Arc<Self>>,
37    ) -> Result<Arc<Self>> {
38        with_new_children_if_necessary(arc_self, new_children)
39    }
40}
41
42/// A node context object beneficial for writing optimizer rules.
43/// This context encapsulating an [`ExecutionPlan`] node with a payload.
44///
45/// Since each wrapped node has it's children within both the [`PlanContext.plan.children()`],
46/// as well as separately within the [`PlanContext.children`] (which are child nodes wrapped in the context),
47/// it's important to keep these child plans in sync when performing mutations.
48///
49/// Since there are two ways to access child plans directly -— it's recommended
50/// to perform mutable operations via [`Self::update_plan_from_children`].
51/// After mutating the `PlanContext.children`, or after creating the `PlanContext`,
52/// call `update_plan_from_children` to sync.
53#[derive(Debug)]
54pub struct PlanContext<T: Sized> {
55    /// The execution plan associated with this context.
56    pub plan: Arc<dyn ExecutionPlan>,
57    /// Custom data payload of the node.
58    pub data: T,
59    /// Child contexts of this node.
60    pub children: Vec<Self>,
61}
62
63impl<T> PlanContext<T> {
64    pub fn new(plan: Arc<dyn ExecutionPlan>, data: T, children: Vec<Self>) -> Self {
65        Self {
66            plan,
67            data,
68            children,
69        }
70    }
71
72    /// Update the [`PlanContext.plan.children()`] from the [`PlanContext.children`],
73    /// if the `PlanContext.children` have been changed.
74    pub fn update_plan_from_children(mut self) -> Result<Self> {
75        let children_plans = self.children.iter().map(|c| Arc::clone(&c.plan)).collect();
76        self.plan = with_new_children_if_necessary(self.plan, children_plans)?;
77
78        Ok(self)
79    }
80}
81
82impl<T: Default> PlanContext<T> {
83    pub fn new_default(plan: Arc<dyn ExecutionPlan>) -> Self {
84        let children = plan
85            .children()
86            .into_iter()
87            .cloned()
88            .map(Self::new_default)
89            .collect();
90        Self::new(plan, Default::default(), children)
91    }
92}
93
94impl<T: Display> Display for PlanContext<T> {
95    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
96        let node_string = displayable(self.plan.as_ref()).one_line();
97        write!(f, "Node plan: {}", node_string)?;
98        write!(f, "Node data: {}", self.data)?;
99        write!(f, "")
100    }
101}
102
103impl<T> ConcreteTreeNode for PlanContext<T> {
104    fn children(&self) -> &[Self] {
105        &self.children
106    }
107
108    fn take_children(mut self) -> (Self, Vec<Self>) {
109        let children = std::mem::take(&mut self.children);
110        (self, children)
111    }
112
113    fn with_new_children(mut self, children: Vec<Self>) -> Result<Self> {
114        self.children = children;
115        self.update_plan_from_children()
116    }
117}