Skip to main content

hawdb_plan_cypher/physical/
metadata.rs

1// Copyright 2026 Nowledge
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Physical optimizer operator metadata.
16
17use std::collections::BTreeMap;
18use std::str::FromStr;
19
20/// A plan-local physical operator identity assigned in pre-order.
21///
22/// The identity is stable for one physical plan shape and lets planning and
23/// execution diagnostics correlate repeated operators without relying on
24/// operator names or process-local addresses.
25#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
26pub struct PhysicalOperatorId(usize);
27
28impl PhysicalOperatorId {
29    /// Creates an identity from its pre-order position in the physical plan.
30    pub const fn from_ordinal(ordinal: usize) -> Self {
31        Self(ordinal)
32    }
33
34    /// Returns the operator's zero-based pre-order position.
35    pub const fn ordinal(self) -> usize {
36        self.0
37    }
38}
39
40#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
41pub enum PhysicalPlanKind {
42    CreateNodeLabel,
43    CreateRelationshipType,
44    CreateNodeTable,
45    CreateRelationshipTable,
46    CreateProperty,
47    AlterTableState,
48    AlterPropertyState,
49    CreateIndex,
50    CreateCompositeIndex,
51    CreateRangeIndex,
52    CreateFullTextIndex,
53    CreateUniqueConstraint,
54    CreateNodePropertyExistsConstraint,
55    CreateRelationshipUniqueConstraint,
56    CreateRelationshipPropertyExistsConstraint,
57    ProjectGraph,
58    GraphAlgorithm,
59    VectorSeedScan,
60    TextSeedScan,
61    GraphSeedScan,
62    VectorIndexScan,
63    CreateNode,
64    UnwindExec,
65    UnwindRowsExec,
66    UnwindMutationExec,
67    LoadCsvMutationExec,
68    MergeNode,
69    MergeRelationship,
70    MergeMatchedRelationship,
71    MergeRelationshipFromMatchedRelationship,
72    MergeRelationshipToMatchedTarget,
73    MergeRelationshipFromMatchedTarget,
74    CreateMatchedRelationship,
75    SetNodeProperty,
76    SetNodeProperties,
77    SetNodePropertiesReturn,
78    MatchSetExec,
79    MutationReturn,
80    SetRelationshipProperty,
81    SetRelationshipProperties,
82    DeleteNode,
83    DeleteRelationship,
84    DeleteRelationshipTargetNodes,
85    CreateRelationship,
86    GraphMatchExec,
87    EmptyExec,
88    LoadCsvExec,
89    SeqNodeScan,
90    RelationshipSeededNodeScan,
91    NodeProjectionScanExec,
92    SourceSegmentScan,
93    NodeCartesianProductExec,
94    HashJoinExec,
95    NodeColumnLookupExec,
96    IndexNodeSeek,
97    IndexNodeMultiSeek,
98    IndexNodeUnionSeek,
99    IndexNodeCompositeSeek,
100    IndexNodeCompositeRangeSeek,
101    IndexNodeRangeSeek,
102    IndexNodeTextSeek,
103    AdjacencyExpandExec,
104    AdjacencyExistsExec,
105    OptionalDegreeExec,
106    OptionalRelationshipCountSumExec,
107    NodeCountExec,
108    RelationshipCountExec,
109    ThreadRepairStatsExec,
110    ShortestPathExec,
111    FilterExec,
112    ProjectExec,
113    AggregateExec,
114    DistinctExec,
115    SortExec,
116    TopNExec,
117    LimitExec,
118    ScoringRerankExec,
119    ScoringProgramExec,
120    HostScoringExec,
121}
122
123#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
124pub enum PhysicalPlanClass {
125    Schema,
126    Mutation,
127    Access,
128    Traversal,
129    Relational,
130    Procedure,
131}
132
133#[derive(Debug, Clone, Copy, PartialEq)]
134pub enum PlanChildren<'a, P> {
135    None,
136    Unary(&'a P),
137    Binary(&'a P, &'a P),
138}
139
140pub trait PhysicalPlanNode {
141    fn kind(&self) -> PhysicalPlanKind;
142
143    fn children(&self) -> PlanChildren<'_, Self>
144    where
145        Self: Sized;
146
147    fn class(&self) -> PhysicalPlanClass {
148        self.kind().class()
149    }
150}
151
152impl PhysicalPlanKind {
153    pub fn all() -> &'static [Self] {
154        const ALL: &[PhysicalPlanKind] = &[
155            PhysicalPlanKind::CreateNodeLabel,
156            PhysicalPlanKind::CreateRelationshipType,
157            PhysicalPlanKind::CreateNodeTable,
158            PhysicalPlanKind::CreateRelationshipTable,
159            PhysicalPlanKind::CreateProperty,
160            PhysicalPlanKind::AlterTableState,
161            PhysicalPlanKind::AlterPropertyState,
162            PhysicalPlanKind::CreateIndex,
163            PhysicalPlanKind::CreateCompositeIndex,
164            PhysicalPlanKind::CreateRangeIndex,
165            PhysicalPlanKind::CreateFullTextIndex,
166            PhysicalPlanKind::CreateUniqueConstraint,
167            PhysicalPlanKind::CreateNodePropertyExistsConstraint,
168            PhysicalPlanKind::CreateRelationshipUniqueConstraint,
169            PhysicalPlanKind::CreateRelationshipPropertyExistsConstraint,
170            PhysicalPlanKind::ProjectGraph,
171            PhysicalPlanKind::GraphAlgorithm,
172            PhysicalPlanKind::VectorSeedScan,
173            PhysicalPlanKind::TextSeedScan,
174            PhysicalPlanKind::GraphSeedScan,
175            PhysicalPlanKind::VectorIndexScan,
176            PhysicalPlanKind::CreateNode,
177            PhysicalPlanKind::UnwindExec,
178            PhysicalPlanKind::UnwindRowsExec,
179            PhysicalPlanKind::UnwindMutationExec,
180            PhysicalPlanKind::LoadCsvMutationExec,
181            PhysicalPlanKind::MergeNode,
182            PhysicalPlanKind::MergeRelationship,
183            PhysicalPlanKind::MergeMatchedRelationship,
184            PhysicalPlanKind::MergeRelationshipFromMatchedRelationship,
185            PhysicalPlanKind::MergeRelationshipToMatchedTarget,
186            PhysicalPlanKind::MergeRelationshipFromMatchedTarget,
187            PhysicalPlanKind::CreateMatchedRelationship,
188            PhysicalPlanKind::SetNodeProperty,
189            PhysicalPlanKind::SetNodeProperties,
190            PhysicalPlanKind::SetNodePropertiesReturn,
191            PhysicalPlanKind::MatchSetExec,
192            PhysicalPlanKind::MutationReturn,
193            PhysicalPlanKind::SetRelationshipProperty,
194            PhysicalPlanKind::SetRelationshipProperties,
195            PhysicalPlanKind::DeleteNode,
196            PhysicalPlanKind::DeleteRelationship,
197            PhysicalPlanKind::DeleteRelationshipTargetNodes,
198            PhysicalPlanKind::CreateRelationship,
199            PhysicalPlanKind::GraphMatchExec,
200            PhysicalPlanKind::EmptyExec,
201            PhysicalPlanKind::LoadCsvExec,
202            PhysicalPlanKind::SeqNodeScan,
203            PhysicalPlanKind::RelationshipSeededNodeScan,
204            PhysicalPlanKind::NodeProjectionScanExec,
205            PhysicalPlanKind::SourceSegmentScan,
206            PhysicalPlanKind::NodeCartesianProductExec,
207            PhysicalPlanKind::HashJoinExec,
208            PhysicalPlanKind::NodeColumnLookupExec,
209            PhysicalPlanKind::IndexNodeSeek,
210            PhysicalPlanKind::IndexNodeMultiSeek,
211            PhysicalPlanKind::IndexNodeUnionSeek,
212            PhysicalPlanKind::IndexNodeCompositeSeek,
213            PhysicalPlanKind::IndexNodeCompositeRangeSeek,
214            PhysicalPlanKind::IndexNodeRangeSeek,
215            PhysicalPlanKind::IndexNodeTextSeek,
216            PhysicalPlanKind::AdjacencyExpandExec,
217            PhysicalPlanKind::AdjacencyExistsExec,
218            PhysicalPlanKind::OptionalDegreeExec,
219            PhysicalPlanKind::OptionalRelationshipCountSumExec,
220            PhysicalPlanKind::NodeCountExec,
221            PhysicalPlanKind::RelationshipCountExec,
222            PhysicalPlanKind::ThreadRepairStatsExec,
223            PhysicalPlanKind::ShortestPathExec,
224            PhysicalPlanKind::FilterExec,
225            PhysicalPlanKind::ProjectExec,
226            PhysicalPlanKind::AggregateExec,
227            PhysicalPlanKind::DistinctExec,
228            PhysicalPlanKind::SortExec,
229            PhysicalPlanKind::TopNExec,
230            PhysicalPlanKind::LimitExec,
231            PhysicalPlanKind::ScoringRerankExec,
232            PhysicalPlanKind::ScoringProgramExec,
233            PhysicalPlanKind::HostScoringExec,
234        ];
235        ALL
236    }
237
238    pub fn as_str(self) -> &'static str {
239        match self {
240            PhysicalPlanKind::CreateNodeLabel => "CreateNodeLabel",
241            PhysicalPlanKind::CreateRelationshipType => "CreateRelationshipType",
242            PhysicalPlanKind::CreateNodeTable => "CreateNodeTable",
243            PhysicalPlanKind::CreateRelationshipTable => "CreateRelationshipTable",
244            PhysicalPlanKind::CreateProperty => "CreateProperty",
245            PhysicalPlanKind::AlterTableState => "AlterTableState",
246            PhysicalPlanKind::AlterPropertyState => "AlterPropertyState",
247            PhysicalPlanKind::CreateIndex => "CreateIndex",
248            PhysicalPlanKind::CreateCompositeIndex => "CreateCompositeIndex",
249            PhysicalPlanKind::CreateRangeIndex => "CreateRangeIndex",
250            PhysicalPlanKind::CreateFullTextIndex => "CreateFullTextIndex",
251            PhysicalPlanKind::CreateUniqueConstraint => "CreateUniqueConstraint",
252            PhysicalPlanKind::CreateNodePropertyExistsConstraint => {
253                "CreateNodePropertyExistsConstraint"
254            }
255            PhysicalPlanKind::CreateRelationshipUniqueConstraint => {
256                "CreateRelationshipUniqueConstraint"
257            }
258            PhysicalPlanKind::CreateRelationshipPropertyExistsConstraint => {
259                "CreateRelationshipPropertyExistsConstraint"
260            }
261            PhysicalPlanKind::ProjectGraph => "ProjectGraph",
262            PhysicalPlanKind::GraphAlgorithm => "GraphAlgorithm",
263            PhysicalPlanKind::VectorSeedScan => "VectorSeedScan",
264            PhysicalPlanKind::TextSeedScan => "TextSeedScan",
265            PhysicalPlanKind::GraphSeedScan => "GraphSeedScan",
266            PhysicalPlanKind::VectorIndexScan => "VectorIndexScan",
267            PhysicalPlanKind::CreateNode => "CreateNode",
268            PhysicalPlanKind::UnwindExec => "UnwindExec",
269            PhysicalPlanKind::UnwindRowsExec => "UnwindRowsExec",
270            PhysicalPlanKind::UnwindMutationExec => "UnwindMutationExec",
271            PhysicalPlanKind::LoadCsvMutationExec => "LoadCsvMutationExec",
272            PhysicalPlanKind::MergeNode => "MergeNode",
273            PhysicalPlanKind::MergeRelationship => "MergeRelationship",
274            PhysicalPlanKind::MergeMatchedRelationship => "MergeMatchedRelationship",
275            PhysicalPlanKind::MergeRelationshipFromMatchedRelationship => {
276                "MergeRelationshipFromMatchedRelationship"
277            }
278            PhysicalPlanKind::MergeRelationshipToMatchedTarget => {
279                "MergeRelationshipToMatchedTarget"
280            }
281            PhysicalPlanKind::MergeRelationshipFromMatchedTarget => {
282                "MergeRelationshipFromMatchedTarget"
283            }
284            PhysicalPlanKind::CreateMatchedRelationship => "CreateMatchedRelationship",
285            PhysicalPlanKind::SetNodeProperty => "SetNodeProperty",
286            PhysicalPlanKind::SetNodeProperties => "SetNodeProperties",
287            PhysicalPlanKind::SetNodePropertiesReturn => "SetNodePropertiesReturn",
288            PhysicalPlanKind::MatchSetExec => "MatchSetExec",
289            PhysicalPlanKind::MutationReturn => "MutationReturn",
290            PhysicalPlanKind::SetRelationshipProperty => "SetRelationshipProperty",
291            PhysicalPlanKind::SetRelationshipProperties => "SetRelationshipProperties",
292            PhysicalPlanKind::DeleteNode => "DeleteNode",
293            PhysicalPlanKind::DeleteRelationship => "DeleteRelationship",
294            PhysicalPlanKind::DeleteRelationshipTargetNodes => "DeleteRelationshipTargetNodes",
295            PhysicalPlanKind::CreateRelationship => "CreateRelationship",
296            PhysicalPlanKind::GraphMatchExec => "GraphMatchExec",
297            PhysicalPlanKind::EmptyExec => "EmptyExec",
298            PhysicalPlanKind::LoadCsvExec => "LoadCsvExec",
299            PhysicalPlanKind::SeqNodeScan => "SeqNodeScan",
300            PhysicalPlanKind::RelationshipSeededNodeScan => "RelationshipSeededNodeScan",
301            PhysicalPlanKind::NodeProjectionScanExec => "NodeProjectionScanExec",
302            PhysicalPlanKind::SourceSegmentScan => "SourceSegmentScan",
303            PhysicalPlanKind::HashJoinExec => "HashJoinExec",
304            PhysicalPlanKind::NodeCartesianProductExec => "NodeCartesianProductExec",
305            PhysicalPlanKind::NodeColumnLookupExec => "NodeColumnLookupExec",
306            PhysicalPlanKind::IndexNodeSeek => "IndexNodeSeek",
307            PhysicalPlanKind::IndexNodeMultiSeek => "IndexNodeMultiSeek",
308            PhysicalPlanKind::IndexNodeUnionSeek => "IndexNodeUnionSeek",
309            PhysicalPlanKind::IndexNodeCompositeSeek => "IndexNodeCompositeSeek",
310            PhysicalPlanKind::IndexNodeCompositeRangeSeek => "IndexNodeCompositeRangeSeek",
311            PhysicalPlanKind::IndexNodeRangeSeek => "IndexNodeRangeSeek",
312            PhysicalPlanKind::IndexNodeTextSeek => "IndexNodeTextSeek",
313            PhysicalPlanKind::AdjacencyExpandExec => "AdjacencyExpandExec",
314            PhysicalPlanKind::AdjacencyExistsExec => "AdjacencyExistsExec",
315            PhysicalPlanKind::OptionalDegreeExec => "OptionalDegreeExec",
316            PhysicalPlanKind::OptionalRelationshipCountSumExec => {
317                "OptionalRelationshipCountSumExec"
318            }
319            PhysicalPlanKind::NodeCountExec => "NodeCountExec",
320            PhysicalPlanKind::RelationshipCountExec => "RelationshipCountExec",
321            PhysicalPlanKind::ThreadRepairStatsExec => "ThreadRepairStatsExec",
322            PhysicalPlanKind::ShortestPathExec => "ShortestPathExec",
323            PhysicalPlanKind::FilterExec => "FilterExec",
324            PhysicalPlanKind::ProjectExec => "ProjectExec",
325            PhysicalPlanKind::AggregateExec => "AggregateExec",
326            PhysicalPlanKind::DistinctExec => "DistinctExec",
327            PhysicalPlanKind::SortExec => "SortExec",
328            PhysicalPlanKind::TopNExec => "TopNExec",
329            PhysicalPlanKind::LimitExec => "LimitExec",
330            PhysicalPlanKind::ScoringRerankExec => "ScoringRerankExec",
331            PhysicalPlanKind::ScoringProgramExec => "ScoringProgramExec",
332            PhysicalPlanKind::HostScoringExec => "HostScoringExec",
333        }
334    }
335
336    pub fn class(self) -> PhysicalPlanClass {
337        match self {
338            PhysicalPlanKind::CreateNodeLabel
339            | PhysicalPlanKind::CreateRelationshipType
340            | PhysicalPlanKind::CreateNodeTable
341            | PhysicalPlanKind::CreateRelationshipTable
342            | PhysicalPlanKind::CreateProperty
343            | PhysicalPlanKind::AlterTableState
344            | PhysicalPlanKind::AlterPropertyState
345            | PhysicalPlanKind::CreateIndex
346            | PhysicalPlanKind::CreateCompositeIndex
347            | PhysicalPlanKind::CreateRangeIndex
348            | PhysicalPlanKind::CreateFullTextIndex
349            | PhysicalPlanKind::CreateUniqueConstraint
350            | PhysicalPlanKind::CreateNodePropertyExistsConstraint
351            | PhysicalPlanKind::CreateRelationshipUniqueConstraint
352            | PhysicalPlanKind::CreateRelationshipPropertyExistsConstraint => {
353                PhysicalPlanClass::Schema
354            }
355            PhysicalPlanKind::CreateNode
356            | PhysicalPlanKind::UnwindMutationExec
357            | PhysicalPlanKind::LoadCsvMutationExec
358            | PhysicalPlanKind::MergeNode
359            | PhysicalPlanKind::MergeRelationship
360            | PhysicalPlanKind::MergeMatchedRelationship
361            | PhysicalPlanKind::MergeRelationshipFromMatchedRelationship
362            | PhysicalPlanKind::MergeRelationshipToMatchedTarget
363            | PhysicalPlanKind::MergeRelationshipFromMatchedTarget
364            | PhysicalPlanKind::CreateMatchedRelationship
365            | PhysicalPlanKind::SetNodeProperty
366            | PhysicalPlanKind::SetNodeProperties
367            | PhysicalPlanKind::SetNodePropertiesReturn
368            | PhysicalPlanKind::MatchSetExec
369            | PhysicalPlanKind::MutationReturn
370            | PhysicalPlanKind::SetRelationshipProperty
371            | PhysicalPlanKind::SetRelationshipProperties
372            | PhysicalPlanKind::DeleteNode
373            | PhysicalPlanKind::DeleteRelationship
374            | PhysicalPlanKind::DeleteRelationshipTargetNodes
375            | PhysicalPlanKind::CreateRelationship => PhysicalPlanClass::Mutation,
376            PhysicalPlanKind::SeqNodeScan
377            | PhysicalPlanKind::RelationshipSeededNodeScan
378            | PhysicalPlanKind::NodeProjectionScanExec
379            | PhysicalPlanKind::SourceSegmentScan
380            | PhysicalPlanKind::NodeColumnLookupExec
381            | PhysicalPlanKind::IndexNodeSeek
382            | PhysicalPlanKind::IndexNodeMultiSeek
383            | PhysicalPlanKind::IndexNodeUnionSeek
384            | PhysicalPlanKind::IndexNodeCompositeSeek
385            | PhysicalPlanKind::IndexNodeCompositeRangeSeek
386            | PhysicalPlanKind::IndexNodeRangeSeek
387            | PhysicalPlanKind::IndexNodeTextSeek => PhysicalPlanClass::Access,
388            PhysicalPlanKind::GraphMatchExec
389            | PhysicalPlanKind::AdjacencyExpandExec
390            | PhysicalPlanKind::AdjacencyExistsExec
391            | PhysicalPlanKind::OptionalDegreeExec
392            | PhysicalPlanKind::OptionalRelationshipCountSumExec
393            | PhysicalPlanKind::ShortestPathExec => PhysicalPlanClass::Traversal,
394            PhysicalPlanKind::NodeCountExec
395            | PhysicalPlanKind::RelationshipCountExec
396            | PhysicalPlanKind::UnwindExec
397            | PhysicalPlanKind::UnwindRowsExec
398            | PhysicalPlanKind::EmptyExec
399            | PhysicalPlanKind::NodeCartesianProductExec
400            | PhysicalPlanKind::HashJoinExec
401            | PhysicalPlanKind::FilterExec
402            | PhysicalPlanKind::ProjectExec
403            | PhysicalPlanKind::AggregateExec
404            | PhysicalPlanKind::DistinctExec
405            | PhysicalPlanKind::SortExec
406            | PhysicalPlanKind::TopNExec
407            | PhysicalPlanKind::LimitExec
408            | PhysicalPlanKind::ScoringRerankExec
409            | PhysicalPlanKind::ScoringProgramExec
410            | PhysicalPlanKind::HostScoringExec => PhysicalPlanClass::Relational,
411            PhysicalPlanKind::ProjectGraph
412            | PhysicalPlanKind::GraphAlgorithm
413            | PhysicalPlanKind::VectorSeedScan
414            | PhysicalPlanKind::TextSeedScan
415            | PhysicalPlanKind::GraphSeedScan
416            | PhysicalPlanKind::VectorIndexScan
417            | PhysicalPlanKind::ThreadRepairStatsExec
418            | PhysicalPlanKind::LoadCsvExec => PhysicalPlanClass::Procedure,
419        }
420    }
421}
422
423impl PhysicalPlanClass {
424    pub fn all() -> &'static [Self] {
425        const ALL: &[PhysicalPlanClass] = &[
426            PhysicalPlanClass::Schema,
427            PhysicalPlanClass::Mutation,
428            PhysicalPlanClass::Access,
429            PhysicalPlanClass::Traversal,
430            PhysicalPlanClass::Relational,
431            PhysicalPlanClass::Procedure,
432        ];
433        ALL
434    }
435
436    pub fn as_str(self) -> &'static str {
437        match self {
438            PhysicalPlanClass::Schema => "schema",
439            PhysicalPlanClass::Mutation => "mutation",
440            PhysicalPlanClass::Access => "access",
441            PhysicalPlanClass::Traversal => "traversal",
442            PhysicalPlanClass::Relational => "relational",
443            PhysicalPlanClass::Procedure => "procedure",
444        }
445    }
446}
447
448impl FromStr for PhysicalPlanKind {
449    type Err = &'static str;
450
451    fn from_str(value: &str) -> Result<Self, Self::Err> {
452        Self::all()
453            .iter()
454            .copied()
455            .find(|kind| kind.as_str() == value)
456            .ok_or("unknown physical plan kind")
457    }
458}
459
460impl FromStr for PhysicalPlanClass {
461    type Err = &'static str;
462
463    fn from_str(value: &str) -> Result<Self, Self::Err> {
464        Self::all()
465            .iter()
466            .copied()
467            .find(|class| class.as_str() == value)
468            .ok_or("unknown physical plan class")
469    }
470}
471
472impl<'a, P> PlanChildren<'a, P> {
473    pub fn len(self) -> usize {
474        match self {
475            PlanChildren::None => 0,
476            PlanChildren::Unary(_) => 1,
477            PlanChildren::Binary(_, _) => 2,
478        }
479    }
480
481    pub fn is_empty(self) -> bool {
482        self.len() == 0
483    }
484}
485
486pub fn plan_operator_counts<P>(plan: &P) -> BTreeMap<String, usize>
487where
488    P: PhysicalPlanNode,
489{
490    let mut counts = BTreeMap::new();
491    visit_plan(plan, &mut |node| {
492        *counts.entry(node.kind().as_str().to_string()).or_default() += 1;
493    });
494    counts
495}
496
497pub fn plan_class_counts<P>(plan: &P) -> BTreeMap<String, usize>
498where
499    P: PhysicalPlanNode,
500{
501    let mut counts = BTreeMap::new();
502    visit_plan(plan, &mut |node| {
503        *counts.entry(node.class().as_str().to_string()).or_default() += 1;
504    });
505    counts
506}
507
508pub fn visit_plan<P>(plan: &P, visitor: &mut impl FnMut(&P))
509where
510    P: PhysicalPlanNode,
511{
512    visitor(plan);
513    match plan.children() {
514        PlanChildren::None => {}
515        PlanChildren::Unary(input) => visit_plan(input, visitor),
516        PlanChildren::Binary(left, right) => {
517            visit_plan(left, visitor);
518            visit_plan(right, visitor);
519        }
520    }
521}
522
523/// Visits a physical plan in pre-order and assigns each operator its plan-local identity.
524pub fn visit_plan_with_ids<P>(plan: &P, visitor: &mut impl FnMut(PhysicalOperatorId, &P))
525where
526    P: PhysicalPlanNode,
527{
528    fn visit<P>(
529        plan: &P,
530        next_ordinal: &mut usize,
531        visitor: &mut impl FnMut(PhysicalOperatorId, &P),
532    ) where
533        P: PhysicalPlanNode,
534    {
535        let operator_id = PhysicalOperatorId::from_ordinal(*next_ordinal);
536        *next_ordinal = next_ordinal
537            .checked_add(1)
538            .expect("physical plan operator count exceeds usize");
539        visitor(operator_id, plan);
540        match plan.children() {
541            PlanChildren::None => {}
542            PlanChildren::Unary(input) => visit(input, next_ordinal, visitor),
543            PlanChildren::Binary(left, right) => {
544                visit(left, next_ordinal, visitor);
545                visit(right, next_ordinal, visitor);
546            }
547        }
548    }
549
550    let mut next_ordinal = 0;
551    visit(plan, &mut next_ordinal, visitor);
552}
553
554#[cfg(test)]
555mod tests {
556    use super::{
557        plan_class_counts, plan_operator_counts, visit_plan, visit_plan_with_ids,
558        PhysicalPlanClass, PhysicalPlanKind, PhysicalPlanNode, PlanChildren,
559    };
560
561    #[test]
562    fn physical_plan_kind_exposes_stable_strings_and_classes() {
563        assert_eq!(PhysicalPlanKind::IndexNodeSeek.as_str(), "IndexNodeSeek");
564        assert_eq!(
565            PhysicalPlanKind::IndexNodeSeek.class(),
566            PhysicalPlanClass::Access
567        );
568        assert_eq!(
569            PhysicalPlanKind::AdjacencyExpandExec.class(),
570            PhysicalPlanClass::Traversal
571        );
572        assert_eq!(
573            PhysicalPlanKind::ProjectExec.class(),
574            PhysicalPlanClass::Relational
575        );
576    }
577
578    #[test]
579    fn physical_plan_kind_strings_round_trip_for_diagnostics() {
580        for kind in PhysicalPlanKind::all() {
581            assert_eq!(kind.as_str().parse::<PhysicalPlanKind>(), Ok(*kind));
582        }
583        assert!("UnknownExec".parse::<PhysicalPlanKind>().is_err());
584    }
585
586    #[test]
587    fn physical_plan_class_exposes_stable_strings() {
588        assert_eq!(PhysicalPlanClass::Schema.as_str(), "schema");
589        assert_eq!(PhysicalPlanClass::Mutation.as_str(), "mutation");
590        assert_eq!(PhysicalPlanClass::Access.as_str(), "access");
591        assert_eq!(PhysicalPlanClass::Traversal.as_str(), "traversal");
592        assert_eq!(PhysicalPlanClass::Relational.as_str(), "relational");
593        assert_eq!(PhysicalPlanClass::Procedure.as_str(), "procedure");
594    }
595
596    #[test]
597    fn physical_plan_class_strings_round_trip_for_diagnostics() {
598        for class in PhysicalPlanClass::all() {
599            assert_eq!(class.as_str().parse::<PhysicalPlanClass>(), Ok(*class));
600        }
601        assert!("unknown".parse::<PhysicalPlanClass>().is_err());
602    }
603
604    #[test]
605    fn plan_children_reports_arity_without_knowing_plan_type() {
606        assert_eq!(PlanChildren::<&str>::None.len(), 0);
607        assert!(PlanChildren::<&str>::None.is_empty());
608
609        let child = "scan";
610        assert_eq!(PlanChildren::Unary(&child).len(), 1);
611
612        let left = "left";
613        let right = "right";
614        assert_eq!(PlanChildren::Binary(&left, &right).len(), 2);
615    }
616
617    #[derive(Debug)]
618    enum TestPlan {
619        Seek,
620        Project(Box<TestPlan>),
621        Join(Box<TestPlan>, Box<TestPlan>),
622    }
623
624    impl PhysicalPlanNode for TestPlan {
625        fn kind(&self) -> PhysicalPlanKind {
626            match self {
627                TestPlan::Seek => PhysicalPlanKind::IndexNodeSeek,
628                TestPlan::Project(_) => PhysicalPlanKind::ProjectExec,
629                TestPlan::Join(_, _) => PhysicalPlanKind::NodeCartesianProductExec,
630            }
631        }
632
633        fn children(&self) -> PlanChildren<'_, Self> {
634            match self {
635                TestPlan::Seek => PlanChildren::None,
636                TestPlan::Project(input) => PlanChildren::Unary(input),
637                TestPlan::Join(left, right) => PlanChildren::Binary(left, right),
638            }
639        }
640    }
641
642    #[test]
643    fn plan_node_helpers_traverse_without_knowing_plan_payloads() {
644        let plan = TestPlan::Project(Box::new(TestPlan::Join(
645            Box::new(TestPlan::Seek),
646            Box::new(TestPlan::Seek),
647        )));
648
649        let mut visit_order = Vec::new();
650        visit_plan(&plan, &mut |node| {
651            visit_order.push(node.kind().as_str());
652        });
653
654        assert_eq!(
655            visit_order,
656            vec![
657                "ProjectExec",
658                "NodeCartesianProductExec",
659                "IndexNodeSeek",
660                "IndexNodeSeek"
661            ]
662        );
663        assert_eq!(plan_operator_counts(&plan)["IndexNodeSeek"], 2);
664        assert_eq!(plan_operator_counts(&plan)["ProjectExec"], 1);
665        assert_eq!(plan_class_counts(&plan)["access"], 2);
666        assert_eq!(plan_class_counts(&plan)["relational"], 2);
667
668        let mut identified = Vec::new();
669        visit_plan_with_ids(&plan, &mut |operator_id, node| {
670            identified.push((operator_id.ordinal(), node.kind().as_str()));
671        });
672        assert_eq!(
673            identified,
674            vec![
675                (0, "ProjectExec"),
676                (1, "NodeCartesianProductExec"),
677                (2, "IndexNodeSeek"),
678                (3, "IndexNodeSeek"),
679            ]
680        );
681    }
682}