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