Skip to main content

grafeo_engine/query/
plan.rs

1//! Logical query plan representation.
2//!
3//! The logical plan is the intermediate representation between parsed queries
4//! and physical execution. Both GQL and Cypher queries are translated to this
5//! common representation.
6
7use std::fmt;
8
9use grafeo_common::types::Value;
10
11/// A count expression for SKIP/LIMIT: either a resolved literal or an unresolved parameter.
12#[derive(Debug, Clone, PartialEq, Eq)]
13pub enum CountExpr {
14    /// A resolved integer count.
15    Literal(usize),
16    /// An unresolved parameter reference (e.g., `$limit`).
17    Parameter(String),
18}
19
20impl CountExpr {
21    /// Returns the resolved count, or panics if still a parameter reference.
22    ///
23    /// Call this only after parameter substitution has run.
24    pub fn value(&self) -> usize {
25        match self {
26            Self::Literal(n) => *n,
27            Self::Parameter(name) => panic!("Unresolved parameter: ${name}"),
28        }
29    }
30
31    /// Returns the resolved count, or an error if still a parameter reference.
32    pub fn try_value(&self) -> Result<usize, String> {
33        match self {
34            Self::Literal(n) => Ok(*n),
35            Self::Parameter(name) => Err(format!("Unresolved SKIP/LIMIT parameter: ${name}")),
36        }
37    }
38
39    /// Returns the count as f64 for cardinality estimation (defaults to 10 for unresolved params).
40    pub fn estimate(&self) -> f64 {
41        match self {
42            Self::Literal(n) => *n as f64,
43            Self::Parameter(_) => 10.0, // reasonable default for unresolved params
44        }
45    }
46}
47
48impl fmt::Display for CountExpr {
49    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
50        match self {
51            Self::Literal(n) => write!(f, "{n}"),
52            Self::Parameter(name) => write!(f, "${name}"),
53        }
54    }
55}
56
57impl From<usize> for CountExpr {
58    fn from(n: usize) -> Self {
59        Self::Literal(n)
60    }
61}
62
63impl PartialEq<usize> for CountExpr {
64    fn eq(&self, other: &usize) -> bool {
65        matches!(self, Self::Literal(n) if n == other)
66    }
67}
68
69/// A logical query plan.
70#[derive(Debug, Clone)]
71pub struct LogicalPlan {
72    /// The root operator of the plan.
73    pub root: LogicalOperator,
74    /// When true, return the plan tree as text instead of executing.
75    pub explain: bool,
76    /// When true, execute the query and return per-operator runtime metrics.
77    pub profile: bool,
78}
79
80impl LogicalPlan {
81    /// Creates a new logical plan with the given root operator.
82    pub fn new(root: LogicalOperator) -> Self {
83        Self {
84            root,
85            explain: false,
86            profile: false,
87        }
88    }
89
90    /// Creates an EXPLAIN plan that returns the plan tree without executing.
91    pub fn explain(root: LogicalOperator) -> Self {
92        Self {
93            root,
94            explain: true,
95            profile: false,
96        }
97    }
98
99    /// Creates a PROFILE plan that executes and returns per-operator metrics.
100    pub fn profile(root: LogicalOperator) -> Self {
101        Self {
102            root,
103            explain: false,
104            profile: true,
105        }
106    }
107}
108
109/// A logical operator in the query plan.
110#[derive(Debug, Clone)]
111pub enum LogicalOperator {
112    /// Scan all nodes, optionally filtered by label.
113    NodeScan(NodeScanOp),
114
115    /// Scan all edges, optionally filtered by type.
116    EdgeScan(EdgeScanOp),
117
118    /// Expand from nodes to neighbors via edges.
119    Expand(ExpandOp),
120
121    /// Filter rows based on a predicate.
122    Filter(FilterOp),
123
124    /// Project specific columns.
125    Project(ProjectOp),
126
127    /// Join two inputs.
128    Join(JoinOp),
129
130    /// Aggregate with grouping.
131    Aggregate(AggregateOp),
132
133    /// Limit the number of results.
134    Limit(LimitOp),
135
136    /// Skip a number of results.
137    Skip(SkipOp),
138
139    /// Sort results.
140    Sort(SortOp),
141
142    /// Remove duplicate results.
143    Distinct(DistinctOp),
144
145    /// Create a new node.
146    CreateNode(CreateNodeOp),
147
148    /// Create a new edge.
149    CreateEdge(CreateEdgeOp),
150
151    /// Delete a node.
152    DeleteNode(DeleteNodeOp),
153
154    /// Delete an edge.
155    DeleteEdge(DeleteEdgeOp),
156
157    /// Set properties on a node or edge.
158    SetProperty(SetPropertyOp),
159
160    /// Add labels to a node.
161    AddLabel(AddLabelOp),
162
163    /// Remove labels from a node.
164    RemoveLabel(RemoveLabelOp),
165
166    /// Return results (terminal operator).
167    Return(ReturnOp),
168
169    /// Empty result set.
170    Empty,
171
172    // ==================== RDF/SPARQL Operators ====================
173    /// Scan RDF triples matching a pattern.
174    TripleScan(TripleScanOp),
175
176    /// Union of multiple result sets.
177    Union(UnionOp),
178
179    /// Left outer join for OPTIONAL patterns.
180    LeftJoin(LeftJoinOp),
181
182    /// Anti-join for MINUS patterns.
183    AntiJoin(AntiJoinOp),
184
185    /// Bind a variable to an expression.
186    Bind(BindOp),
187
188    /// Unwind a list into individual rows.
189    Unwind(UnwindOp),
190
191    /// Collect grouped key-value rows into a single Map value.
192    /// Used for Gremlin `groupCount()` semantics.
193    MapCollect(MapCollectOp),
194
195    /// Merge a node pattern (match or create).
196    Merge(MergeOp),
197
198    /// Merge a relationship pattern (match or create).
199    MergeRelationship(MergeRelationshipOp),
200
201    /// Find shortest path between nodes.
202    ShortestPath(ShortestPathOp),
203
204    // ==================== SPARQL Update Operators ====================
205    /// Insert RDF triples.
206    InsertTriple(InsertTripleOp),
207
208    /// Delete RDF triples.
209    DeleteTriple(DeleteTripleOp),
210
211    /// SPARQL MODIFY operation (DELETE/INSERT WHERE).
212    /// Evaluates WHERE once, applies DELETE templates, then INSERT templates.
213    Modify(ModifyOp),
214
215    /// Clear a graph (remove all triples).
216    ClearGraph(ClearGraphOp),
217
218    /// Create a new named graph.
219    CreateGraph(CreateGraphOp),
220
221    /// Drop (remove) a named graph.
222    DropGraph(DropGraphOp),
223
224    /// Load data from a URL into a graph.
225    LoadGraph(LoadGraphOp),
226
227    /// Copy triples from one graph to another.
228    CopyGraph(CopyGraphOp),
229
230    /// Move triples from one graph to another.
231    MoveGraph(MoveGraphOp),
232
233    /// Add (merge) triples from one graph to another.
234    AddGraph(AddGraphOp),
235
236    /// Per-row aggregation over a list-valued column (horizontal aggregation, GE09).
237    HorizontalAggregate(HorizontalAggregateOp),
238
239    // ==================== Vector Search Operators ====================
240    /// Scan using vector similarity search.
241    VectorScan(VectorScanOp),
242
243    /// Join graph patterns with vector similarity search.
244    ///
245    /// Computes vector distances between entities from the left input and
246    /// a query vector, then joins with similarity scores. Useful for:
247    /// - Filtering graph traversal results by vector similarity
248    /// - Computing aggregated embeddings and finding similar entities
249    /// - Combining multiple vector sources with graph structure
250    VectorJoin(VectorJoinOp),
251
252    // ==================== Set Operations ====================
253    /// Set difference: rows in left that are not in right.
254    Except(ExceptOp),
255
256    /// Set intersection: rows common to all inputs.
257    Intersect(IntersectOp),
258
259    /// Fallback: use left result if non-empty, otherwise right.
260    Otherwise(OtherwiseOp),
261
262    // ==================== Correlated Subquery ====================
263    /// Apply (lateral join): evaluate a subplan per input row.
264    Apply(ApplyOp),
265
266    /// Parameter scan: leaf of a correlated inner plan that receives values
267    /// from the outer Apply operator. The column names match `ApplyOp.shared_variables`.
268    ParameterScan(ParameterScanOp),
269
270    // ==================== DDL Operators ====================
271    /// Define a property graph schema (SQL/PGQ DDL).
272    CreatePropertyGraph(CreatePropertyGraphOp),
273
274    // ==================== Multi-Way Join ====================
275    /// Multi-way join using worst-case optimal join (leapfrog).
276    /// Used for cyclic patterns (triangles, cliques) with 3+ relations.
277    MultiWayJoin(MultiWayJoinOp),
278
279    // ==================== Procedure Call Operators ====================
280    /// Invoke a stored procedure (CALL ... YIELD).
281    CallProcedure(CallProcedureOp),
282
283    // ==================== Data Import Operators ====================
284    /// Load data from a file (CSV, JSONL, or Parquet), producing one row per record.
285    LoadData(LoadDataOp),
286}
287
288impl LogicalOperator {
289    /// Returns `true` if this operator or any of its children perform mutations.
290    #[must_use]
291    pub fn has_mutations(&self) -> bool {
292        match self {
293            // Direct mutation operators
294            Self::CreateNode(_)
295            | Self::CreateEdge(_)
296            | Self::DeleteNode(_)
297            | Self::DeleteEdge(_)
298            | Self::SetProperty(_)
299            | Self::AddLabel(_)
300            | Self::RemoveLabel(_)
301            | Self::Merge(_)
302            | Self::MergeRelationship(_)
303            | Self::InsertTriple(_)
304            | Self::DeleteTriple(_)
305            | Self::Modify(_)
306            | Self::ClearGraph(_)
307            | Self::CreateGraph(_)
308            | Self::DropGraph(_)
309            | Self::LoadGraph(_)
310            | Self::CopyGraph(_)
311            | Self::MoveGraph(_)
312            | Self::AddGraph(_)
313            | Self::CreatePropertyGraph(_) => true,
314
315            // Operators with an `input` child
316            Self::Filter(op) => op.input.has_mutations(),
317            Self::Project(op) => op.input.has_mutations(),
318            Self::Aggregate(op) => op.input.has_mutations(),
319            Self::Limit(op) => op.input.has_mutations(),
320            Self::Skip(op) => op.input.has_mutations(),
321            Self::Sort(op) => op.input.has_mutations(),
322            Self::Distinct(op) => op.input.has_mutations(),
323            Self::Unwind(op) => op.input.has_mutations(),
324            Self::Bind(op) => op.input.has_mutations(),
325            Self::MapCollect(op) => op.input.has_mutations(),
326            Self::Return(op) => op.input.has_mutations(),
327            Self::HorizontalAggregate(op) => op.input.has_mutations(),
328            Self::VectorScan(_) | Self::VectorJoin(_) => false,
329
330            // Operators with two children
331            Self::Join(op) => op.left.has_mutations() || op.right.has_mutations(),
332            Self::LeftJoin(op) => op.left.has_mutations() || op.right.has_mutations(),
333            Self::AntiJoin(op) => op.left.has_mutations() || op.right.has_mutations(),
334            Self::Except(op) => op.left.has_mutations() || op.right.has_mutations(),
335            Self::Intersect(op) => op.left.has_mutations() || op.right.has_mutations(),
336            Self::Otherwise(op) => op.left.has_mutations() || op.right.has_mutations(),
337            Self::Union(op) => op.inputs.iter().any(|i| i.has_mutations()),
338            Self::MultiWayJoin(op) => op.inputs.iter().any(|i| i.has_mutations()),
339            Self::Apply(op) => op.input.has_mutations() || op.subplan.has_mutations(),
340
341            // Leaf operators (read-only)
342            Self::NodeScan(_)
343            | Self::EdgeScan(_)
344            | Self::Expand(_)
345            | Self::TripleScan(_)
346            | Self::ShortestPath(_)
347            | Self::Empty
348            | Self::ParameterScan(_)
349            | Self::CallProcedure(_)
350            | Self::LoadData(_) => false,
351        }
352    }
353
354    /// Returns references to the child operators.
355    ///
356    /// Used by [`crate::query::profile::build_profile_tree`] to walk the logical
357    /// plan tree in post-order, matching operators to profiling entries.
358    #[must_use]
359    pub fn children(&self) -> Vec<&LogicalOperator> {
360        match self {
361            // Optional single input
362            Self::NodeScan(op) => op.input.as_deref().into_iter().collect(),
363            Self::EdgeScan(op) => op.input.as_deref().into_iter().collect(),
364            Self::TripleScan(op) => op.input.as_deref().into_iter().collect(),
365            Self::VectorScan(op) => op.input.as_deref().into_iter().collect(),
366            Self::CreateNode(op) => op.input.as_deref().into_iter().collect(),
367            Self::InsertTriple(op) => op.input.as_deref().into_iter().collect(),
368            Self::DeleteTriple(op) => op.input.as_deref().into_iter().collect(),
369
370            // Single required input
371            Self::Expand(op) => vec![&*op.input],
372            Self::Filter(op) => vec![&*op.input],
373            Self::Project(op) => vec![&*op.input],
374            Self::Aggregate(op) => vec![&*op.input],
375            Self::Limit(op) => vec![&*op.input],
376            Self::Skip(op) => vec![&*op.input],
377            Self::Sort(op) => vec![&*op.input],
378            Self::Distinct(op) => vec![&*op.input],
379            Self::Return(op) => vec![&*op.input],
380            Self::Unwind(op) => vec![&*op.input],
381            Self::Bind(op) => vec![&*op.input],
382            Self::MapCollect(op) => vec![&*op.input],
383            Self::ShortestPath(op) => vec![&*op.input],
384            Self::Merge(op) => vec![&*op.input],
385            Self::MergeRelationship(op) => vec![&*op.input],
386            Self::CreateEdge(op) => vec![&*op.input],
387            Self::DeleteNode(op) => vec![&*op.input],
388            Self::DeleteEdge(op) => vec![&*op.input],
389            Self::SetProperty(op) => vec![&*op.input],
390            Self::AddLabel(op) => vec![&*op.input],
391            Self::RemoveLabel(op) => vec![&*op.input],
392            Self::HorizontalAggregate(op) => vec![&*op.input],
393            Self::VectorJoin(op) => vec![&*op.input],
394            Self::Modify(op) => vec![&*op.where_clause],
395
396            // Two children (left + right)
397            Self::Join(op) => vec![&*op.left, &*op.right],
398            Self::LeftJoin(op) => vec![&*op.left, &*op.right],
399            Self::AntiJoin(op) => vec![&*op.left, &*op.right],
400            Self::Except(op) => vec![&*op.left, &*op.right],
401            Self::Intersect(op) => vec![&*op.left, &*op.right],
402            Self::Otherwise(op) => vec![&*op.left, &*op.right],
403
404            // Two children (input + subplan)
405            Self::Apply(op) => vec![&*op.input, &*op.subplan],
406
407            // Vec children
408            Self::Union(op) => op.inputs.iter().collect(),
409            Self::MultiWayJoin(op) => op.inputs.iter().collect(),
410
411            // Leaf operators
412            Self::Empty
413            | Self::ParameterScan(_)
414            | Self::CallProcedure(_)
415            | Self::ClearGraph(_)
416            | Self::CreateGraph(_)
417            | Self::DropGraph(_)
418            | Self::LoadGraph(_)
419            | Self::CopyGraph(_)
420            | Self::MoveGraph(_)
421            | Self::AddGraph(_)
422            | Self::CreatePropertyGraph(_)
423            | Self::LoadData(_) => vec![],
424        }
425    }
426
427    /// Returns a compact display label for this operator, used in PROFILE output.
428    #[must_use]
429    pub fn display_label(&self) -> String {
430        match self {
431            Self::NodeScan(op) => {
432                let label = op.label.as_deref().unwrap_or("*");
433                format!("{}:{}", op.variable, label)
434            }
435            Self::EdgeScan(op) => {
436                let types = if op.edge_types.is_empty() {
437                    "*".to_string()
438                } else {
439                    op.edge_types.join("|")
440                };
441                format!("{}:{}", op.variable, types)
442            }
443            Self::Expand(op) => {
444                let types = if op.edge_types.is_empty() {
445                    "*".to_string()
446                } else {
447                    op.edge_types.join("|")
448                };
449                let dir = match op.direction {
450                    ExpandDirection::Outgoing => "->",
451                    ExpandDirection::Incoming => "<-",
452                    ExpandDirection::Both => "--",
453                };
454                format!(
455                    "({from}){dir}[:{types}]{dir}({to})",
456                    from = op.from_variable,
457                    to = op.to_variable,
458                )
459            }
460            Self::Filter(op) => {
461                let hint = match &op.pushdown_hint {
462                    Some(PushdownHint::IndexLookup { property }) => {
463                        format!(" [index: {property}]")
464                    }
465                    Some(PushdownHint::RangeScan { property }) => {
466                        format!(" [range: {property}]")
467                    }
468                    Some(PushdownHint::LabelFirst) => " [label-first]".to_string(),
469                    None => String::new(),
470                };
471                format!("{}{hint}", fmt_expr(&op.predicate))
472            }
473            Self::Project(op) => {
474                let cols: Vec<String> = op
475                    .projections
476                    .iter()
477                    .map(|p| match &p.alias {
478                        Some(alias) => alias.clone(),
479                        None => fmt_expr(&p.expression),
480                    })
481                    .collect();
482                cols.join(", ")
483            }
484            Self::Join(op) => format!("{:?}", op.join_type),
485            Self::Aggregate(op) => {
486                let groups: Vec<String> = op.group_by.iter().map(fmt_expr).collect();
487                format!("group: [{}]", groups.join(", "))
488            }
489            Self::Limit(op) => format!("{}", op.count),
490            Self::Skip(op) => format!("{}", op.count),
491            Self::Sort(op) => {
492                let keys: Vec<String> = op
493                    .keys
494                    .iter()
495                    .map(|k| {
496                        let dir = match k.order {
497                            SortOrder::Ascending => "ASC",
498                            SortOrder::Descending => "DESC",
499                        };
500                        format!("{} {dir}", fmt_expr(&k.expression))
501                    })
502                    .collect();
503                keys.join(", ")
504            }
505            Self::Distinct(_) => String::new(),
506            Self::Return(op) => {
507                let items: Vec<String> = op
508                    .items
509                    .iter()
510                    .map(|item| match &item.alias {
511                        Some(alias) => alias.clone(),
512                        None => fmt_expr(&item.expression),
513                    })
514                    .collect();
515                items.join(", ")
516            }
517            Self::Union(op) => format!("{} branches", op.inputs.len()),
518            Self::MultiWayJoin(op) => {
519                format!("{} inputs", op.inputs.len())
520            }
521            Self::LeftJoin(_) => String::new(),
522            Self::AntiJoin(_) => String::new(),
523            Self::Unwind(op) => op.variable.clone(),
524            Self::Bind(op) => op.variable.clone(),
525            Self::MapCollect(op) => op.alias.clone(),
526            Self::ShortestPath(op) => {
527                format!("{} -> {}", op.source_var, op.target_var)
528            }
529            Self::Merge(op) => op.variable.clone(),
530            Self::MergeRelationship(op) => op.variable.clone(),
531            Self::CreateNode(op) => {
532                let labels = op.labels.join(":");
533                format!("{}:{labels}", op.variable)
534            }
535            Self::CreateEdge(op) => {
536                format!(
537                    "[{}:{}]",
538                    op.variable.as_deref().unwrap_or("?"),
539                    op.edge_type
540                )
541            }
542            Self::DeleteNode(op) => op.variable.clone(),
543            Self::DeleteEdge(op) => op.variable.clone(),
544            Self::SetProperty(op) => op.variable.clone(),
545            Self::AddLabel(op) => {
546                let labels = op.labels.join(":");
547                format!("{}:{labels}", op.variable)
548            }
549            Self::RemoveLabel(op) => {
550                let labels = op.labels.join(":");
551                format!("{}:{labels}", op.variable)
552            }
553            Self::CallProcedure(op) => op.name.join("."),
554            Self::LoadData(op) => format!("{} AS {}", op.path, op.variable),
555            Self::Apply(_) => String::new(),
556            Self::VectorScan(op) => op.variable.clone(),
557            Self::VectorJoin(op) => op.right_variable.clone(),
558            _ => String::new(),
559        }
560    }
561}
562
563impl LogicalOperator {
564    /// Formats this operator tree as a human-readable plan for EXPLAIN output.
565    pub fn explain_tree(&self) -> String {
566        let mut output = String::new();
567        self.fmt_tree(&mut output, 0);
568        output
569    }
570
571    fn fmt_tree(&self, out: &mut String, depth: usize) {
572        use std::fmt::Write;
573
574        let indent = "  ".repeat(depth);
575        match self {
576            Self::NodeScan(op) => {
577                let label = op.label.as_deref().unwrap_or("*");
578                let _ = writeln!(out, "{indent}NodeScan ({var}:{label})", var = op.variable);
579                if let Some(input) = &op.input {
580                    input.fmt_tree(out, depth + 1);
581                }
582            }
583            Self::EdgeScan(op) => {
584                let types = if op.edge_types.is_empty() {
585                    "*".to_string()
586                } else {
587                    op.edge_types.join("|")
588                };
589                let _ = writeln!(out, "{indent}EdgeScan ({var}:{types})", var = op.variable);
590            }
591            Self::Expand(op) => {
592                let types = if op.edge_types.is_empty() {
593                    "*".to_string()
594                } else {
595                    op.edge_types.join("|")
596                };
597                let dir = match op.direction {
598                    ExpandDirection::Outgoing => "->",
599                    ExpandDirection::Incoming => "<-",
600                    ExpandDirection::Both => "--",
601                };
602                let hops = match (op.min_hops, op.max_hops) {
603                    (1, Some(1)) => String::new(),
604                    (min, Some(max)) if min == max => format!("*{min}"),
605                    (min, Some(max)) => format!("*{min}..{max}"),
606                    (min, None) => format!("*{min}.."),
607                };
608                let _ = writeln!(
609                    out,
610                    "{indent}Expand ({from}){dir}[:{types}{hops}]{dir}({to})",
611                    from = op.from_variable,
612                    to = op.to_variable,
613                );
614                op.input.fmt_tree(out, depth + 1);
615            }
616            Self::Filter(op) => {
617                let hint = match &op.pushdown_hint {
618                    Some(PushdownHint::IndexLookup { property }) => {
619                        format!(" [index: {property}]")
620                    }
621                    Some(PushdownHint::RangeScan { property }) => {
622                        format!(" [range: {property}]")
623                    }
624                    Some(PushdownHint::LabelFirst) => " [label-first]".to_string(),
625                    None => String::new(),
626                };
627                let _ = writeln!(
628                    out,
629                    "{indent}Filter ({expr}){hint}",
630                    expr = fmt_expr(&op.predicate)
631                );
632                op.input.fmt_tree(out, depth + 1);
633            }
634            Self::Project(op) => {
635                let cols: Vec<String> = op
636                    .projections
637                    .iter()
638                    .map(|p| {
639                        let expr = fmt_expr(&p.expression);
640                        match &p.alias {
641                            Some(alias) => format!("{expr} AS {alias}"),
642                            None => expr,
643                        }
644                    })
645                    .collect();
646                let _ = writeln!(out, "{indent}Project ({cols})", cols = cols.join(", "));
647                op.input.fmt_tree(out, depth + 1);
648            }
649            Self::Join(op) => {
650                let _ = writeln!(out, "{indent}Join ({ty:?})", ty = op.join_type);
651                op.left.fmt_tree(out, depth + 1);
652                op.right.fmt_tree(out, depth + 1);
653            }
654            Self::Aggregate(op) => {
655                let groups: Vec<String> = op.group_by.iter().map(fmt_expr).collect();
656                let aggs: Vec<String> = op
657                    .aggregates
658                    .iter()
659                    .map(|a| {
660                        let func = format!("{:?}", a.function).to_lowercase();
661                        match &a.alias {
662                            Some(alias) => format!("{func}(...) AS {alias}"),
663                            None => format!("{func}(...)"),
664                        }
665                    })
666                    .collect();
667                let _ = writeln!(
668                    out,
669                    "{indent}Aggregate (group: [{groups}], aggs: [{aggs}])",
670                    groups = groups.join(", "),
671                    aggs = aggs.join(", "),
672                );
673                op.input.fmt_tree(out, depth + 1);
674            }
675            Self::Limit(op) => {
676                let _ = writeln!(out, "{indent}Limit ({})", op.count);
677                op.input.fmt_tree(out, depth + 1);
678            }
679            Self::Skip(op) => {
680                let _ = writeln!(out, "{indent}Skip ({})", op.count);
681                op.input.fmt_tree(out, depth + 1);
682            }
683            Self::Sort(op) => {
684                let keys: Vec<String> = op
685                    .keys
686                    .iter()
687                    .map(|k| {
688                        let dir = match k.order {
689                            SortOrder::Ascending => "ASC",
690                            SortOrder::Descending => "DESC",
691                        };
692                        format!("{} {dir}", fmt_expr(&k.expression))
693                    })
694                    .collect();
695                let _ = writeln!(out, "{indent}Sort ({keys})", keys = keys.join(", "));
696                op.input.fmt_tree(out, depth + 1);
697            }
698            Self::Distinct(op) => {
699                let _ = writeln!(out, "{indent}Distinct");
700                op.input.fmt_tree(out, depth + 1);
701            }
702            Self::Return(op) => {
703                let items: Vec<String> = op
704                    .items
705                    .iter()
706                    .map(|item| {
707                        let expr = fmt_expr(&item.expression);
708                        match &item.alias {
709                            Some(alias) => format!("{expr} AS {alias}"),
710                            None => expr,
711                        }
712                    })
713                    .collect();
714                let distinct = if op.distinct { " DISTINCT" } else { "" };
715                let _ = writeln!(
716                    out,
717                    "{indent}Return{distinct} ({items})",
718                    items = items.join(", ")
719                );
720                op.input.fmt_tree(out, depth + 1);
721            }
722            Self::Union(op) => {
723                let _ = writeln!(out, "{indent}Union ({n} branches)", n = op.inputs.len());
724                for input in &op.inputs {
725                    input.fmt_tree(out, depth + 1);
726                }
727            }
728            Self::MultiWayJoin(op) => {
729                let vars = op.shared_variables.join(", ");
730                let _ = writeln!(
731                    out,
732                    "{indent}MultiWayJoin ({n} inputs, shared: [{vars}])",
733                    n = op.inputs.len()
734                );
735                for input in &op.inputs {
736                    input.fmt_tree(out, depth + 1);
737                }
738            }
739            Self::LeftJoin(op) => {
740                if let Some(cond) = &op.condition {
741                    let _ = writeln!(out, "{indent}LeftJoin (condition: {cond:?})");
742                } else {
743                    let _ = writeln!(out, "{indent}LeftJoin");
744                }
745                op.left.fmt_tree(out, depth + 1);
746                op.right.fmt_tree(out, depth + 1);
747            }
748            Self::AntiJoin(op) => {
749                let _ = writeln!(out, "{indent}AntiJoin");
750                op.left.fmt_tree(out, depth + 1);
751                op.right.fmt_tree(out, depth + 1);
752            }
753            Self::Unwind(op) => {
754                let _ = writeln!(out, "{indent}Unwind ({var})", var = op.variable);
755                op.input.fmt_tree(out, depth + 1);
756            }
757            Self::Bind(op) => {
758                let _ = writeln!(out, "{indent}Bind ({var})", var = op.variable);
759                op.input.fmt_tree(out, depth + 1);
760            }
761            Self::MapCollect(op) => {
762                let _ = writeln!(
763                    out,
764                    "{indent}MapCollect ({key} -> {val} AS {alias})",
765                    key = op.key_var,
766                    val = op.value_var,
767                    alias = op.alias
768                );
769                op.input.fmt_tree(out, depth + 1);
770            }
771            Self::Apply(op) => {
772                let _ = writeln!(out, "{indent}Apply");
773                op.input.fmt_tree(out, depth + 1);
774                op.subplan.fmt_tree(out, depth + 1);
775            }
776            Self::Except(op) => {
777                let all = if op.all { " ALL" } else { "" };
778                let _ = writeln!(out, "{indent}Except{all}");
779                op.left.fmt_tree(out, depth + 1);
780                op.right.fmt_tree(out, depth + 1);
781            }
782            Self::Intersect(op) => {
783                let all = if op.all { " ALL" } else { "" };
784                let _ = writeln!(out, "{indent}Intersect{all}");
785                op.left.fmt_tree(out, depth + 1);
786                op.right.fmt_tree(out, depth + 1);
787            }
788            Self::Otherwise(op) => {
789                let _ = writeln!(out, "{indent}Otherwise");
790                op.left.fmt_tree(out, depth + 1);
791                op.right.fmt_tree(out, depth + 1);
792            }
793            Self::ShortestPath(op) => {
794                let _ = writeln!(
795                    out,
796                    "{indent}ShortestPath ({from} -> {to})",
797                    from = op.source_var,
798                    to = op.target_var
799                );
800                op.input.fmt_tree(out, depth + 1);
801            }
802            Self::Merge(op) => {
803                let _ = writeln!(out, "{indent}Merge ({var})", var = op.variable);
804                op.input.fmt_tree(out, depth + 1);
805            }
806            Self::MergeRelationship(op) => {
807                let _ = writeln!(out, "{indent}MergeRelationship ({var})", var = op.variable);
808                op.input.fmt_tree(out, depth + 1);
809            }
810            Self::CreateNode(op) => {
811                let labels = op.labels.join(":");
812                let _ = writeln!(
813                    out,
814                    "{indent}CreateNode ({var}:{labels})",
815                    var = op.variable
816                );
817                if let Some(input) = &op.input {
818                    input.fmt_tree(out, depth + 1);
819                }
820            }
821            Self::CreateEdge(op) => {
822                let var = op.variable.as_deref().unwrap_or("?");
823                let _ = writeln!(
824                    out,
825                    "{indent}CreateEdge ({from})-[{var}:{ty}]->({to})",
826                    from = op.from_variable,
827                    ty = op.edge_type,
828                    to = op.to_variable
829                );
830                op.input.fmt_tree(out, depth + 1);
831            }
832            Self::DeleteNode(op) => {
833                let _ = writeln!(out, "{indent}DeleteNode ({var})", var = op.variable);
834                op.input.fmt_tree(out, depth + 1);
835            }
836            Self::DeleteEdge(op) => {
837                let _ = writeln!(out, "{indent}DeleteEdge ({var})", var = op.variable);
838                op.input.fmt_tree(out, depth + 1);
839            }
840            Self::SetProperty(op) => {
841                let props: Vec<String> = op
842                    .properties
843                    .iter()
844                    .map(|(k, _)| format!("{}.{k}", op.variable))
845                    .collect();
846                let _ = writeln!(
847                    out,
848                    "{indent}SetProperty ({props})",
849                    props = props.join(", ")
850                );
851                op.input.fmt_tree(out, depth + 1);
852            }
853            Self::AddLabel(op) => {
854                let labels = op.labels.join(":");
855                let _ = writeln!(out, "{indent}AddLabel ({var}:{labels})", var = op.variable);
856                op.input.fmt_tree(out, depth + 1);
857            }
858            Self::RemoveLabel(op) => {
859                let labels = op.labels.join(":");
860                let _ = writeln!(
861                    out,
862                    "{indent}RemoveLabel ({var}:{labels})",
863                    var = op.variable
864                );
865                op.input.fmt_tree(out, depth + 1);
866            }
867            Self::CallProcedure(op) => {
868                let _ = writeln!(
869                    out,
870                    "{indent}CallProcedure ({name})",
871                    name = op.name.join(".")
872                );
873            }
874            Self::LoadData(op) => {
875                let format_name = match op.format {
876                    LoadDataFormat::Csv => "LoadCsv",
877                    LoadDataFormat::Jsonl => "LoadJsonl",
878                    LoadDataFormat::Parquet => "LoadParquet",
879                };
880                let headers = if op.with_headers && op.format == LoadDataFormat::Csv {
881                    " WITH HEADERS"
882                } else {
883                    ""
884                };
885                let _ = writeln!(
886                    out,
887                    "{indent}{format_name}{headers} ('{path}' AS {var})",
888                    path = op.path,
889                    var = op.variable,
890                );
891            }
892            Self::TripleScan(op) => {
893                let _ = writeln!(
894                    out,
895                    "{indent}TripleScan ({s} {p} {o})",
896                    s = fmt_triple_component(&op.subject),
897                    p = fmt_triple_component(&op.predicate),
898                    o = fmt_triple_component(&op.object)
899                );
900                if let Some(input) = &op.input {
901                    input.fmt_tree(out, depth + 1);
902                }
903            }
904            Self::Empty => {
905                let _ = writeln!(out, "{indent}Empty");
906            }
907            // Remaining operators: show a simple name
908            _ => {
909                let _ = writeln!(out, "{indent}{:?}", std::mem::discriminant(self));
910            }
911        }
912    }
913}
914
915/// Format a logical expression compactly for EXPLAIN output.
916fn fmt_expr(expr: &LogicalExpression) -> String {
917    match expr {
918        LogicalExpression::Variable(name) => name.clone(),
919        LogicalExpression::Property { variable, property } => format!("{variable}.{property}"),
920        LogicalExpression::Literal(val) => format!("{val}"),
921        LogicalExpression::Binary { left, op, right } => {
922            format!("{} {op:?} {}", fmt_expr(left), fmt_expr(right))
923        }
924        LogicalExpression::Unary { op, operand } => {
925            format!("{op:?} {}", fmt_expr(operand))
926        }
927        LogicalExpression::FunctionCall { name, args, .. } => {
928            let arg_strs: Vec<String> = args.iter().map(fmt_expr).collect();
929            format!("{name}({})", arg_strs.join(", "))
930        }
931        _ => format!("{expr:?}"),
932    }
933}
934
935/// Format a triple component for EXPLAIN output.
936fn fmt_triple_component(comp: &TripleComponent) -> String {
937    match comp {
938        TripleComponent::Variable(name) => format!("?{name}"),
939        TripleComponent::Iri(iri) => format!("<{iri}>"),
940        TripleComponent::Literal(val) => format!("{val}"),
941    }
942}
943
944/// Scan nodes from the graph.
945#[derive(Debug, Clone)]
946pub struct NodeScanOp {
947    /// Variable name to bind the node to.
948    pub variable: String,
949    /// Optional label filter.
950    pub label: Option<String>,
951    /// Child operator (if any, for chained patterns).
952    pub input: Option<Box<LogicalOperator>>,
953}
954
955/// Scan edges from the graph.
956#[derive(Debug, Clone)]
957pub struct EdgeScanOp {
958    /// Variable name to bind the edge to.
959    pub variable: String,
960    /// Edge type filter (empty = match all types).
961    pub edge_types: Vec<String>,
962    /// Child operator (if any).
963    pub input: Option<Box<LogicalOperator>>,
964}
965
966/// Path traversal mode for variable-length expansion.
967#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
968pub enum PathMode {
969    /// Allows repeated nodes and edges (default).
970    #[default]
971    Walk,
972    /// No repeated edges.
973    Trail,
974    /// No repeated nodes except endpoints.
975    Simple,
976    /// No repeated nodes at all.
977    Acyclic,
978}
979
980/// Expand from nodes to their neighbors.
981#[derive(Debug, Clone)]
982pub struct ExpandOp {
983    /// Source node variable.
984    pub from_variable: String,
985    /// Target node variable to bind.
986    pub to_variable: String,
987    /// Edge variable to bind (optional).
988    pub edge_variable: Option<String>,
989    /// Direction of expansion.
990    pub direction: ExpandDirection,
991    /// Edge type filter (empty = match all types, multiple = match any).
992    pub edge_types: Vec<String>,
993    /// Minimum hops (for variable-length patterns).
994    pub min_hops: u32,
995    /// Maximum hops (for variable-length patterns).
996    pub max_hops: Option<u32>,
997    /// Input operator.
998    pub input: Box<LogicalOperator>,
999    /// Path alias for variable-length patterns (e.g., `p` in `p = (a)-[*1..3]->(b)`).
1000    /// When set, a path length column will be output under this name.
1001    pub path_alias: Option<String>,
1002    /// Path traversal mode (WALK, TRAIL, SIMPLE, ACYCLIC).
1003    pub path_mode: PathMode,
1004}
1005
1006/// Direction for edge expansion.
1007#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1008pub enum ExpandDirection {
1009    /// Follow outgoing edges.
1010    Outgoing,
1011    /// Follow incoming edges.
1012    Incoming,
1013    /// Follow edges in either direction.
1014    Both,
1015}
1016
1017/// Join two inputs.
1018#[derive(Debug, Clone)]
1019pub struct JoinOp {
1020    /// Left input.
1021    pub left: Box<LogicalOperator>,
1022    /// Right input.
1023    pub right: Box<LogicalOperator>,
1024    /// Join type.
1025    pub join_type: JoinType,
1026    /// Join conditions.
1027    pub conditions: Vec<JoinCondition>,
1028}
1029
1030/// Join type.
1031#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1032pub enum JoinType {
1033    /// Inner join.
1034    Inner,
1035    /// Left outer join.
1036    Left,
1037    /// Right outer join.
1038    Right,
1039    /// Full outer join.
1040    Full,
1041    /// Cross join (Cartesian product).
1042    Cross,
1043    /// Semi join (returns left rows with matching right rows).
1044    Semi,
1045    /// Anti join (returns left rows without matching right rows).
1046    Anti,
1047}
1048
1049/// A join condition.
1050#[derive(Debug, Clone)]
1051pub struct JoinCondition {
1052    /// Left expression.
1053    pub left: LogicalExpression,
1054    /// Right expression.
1055    pub right: LogicalExpression,
1056}
1057
1058/// Multi-way join for worst-case optimal joins (leapfrog).
1059///
1060/// Unlike binary `JoinOp`, this joins 3+ relations simultaneously
1061/// using the leapfrog trie join algorithm. Preferred for cyclic patterns
1062/// (triangles, cliques) where cascading binary joins hit O(N^2).
1063#[derive(Debug, Clone)]
1064pub struct MultiWayJoinOp {
1065    /// Input relations (one per relation in the join).
1066    pub inputs: Vec<LogicalOperator>,
1067    /// All pairwise join conditions.
1068    pub conditions: Vec<JoinCondition>,
1069    /// Variables shared across multiple inputs (intersection keys).
1070    pub shared_variables: Vec<String>,
1071}
1072
1073/// Aggregate with grouping.
1074#[derive(Debug, Clone)]
1075pub struct AggregateOp {
1076    /// Group by expressions.
1077    pub group_by: Vec<LogicalExpression>,
1078    /// Aggregate functions.
1079    pub aggregates: Vec<AggregateExpr>,
1080    /// Input operator.
1081    pub input: Box<LogicalOperator>,
1082    /// HAVING clause filter (applied after aggregation).
1083    pub having: Option<LogicalExpression>,
1084}
1085
1086/// Whether a horizontal aggregate operates on edges or nodes.
1087#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1088pub enum EntityKind {
1089    /// Aggregate over edges in a path.
1090    Edge,
1091    /// Aggregate over nodes in a path.
1092    Node,
1093}
1094
1095/// Per-row aggregation over a list-valued column (horizontal aggregation, GE09).
1096///
1097/// For each input row, reads a list of entity IDs from `list_column`, accesses
1098/// `property` on each entity, computes the aggregate, and emits the scalar result.
1099#[derive(Debug, Clone)]
1100pub struct HorizontalAggregateOp {
1101    /// The list column name (e.g., `_path_edges_p`).
1102    pub list_column: String,
1103    /// Whether the list contains edge IDs or node IDs.
1104    pub entity_kind: EntityKind,
1105    /// The aggregate function to apply.
1106    pub function: AggregateFunction,
1107    /// The property to access on each entity.
1108    pub property: String,
1109    /// Output alias for the result column.
1110    pub alias: String,
1111    /// Input operator.
1112    pub input: Box<LogicalOperator>,
1113}
1114
1115/// An aggregate expression.
1116#[derive(Debug, Clone)]
1117pub struct AggregateExpr {
1118    /// Aggregate function.
1119    pub function: AggregateFunction,
1120    /// Expression to aggregate (first/only argument, y for binary set functions).
1121    pub expression: Option<LogicalExpression>,
1122    /// Second expression for binary set functions (x for COVAR, CORR, REGR_*).
1123    pub expression2: Option<LogicalExpression>,
1124    /// Whether to use DISTINCT.
1125    pub distinct: bool,
1126    /// Alias for the result.
1127    pub alias: Option<String>,
1128    /// Percentile parameter for PERCENTILE_DISC/PERCENTILE_CONT (0.0 to 1.0).
1129    pub percentile: Option<f64>,
1130    /// Separator string for GROUP_CONCAT / LISTAGG (defaults to space for GROUP_CONCAT, comma for LISTAGG).
1131    pub separator: Option<String>,
1132}
1133
1134/// Aggregate function.
1135#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1136pub enum AggregateFunction {
1137    /// Count all rows (COUNT(*)).
1138    Count,
1139    /// Count non-null values (COUNT(expr)).
1140    CountNonNull,
1141    /// Sum values.
1142    Sum,
1143    /// Average values.
1144    Avg,
1145    /// Minimum value.
1146    Min,
1147    /// Maximum value.
1148    Max,
1149    /// Collect into list.
1150    Collect,
1151    /// Sample standard deviation (STDEV).
1152    StdDev,
1153    /// Population standard deviation (STDEVP).
1154    StdDevPop,
1155    /// Sample variance (VAR_SAMP / VARIANCE).
1156    Variance,
1157    /// Population variance (VAR_POP).
1158    VariancePop,
1159    /// Discrete percentile (PERCENTILE_DISC).
1160    PercentileDisc,
1161    /// Continuous percentile (PERCENTILE_CONT).
1162    PercentileCont,
1163    /// Concatenate values with separator (GROUP_CONCAT).
1164    GroupConcat,
1165    /// Return an arbitrary value from the group (SAMPLE).
1166    Sample,
1167    /// Sample covariance (COVAR_SAMP(y, x)).
1168    CovarSamp,
1169    /// Population covariance (COVAR_POP(y, x)).
1170    CovarPop,
1171    /// Pearson correlation coefficient (CORR(y, x)).
1172    Corr,
1173    /// Regression slope (REGR_SLOPE(y, x)).
1174    RegrSlope,
1175    /// Regression intercept (REGR_INTERCEPT(y, x)).
1176    RegrIntercept,
1177    /// Coefficient of determination (REGR_R2(y, x)).
1178    RegrR2,
1179    /// Regression count of non-null pairs (REGR_COUNT(y, x)).
1180    RegrCount,
1181    /// Regression sum of squares for x (REGR_SXX(y, x)).
1182    RegrSxx,
1183    /// Regression sum of squares for y (REGR_SYY(y, x)).
1184    RegrSyy,
1185    /// Regression sum of cross-products (REGR_SXY(y, x)).
1186    RegrSxy,
1187    /// Regression average of x (REGR_AVGX(y, x)).
1188    RegrAvgx,
1189    /// Regression average of y (REGR_AVGY(y, x)).
1190    RegrAvgy,
1191}
1192
1193/// Hint about how a filter will be executed at the physical level.
1194///
1195/// Set during EXPLAIN annotation to communicate pushdown decisions.
1196#[derive(Debug, Clone)]
1197pub enum PushdownHint {
1198    /// Equality predicate resolved via a property index.
1199    IndexLookup {
1200        /// The indexed property name.
1201        property: String,
1202    },
1203    /// Range predicate resolved via a range/btree index.
1204    RangeScan {
1205        /// The indexed property name.
1206        property: String,
1207    },
1208    /// No index available, but label narrows the scan before filtering.
1209    LabelFirst,
1210}
1211
1212/// Filter rows based on a predicate.
1213#[derive(Debug, Clone)]
1214pub struct FilterOp {
1215    /// The filter predicate.
1216    pub predicate: LogicalExpression,
1217    /// Input operator.
1218    pub input: Box<LogicalOperator>,
1219    /// Optional hint about pushdown strategy (populated by EXPLAIN).
1220    pub pushdown_hint: Option<PushdownHint>,
1221}
1222
1223/// Project specific columns.
1224#[derive(Debug, Clone)]
1225pub struct ProjectOp {
1226    /// Columns to project.
1227    pub projections: Vec<Projection>,
1228    /// Input operator.
1229    pub input: Box<LogicalOperator>,
1230    /// When true, all input columns are passed through and the explicit
1231    /// projections are appended as additional output columns. Used by GQL
1232    /// LET clauses which add bindings without replacing the existing scope.
1233    pub pass_through_input: bool,
1234}
1235
1236/// A single projection (column selection or computation).
1237#[derive(Debug, Clone)]
1238pub struct Projection {
1239    /// Expression to compute.
1240    pub expression: LogicalExpression,
1241    /// Alias for the result.
1242    pub alias: Option<String>,
1243}
1244
1245/// Limit the number of results.
1246#[derive(Debug, Clone)]
1247pub struct LimitOp {
1248    /// Maximum number of rows to return (literal or parameter reference).
1249    pub count: CountExpr,
1250    /// Input operator.
1251    pub input: Box<LogicalOperator>,
1252}
1253
1254/// Skip a number of results.
1255#[derive(Debug, Clone)]
1256pub struct SkipOp {
1257    /// Number of rows to skip (literal or parameter reference).
1258    pub count: CountExpr,
1259    /// Input operator.
1260    pub input: Box<LogicalOperator>,
1261}
1262
1263/// Sort results.
1264#[derive(Debug, Clone)]
1265pub struct SortOp {
1266    /// Sort keys.
1267    pub keys: Vec<SortKey>,
1268    /// Input operator.
1269    pub input: Box<LogicalOperator>,
1270}
1271
1272/// A sort key.
1273#[derive(Debug, Clone)]
1274pub struct SortKey {
1275    /// Expression to sort by.
1276    pub expression: LogicalExpression,
1277    /// Sort order.
1278    pub order: SortOrder,
1279    /// Optional null ordering (NULLS FIRST / NULLS LAST).
1280    pub nulls: Option<NullsOrdering>,
1281}
1282
1283/// Sort order.
1284#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1285pub enum SortOrder {
1286    /// Ascending order.
1287    Ascending,
1288    /// Descending order.
1289    Descending,
1290}
1291
1292/// Null ordering for sort operations.
1293#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1294pub enum NullsOrdering {
1295    /// Nulls sort before all non-null values.
1296    First,
1297    /// Nulls sort after all non-null values.
1298    Last,
1299}
1300
1301/// Remove duplicate results.
1302#[derive(Debug, Clone)]
1303pub struct DistinctOp {
1304    /// Input operator.
1305    pub input: Box<LogicalOperator>,
1306    /// Optional columns to use for deduplication.
1307    /// If None, all columns are used.
1308    pub columns: Option<Vec<String>>,
1309}
1310
1311/// Create a new node.
1312#[derive(Debug, Clone)]
1313pub struct CreateNodeOp {
1314    /// Variable name to bind the created node to.
1315    pub variable: String,
1316    /// Labels for the new node.
1317    pub labels: Vec<String>,
1318    /// Properties for the new node.
1319    pub properties: Vec<(String, LogicalExpression)>,
1320    /// Input operator (for chained creates).
1321    pub input: Option<Box<LogicalOperator>>,
1322}
1323
1324/// Create a new edge.
1325#[derive(Debug, Clone)]
1326pub struct CreateEdgeOp {
1327    /// Variable name to bind the created edge to.
1328    pub variable: Option<String>,
1329    /// Source node variable.
1330    pub from_variable: String,
1331    /// Target node variable.
1332    pub to_variable: String,
1333    /// Edge type.
1334    pub edge_type: String,
1335    /// Properties for the new edge.
1336    pub properties: Vec<(String, LogicalExpression)>,
1337    /// Input operator.
1338    pub input: Box<LogicalOperator>,
1339}
1340
1341/// Delete a node.
1342#[derive(Debug, Clone)]
1343pub struct DeleteNodeOp {
1344    /// Variable of the node to delete.
1345    pub variable: String,
1346    /// Whether to detach (delete connected edges) before deleting.
1347    pub detach: bool,
1348    /// Input operator.
1349    pub input: Box<LogicalOperator>,
1350}
1351
1352/// Delete an edge.
1353#[derive(Debug, Clone)]
1354pub struct DeleteEdgeOp {
1355    /// Variable of the edge to delete.
1356    pub variable: String,
1357    /// Input operator.
1358    pub input: Box<LogicalOperator>,
1359}
1360
1361/// Set properties on a node or edge.
1362#[derive(Debug, Clone)]
1363pub struct SetPropertyOp {
1364    /// Variable of the entity to update.
1365    pub variable: String,
1366    /// Properties to set (name -> expression).
1367    pub properties: Vec<(String, LogicalExpression)>,
1368    /// Whether to replace all properties (vs. merge).
1369    pub replace: bool,
1370    /// Whether the target variable is an edge (vs. node).
1371    pub is_edge: bool,
1372    /// Input operator.
1373    pub input: Box<LogicalOperator>,
1374}
1375
1376/// Add labels to a node.
1377#[derive(Debug, Clone)]
1378pub struct AddLabelOp {
1379    /// Variable of the node to update.
1380    pub variable: String,
1381    /// Labels to add.
1382    pub labels: Vec<String>,
1383    /// Input operator.
1384    pub input: Box<LogicalOperator>,
1385}
1386
1387/// Remove labels from a node.
1388#[derive(Debug, Clone)]
1389pub struct RemoveLabelOp {
1390    /// Variable of the node to update.
1391    pub variable: String,
1392    /// Labels to remove.
1393    pub labels: Vec<String>,
1394    /// Input operator.
1395    pub input: Box<LogicalOperator>,
1396}
1397
1398// ==================== RDF/SPARQL Operators ====================
1399
1400/// Scan RDF triples matching a pattern.
1401#[derive(Debug, Clone)]
1402pub struct TripleScanOp {
1403    /// Subject pattern (variable name or IRI).
1404    pub subject: TripleComponent,
1405    /// Predicate pattern (variable name or IRI).
1406    pub predicate: TripleComponent,
1407    /// Object pattern (variable name, IRI, or literal).
1408    pub object: TripleComponent,
1409    /// Named graph (optional).
1410    pub graph: Option<TripleComponent>,
1411    /// Input operator (for chained patterns).
1412    pub input: Option<Box<LogicalOperator>>,
1413}
1414
1415/// A component of a triple pattern.
1416#[derive(Debug, Clone)]
1417pub enum TripleComponent {
1418    /// A variable to bind.
1419    Variable(String),
1420    /// A constant IRI.
1421    Iri(String),
1422    /// A constant literal value.
1423    Literal(Value),
1424}
1425
1426/// Union of multiple result sets.
1427#[derive(Debug, Clone)]
1428pub struct UnionOp {
1429    /// Inputs to union together.
1430    pub inputs: Vec<LogicalOperator>,
1431}
1432
1433/// Set difference: rows in left that are not in right.
1434#[derive(Debug, Clone)]
1435pub struct ExceptOp {
1436    /// Left input.
1437    pub left: Box<LogicalOperator>,
1438    /// Right input (rows to exclude).
1439    pub right: Box<LogicalOperator>,
1440    /// If true, preserve duplicates (EXCEPT ALL); if false, deduplicate (EXCEPT DISTINCT).
1441    pub all: bool,
1442}
1443
1444/// Set intersection: rows common to both inputs.
1445#[derive(Debug, Clone)]
1446pub struct IntersectOp {
1447    /// Left input.
1448    pub left: Box<LogicalOperator>,
1449    /// Right input.
1450    pub right: Box<LogicalOperator>,
1451    /// If true, preserve duplicates (INTERSECT ALL); if false, deduplicate (INTERSECT DISTINCT).
1452    pub all: bool,
1453}
1454
1455/// Fallback operator: use left result if non-empty, otherwise use right.
1456#[derive(Debug, Clone)]
1457pub struct OtherwiseOp {
1458    /// Primary input (preferred).
1459    pub left: Box<LogicalOperator>,
1460    /// Fallback input (used only if left produces zero rows).
1461    pub right: Box<LogicalOperator>,
1462}
1463
1464/// Apply (lateral join): evaluate a subplan for each row of the outer input.
1465///
1466/// The subplan can reference variables bound by the outer input. Results are
1467/// concatenated (cross-product per row).
1468#[derive(Debug, Clone)]
1469pub struct ApplyOp {
1470    /// Outer input providing rows.
1471    pub input: Box<LogicalOperator>,
1472    /// Subplan to evaluate per outer row.
1473    pub subplan: Box<LogicalOperator>,
1474    /// Variables imported from the outer scope into the inner plan.
1475    /// When non-empty, the planner injects these via `ParameterState`.
1476    pub shared_variables: Vec<String>,
1477    /// When true, uses left-join semantics: outer rows with no matching inner
1478    /// rows are emitted with NULLs for the inner columns (OPTIONAL CALL).
1479    pub optional: bool,
1480}
1481
1482/// Parameter scan: leaf operator for correlated subquery inner plans.
1483///
1484/// Emits a single row containing the values injected from the outer Apply.
1485/// Column names correspond to the outer variables imported via WITH.
1486#[derive(Debug, Clone)]
1487pub struct ParameterScanOp {
1488    /// Column names for the injected parameters.
1489    pub columns: Vec<String>,
1490}
1491
1492/// Left outer join for OPTIONAL patterns.
1493#[derive(Debug, Clone)]
1494pub struct LeftJoinOp {
1495    /// Left (required) input.
1496    pub left: Box<LogicalOperator>,
1497    /// Right (optional) input.
1498    pub right: Box<LogicalOperator>,
1499    /// Optional filter condition.
1500    pub condition: Option<LogicalExpression>,
1501}
1502
1503/// Anti-join for MINUS patterns.
1504#[derive(Debug, Clone)]
1505pub struct AntiJoinOp {
1506    /// Left input (results to keep if no match on right).
1507    pub left: Box<LogicalOperator>,
1508    /// Right input (patterns to exclude).
1509    pub right: Box<LogicalOperator>,
1510}
1511
1512/// Bind a variable to an expression.
1513#[derive(Debug, Clone)]
1514pub struct BindOp {
1515    /// Expression to compute.
1516    pub expression: LogicalExpression,
1517    /// Variable to bind the result to.
1518    pub variable: String,
1519    /// Input operator.
1520    pub input: Box<LogicalOperator>,
1521}
1522
1523/// Unwind a list into individual rows.
1524///
1525/// For each input row, evaluates the expression (which should return a list)
1526/// and emits one row for each element in the list.
1527#[derive(Debug, Clone)]
1528pub struct UnwindOp {
1529    /// The list expression to unwind.
1530    pub expression: LogicalExpression,
1531    /// The variable name for each element.
1532    pub variable: String,
1533    /// Optional variable for 1-based element position (ORDINALITY).
1534    pub ordinality_var: Option<String>,
1535    /// Optional variable for 0-based element position (OFFSET).
1536    pub offset_var: Option<String>,
1537    /// Input operator.
1538    pub input: Box<LogicalOperator>,
1539}
1540
1541/// Collect grouped key-value rows into a single Map value.
1542/// Used for Gremlin `groupCount()` semantics.
1543#[derive(Debug, Clone)]
1544pub struct MapCollectOp {
1545    /// Variable holding the map key.
1546    pub key_var: String,
1547    /// Variable holding the map value.
1548    pub value_var: String,
1549    /// Output variable alias.
1550    pub alias: String,
1551    /// Input operator (typically a grouped aggregate).
1552    pub input: Box<LogicalOperator>,
1553}
1554
1555/// Merge a pattern (match or create).
1556///
1557/// MERGE tries to match a pattern in the graph. If found, returns the existing
1558/// elements (optionally applying ON MATCH SET). If not found, creates the pattern
1559/// (optionally applying ON CREATE SET).
1560#[derive(Debug, Clone)]
1561pub struct MergeOp {
1562    /// The node to merge.
1563    pub variable: String,
1564    /// Labels to match/create.
1565    pub labels: Vec<String>,
1566    /// Properties that must match (used for both matching and creation).
1567    pub match_properties: Vec<(String, LogicalExpression)>,
1568    /// Properties to set on CREATE.
1569    pub on_create: Vec<(String, LogicalExpression)>,
1570    /// Properties to set on MATCH.
1571    pub on_match: Vec<(String, LogicalExpression)>,
1572    /// Input operator.
1573    pub input: Box<LogicalOperator>,
1574}
1575
1576/// Merge a relationship pattern (match or create between two bound nodes).
1577///
1578/// MERGE on a relationship tries to find an existing relationship of the given type
1579/// between the source and target nodes. If found, returns the existing relationship
1580/// (optionally applying ON MATCH SET). If not found, creates it (optionally applying
1581/// ON CREATE SET).
1582#[derive(Debug, Clone)]
1583pub struct MergeRelationshipOp {
1584    /// Variable to bind the relationship to.
1585    pub variable: String,
1586    /// Source node variable (must already be bound).
1587    pub source_variable: String,
1588    /// Target node variable (must already be bound).
1589    pub target_variable: String,
1590    /// Relationship type.
1591    pub edge_type: String,
1592    /// Properties that must match (used for both matching and creation).
1593    pub match_properties: Vec<(String, LogicalExpression)>,
1594    /// Properties to set on CREATE.
1595    pub on_create: Vec<(String, LogicalExpression)>,
1596    /// Properties to set on MATCH.
1597    pub on_match: Vec<(String, LogicalExpression)>,
1598    /// Input operator.
1599    pub input: Box<LogicalOperator>,
1600}
1601
1602/// Find shortest path between two nodes.
1603///
1604/// This operator uses Dijkstra's algorithm to find the shortest path(s)
1605/// between a source node and a target node, optionally filtered by edge type.
1606#[derive(Debug, Clone)]
1607pub struct ShortestPathOp {
1608    /// Input operator providing source/target nodes.
1609    pub input: Box<LogicalOperator>,
1610    /// Variable name for the source node.
1611    pub source_var: String,
1612    /// Variable name for the target node.
1613    pub target_var: String,
1614    /// Edge type filter (empty = match all types, multiple = match any).
1615    pub edge_types: Vec<String>,
1616    /// Direction of edge traversal.
1617    pub direction: ExpandDirection,
1618    /// Variable name to bind the path result.
1619    pub path_alias: String,
1620    /// Whether to find all shortest paths (vs. just one).
1621    pub all_paths: bool,
1622}
1623
1624// ==================== SPARQL Update Operators ====================
1625
1626/// Insert RDF triples.
1627#[derive(Debug, Clone)]
1628pub struct InsertTripleOp {
1629    /// Subject of the triple.
1630    pub subject: TripleComponent,
1631    /// Predicate of the triple.
1632    pub predicate: TripleComponent,
1633    /// Object of the triple.
1634    pub object: TripleComponent,
1635    /// Named graph (optional).
1636    pub graph: Option<String>,
1637    /// Input operator (provides variable bindings).
1638    pub input: Option<Box<LogicalOperator>>,
1639}
1640
1641/// Delete RDF triples.
1642#[derive(Debug, Clone)]
1643pub struct DeleteTripleOp {
1644    /// Subject pattern.
1645    pub subject: TripleComponent,
1646    /// Predicate pattern.
1647    pub predicate: TripleComponent,
1648    /// Object pattern.
1649    pub object: TripleComponent,
1650    /// Named graph (optional).
1651    pub graph: Option<String>,
1652    /// Input operator (provides variable bindings).
1653    pub input: Option<Box<LogicalOperator>>,
1654}
1655
1656/// SPARQL MODIFY operation (DELETE/INSERT WHERE).
1657///
1658/// Per SPARQL 1.1 Update spec, this operator:
1659/// 1. Evaluates the WHERE clause once to get bindings
1660/// 2. Applies DELETE templates using those bindings
1661/// 3. Applies INSERT templates using the SAME bindings
1662///
1663/// This ensures DELETE and INSERT see consistent data.
1664#[derive(Debug, Clone)]
1665pub struct ModifyOp {
1666    /// DELETE triple templates (patterns with variables).
1667    pub delete_templates: Vec<TripleTemplate>,
1668    /// INSERT triple templates (patterns with variables).
1669    pub insert_templates: Vec<TripleTemplate>,
1670    /// WHERE clause that provides variable bindings.
1671    pub where_clause: Box<LogicalOperator>,
1672    /// Named graph context (for WITH clause).
1673    pub graph: Option<String>,
1674}
1675
1676/// A triple template for DELETE/INSERT operations.
1677#[derive(Debug, Clone)]
1678pub struct TripleTemplate {
1679    /// Subject (may be a variable).
1680    pub subject: TripleComponent,
1681    /// Predicate (may be a variable).
1682    pub predicate: TripleComponent,
1683    /// Object (may be a variable or literal).
1684    pub object: TripleComponent,
1685    /// Named graph (optional).
1686    pub graph: Option<String>,
1687}
1688
1689/// Clear all triples from a graph.
1690#[derive(Debug, Clone)]
1691pub struct ClearGraphOp {
1692    /// Target graph (None = default graph, Some("") = all named, Some(iri) = specific graph).
1693    pub graph: Option<String>,
1694    /// Whether to silently ignore errors.
1695    pub silent: bool,
1696}
1697
1698/// Create a new named graph.
1699#[derive(Debug, Clone)]
1700pub struct CreateGraphOp {
1701    /// IRI of the graph to create.
1702    pub graph: String,
1703    /// Whether to silently ignore if graph already exists.
1704    pub silent: bool,
1705}
1706
1707/// Drop (remove) a named graph.
1708#[derive(Debug, Clone)]
1709pub struct DropGraphOp {
1710    /// Target graph (None = default graph).
1711    pub graph: Option<String>,
1712    /// Whether to silently ignore errors.
1713    pub silent: bool,
1714}
1715
1716/// Load data from a URL into a graph.
1717#[derive(Debug, Clone)]
1718pub struct LoadGraphOp {
1719    /// Source URL to load data from.
1720    pub source: String,
1721    /// Destination graph (None = default graph).
1722    pub destination: Option<String>,
1723    /// Whether to silently ignore errors.
1724    pub silent: bool,
1725}
1726
1727/// Copy triples from one graph to another.
1728#[derive(Debug, Clone)]
1729pub struct CopyGraphOp {
1730    /// Source graph.
1731    pub source: Option<String>,
1732    /// Destination graph.
1733    pub destination: Option<String>,
1734    /// Whether to silently ignore errors.
1735    pub silent: bool,
1736}
1737
1738/// Move triples from one graph to another.
1739#[derive(Debug, Clone)]
1740pub struct MoveGraphOp {
1741    /// Source graph.
1742    pub source: Option<String>,
1743    /// Destination graph.
1744    pub destination: Option<String>,
1745    /// Whether to silently ignore errors.
1746    pub silent: bool,
1747}
1748
1749/// Add (merge) triples from one graph to another.
1750#[derive(Debug, Clone)]
1751pub struct AddGraphOp {
1752    /// Source graph.
1753    pub source: Option<String>,
1754    /// Destination graph.
1755    pub destination: Option<String>,
1756    /// Whether to silently ignore errors.
1757    pub silent: bool,
1758}
1759
1760// ==================== Vector Search Operators ====================
1761
1762/// Vector similarity scan operation.
1763///
1764/// Performs approximate nearest neighbor search using a vector index (HNSW)
1765/// or brute-force search for small datasets. Returns nodes/edges whose
1766/// embeddings are similar to the query vector.
1767///
1768/// # Example GQL
1769///
1770/// ```gql
1771/// MATCH (m:Movie)
1772/// WHERE vector_similarity(m.embedding, $query_vector) > 0.8
1773/// RETURN m.title
1774/// ```
1775#[derive(Debug, Clone)]
1776pub struct VectorScanOp {
1777    /// Variable name to bind matching entities to.
1778    pub variable: String,
1779    /// Name of the vector index to use (None = brute-force).
1780    pub index_name: Option<String>,
1781    /// Property containing the vector embedding.
1782    pub property: String,
1783    /// Optional label filter (scan only nodes with this label).
1784    pub label: Option<String>,
1785    /// The query vector expression.
1786    pub query_vector: LogicalExpression,
1787    /// Number of nearest neighbors to return.
1788    pub k: usize,
1789    /// Distance metric (None = use index default, typically cosine).
1790    pub metric: Option<VectorMetric>,
1791    /// Minimum similarity threshold (filters results below this).
1792    pub min_similarity: Option<f32>,
1793    /// Maximum distance threshold (filters results above this).
1794    pub max_distance: Option<f32>,
1795    /// Input operator (for hybrid queries combining graph + vector).
1796    pub input: Option<Box<LogicalOperator>>,
1797}
1798
1799/// Vector distance/similarity metric for vector scan operations.
1800#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1801pub enum VectorMetric {
1802    /// Cosine similarity (1 - cosine_distance). Best for normalized embeddings.
1803    Cosine,
1804    /// Euclidean (L2) distance. Best when magnitude matters.
1805    Euclidean,
1806    /// Dot product. Best for maximum inner product search.
1807    DotProduct,
1808    /// Manhattan (L1) distance. Less sensitive to outliers.
1809    Manhattan,
1810}
1811
1812/// Join graph patterns with vector similarity search.
1813///
1814/// This operator takes entities from the left input and computes vector
1815/// similarity against a query vector, outputting (entity, distance) pairs.
1816///
1817/// # Use Cases
1818///
1819/// 1. **Hybrid graph + vector queries**: Find similar nodes after graph traversal
1820/// 2. **Aggregated embeddings**: Use AVG(embeddings) as query vector
1821/// 3. **Filtering by similarity**: Join with threshold-based filtering
1822///
1823/// # Example
1824///
1825/// ```gql
1826/// // Find movies similar to what the user liked
1827/// MATCH (u:User {id: $user_id})-[:LIKED]->(liked:Movie)
1828/// WITH avg(liked.embedding) AS user_taste
1829/// VECTOR JOIN (m:Movie) ON m.embedding
1830/// WHERE vector_similarity(m.embedding, user_taste) > 0.7
1831/// RETURN m.title
1832/// ```
1833#[derive(Debug, Clone)]
1834pub struct VectorJoinOp {
1835    /// Input operator providing entities to match against.
1836    pub input: Box<LogicalOperator>,
1837    /// Variable from input to extract vectors from (for entity-to-entity similarity).
1838    /// If None, uses `query_vector` directly.
1839    pub left_vector_variable: Option<String>,
1840    /// Property containing the left vector (used with `left_vector_variable`).
1841    pub left_property: Option<String>,
1842    /// The query vector expression (constant or computed).
1843    pub query_vector: LogicalExpression,
1844    /// Variable name to bind the right-side matching entities.
1845    pub right_variable: String,
1846    /// Property containing the right-side vector embeddings.
1847    pub right_property: String,
1848    /// Optional label filter for right-side entities.
1849    pub right_label: Option<String>,
1850    /// Name of vector index on right side (None = brute-force).
1851    pub index_name: Option<String>,
1852    /// Number of nearest neighbors per left-side entity.
1853    pub k: usize,
1854    /// Distance metric.
1855    pub metric: Option<VectorMetric>,
1856    /// Minimum similarity threshold.
1857    pub min_similarity: Option<f32>,
1858    /// Maximum distance threshold.
1859    pub max_distance: Option<f32>,
1860    /// Variable to bind the distance/similarity score.
1861    pub score_variable: Option<String>,
1862}
1863
1864/// Return results (terminal operator).
1865#[derive(Debug, Clone)]
1866pub struct ReturnOp {
1867    /// Items to return.
1868    pub items: Vec<ReturnItem>,
1869    /// Whether to return distinct results.
1870    pub distinct: bool,
1871    /// Input operator.
1872    pub input: Box<LogicalOperator>,
1873}
1874
1875/// A single return item.
1876#[derive(Debug, Clone)]
1877pub struct ReturnItem {
1878    /// Expression to return.
1879    pub expression: LogicalExpression,
1880    /// Alias for the result column.
1881    pub alias: Option<String>,
1882}
1883
1884/// Define a property graph schema (SQL/PGQ DDL).
1885#[derive(Debug, Clone)]
1886pub struct CreatePropertyGraphOp {
1887    /// Graph name.
1888    pub name: String,
1889    /// Node table schemas (label name + column definitions).
1890    pub node_tables: Vec<PropertyGraphNodeTable>,
1891    /// Edge table schemas (type name + column definitions + references).
1892    pub edge_tables: Vec<PropertyGraphEdgeTable>,
1893}
1894
1895/// A node table in a property graph definition.
1896#[derive(Debug, Clone)]
1897pub struct PropertyGraphNodeTable {
1898    /// Table name (maps to a node label).
1899    pub name: String,
1900    /// Column definitions as (name, type_name) pairs.
1901    pub columns: Vec<(String, String)>,
1902}
1903
1904/// An edge table in a property graph definition.
1905#[derive(Debug, Clone)]
1906pub struct PropertyGraphEdgeTable {
1907    /// Table name (maps to an edge type).
1908    pub name: String,
1909    /// Column definitions as (name, type_name) pairs.
1910    pub columns: Vec<(String, String)>,
1911    /// Source node table name.
1912    pub source_table: String,
1913    /// Target node table name.
1914    pub target_table: String,
1915}
1916
1917// ==================== Procedure Call Types ====================
1918
1919/// A CALL procedure operation.
1920///
1921/// ```text
1922/// CALL grafeo.pagerank({damping: 0.85}) YIELD nodeId, score
1923/// ```
1924#[derive(Debug, Clone)]
1925pub struct CallProcedureOp {
1926    /// Dotted procedure name, e.g. `["grafeo", "pagerank"]`.
1927    pub name: Vec<String>,
1928    /// Argument expressions (constants in Phase 1).
1929    pub arguments: Vec<LogicalExpression>,
1930    /// Optional YIELD clause: which columns to expose + aliases.
1931    pub yield_items: Option<Vec<ProcedureYield>>,
1932}
1933
1934/// A single YIELD item in a procedure call.
1935#[derive(Debug, Clone)]
1936pub struct ProcedureYield {
1937    /// Column name from the procedure result.
1938    pub field_name: String,
1939    /// Optional alias (YIELD score AS rank).
1940    pub alias: Option<String>,
1941}
1942
1943/// Re-export format enum from the physical operator.
1944pub use grafeo_core::execution::operators::LoadDataFormat;
1945
1946/// LOAD DATA operator: reads a file and produces rows.
1947///
1948/// With headers (CSV), each row is bound as a `Value::Map` with column names as keys.
1949/// Without headers (CSV), each row is bound as a `Value::List` of string values.
1950/// JSONL always produces `Value::Map`. Parquet always produces `Value::Map`.
1951#[derive(Debug, Clone)]
1952pub struct LoadDataOp {
1953    /// File format.
1954    pub format: LoadDataFormat,
1955    /// Whether the file has a header row (CSV only, ignored for JSONL/Parquet).
1956    pub with_headers: bool,
1957    /// File path (local filesystem).
1958    pub path: String,
1959    /// Variable name to bind each row to.
1960    pub variable: String,
1961    /// Field separator character (CSV only, default: comma).
1962    pub field_terminator: Option<char>,
1963}
1964
1965/// A logical expression.
1966#[derive(Debug, Clone)]
1967pub enum LogicalExpression {
1968    /// A literal value.
1969    Literal(Value),
1970
1971    /// A variable reference.
1972    Variable(String),
1973
1974    /// Property access (e.g., n.name).
1975    Property {
1976        /// The variable to access.
1977        variable: String,
1978        /// The property name.
1979        property: String,
1980    },
1981
1982    /// Binary operation.
1983    Binary {
1984        /// Left operand.
1985        left: Box<LogicalExpression>,
1986        /// Operator.
1987        op: BinaryOp,
1988        /// Right operand.
1989        right: Box<LogicalExpression>,
1990    },
1991
1992    /// Unary operation.
1993    Unary {
1994        /// Operator.
1995        op: UnaryOp,
1996        /// Operand.
1997        operand: Box<LogicalExpression>,
1998    },
1999
2000    /// Function call.
2001    FunctionCall {
2002        /// Function name.
2003        name: String,
2004        /// Arguments.
2005        args: Vec<LogicalExpression>,
2006        /// Whether DISTINCT is applied (e.g., COUNT(DISTINCT x)).
2007        distinct: bool,
2008    },
2009
2010    /// List literal.
2011    List(Vec<LogicalExpression>),
2012
2013    /// Map literal (e.g., {name: 'Alix', age: 30}).
2014    Map(Vec<(String, LogicalExpression)>),
2015
2016    /// Index access (e.g., `list[0]`).
2017    IndexAccess {
2018        /// The base expression (typically a list or string).
2019        base: Box<LogicalExpression>,
2020        /// The index expression.
2021        index: Box<LogicalExpression>,
2022    },
2023
2024    /// Slice access (e.g., list[1..3]).
2025    SliceAccess {
2026        /// The base expression (typically a list or string).
2027        base: Box<LogicalExpression>,
2028        /// Start index (None means from beginning).
2029        start: Option<Box<LogicalExpression>>,
2030        /// End index (None means to end).
2031        end: Option<Box<LogicalExpression>>,
2032    },
2033
2034    /// CASE expression.
2035    Case {
2036        /// Test expression (for simple CASE).
2037        operand: Option<Box<LogicalExpression>>,
2038        /// WHEN clauses.
2039        when_clauses: Vec<(LogicalExpression, LogicalExpression)>,
2040        /// ELSE clause.
2041        else_clause: Option<Box<LogicalExpression>>,
2042    },
2043
2044    /// Parameter reference.
2045    Parameter(String),
2046
2047    /// Labels of a node.
2048    Labels(String),
2049
2050    /// Type of an edge.
2051    Type(String),
2052
2053    /// ID of a node or edge.
2054    Id(String),
2055
2056    /// List comprehension: [x IN list WHERE predicate | expression]
2057    ListComprehension {
2058        /// Variable name for each element.
2059        variable: String,
2060        /// The source list expression.
2061        list_expr: Box<LogicalExpression>,
2062        /// Optional filter predicate.
2063        filter_expr: Option<Box<LogicalExpression>>,
2064        /// The mapping expression for each element.
2065        map_expr: Box<LogicalExpression>,
2066    },
2067
2068    /// List predicate: all/any/none/single(x IN list WHERE pred).
2069    ListPredicate {
2070        /// The kind of list predicate.
2071        kind: ListPredicateKind,
2072        /// The iteration variable name.
2073        variable: String,
2074        /// The source list expression.
2075        list_expr: Box<LogicalExpression>,
2076        /// The predicate to test for each element.
2077        predicate: Box<LogicalExpression>,
2078    },
2079
2080    /// EXISTS subquery.
2081    ExistsSubquery(Box<LogicalOperator>),
2082
2083    /// COUNT subquery.
2084    CountSubquery(Box<LogicalOperator>),
2085
2086    /// VALUE subquery: returns scalar value from first row of inner query.
2087    ValueSubquery(Box<LogicalOperator>),
2088
2089    /// Map projection: `node { .prop1, .prop2, key: expr, .* }`.
2090    MapProjection {
2091        /// The base variable name.
2092        base: String,
2093        /// Projection entries (property selectors, literal entries, all-properties).
2094        entries: Vec<MapProjectionEntry>,
2095    },
2096
2097    /// reduce() accumulator: `reduce(acc = init, x IN list | expr)`.
2098    Reduce {
2099        /// Accumulator variable name.
2100        accumulator: String,
2101        /// Initial value for the accumulator.
2102        initial: Box<LogicalExpression>,
2103        /// Iteration variable name.
2104        variable: String,
2105        /// List to iterate over.
2106        list: Box<LogicalExpression>,
2107        /// Body expression evaluated per iteration (references both accumulator and variable).
2108        expression: Box<LogicalExpression>,
2109    },
2110
2111    /// Pattern comprehension: `[(pattern) WHERE pred | expr]`.
2112    ///
2113    /// Executes the inner subplan, evaluates the projection for each row,
2114    /// and collects the results into a list.
2115    PatternComprehension {
2116        /// The subplan produced by translating the pattern (+optional WHERE).
2117        subplan: Box<LogicalOperator>,
2118        /// The projection expression evaluated for each match.
2119        projection: Box<LogicalExpression>,
2120    },
2121}
2122
2123/// An entry in a map projection.
2124#[derive(Debug, Clone)]
2125pub enum MapProjectionEntry {
2126    /// `.propertyName`: shorthand for `propertyName: base.propertyName`.
2127    PropertySelector(String),
2128    /// `key: expression`: explicit key-value pair.
2129    LiteralEntry(String, LogicalExpression),
2130    /// `.*`: include all properties of the base entity.
2131    AllProperties,
2132}
2133
2134/// The kind of list predicate function.
2135#[derive(Debug, Clone, PartialEq, Eq)]
2136pub enum ListPredicateKind {
2137    /// all(x IN list WHERE pred): true if pred holds for every element.
2138    All,
2139    /// any(x IN list WHERE pred): true if pred holds for at least one element.
2140    Any,
2141    /// none(x IN list WHERE pred): true if pred holds for no element.
2142    None,
2143    /// single(x IN list WHERE pred): true if pred holds for exactly one element.
2144    Single,
2145}
2146
2147/// Binary operator.
2148#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2149pub enum BinaryOp {
2150    /// Equality comparison (=).
2151    Eq,
2152    /// Inequality comparison (<>).
2153    Ne,
2154    /// Less than (<).
2155    Lt,
2156    /// Less than or equal (<=).
2157    Le,
2158    /// Greater than (>).
2159    Gt,
2160    /// Greater than or equal (>=).
2161    Ge,
2162
2163    /// Logical AND.
2164    And,
2165    /// Logical OR.
2166    Or,
2167    /// Logical XOR.
2168    Xor,
2169
2170    /// Addition (+).
2171    Add,
2172    /// Subtraction (-).
2173    Sub,
2174    /// Multiplication (*).
2175    Mul,
2176    /// Division (/).
2177    Div,
2178    /// Modulo (%).
2179    Mod,
2180
2181    /// String concatenation.
2182    Concat,
2183    /// String starts with.
2184    StartsWith,
2185    /// String ends with.
2186    EndsWith,
2187    /// String contains.
2188    Contains,
2189
2190    /// Collection membership (IN).
2191    In,
2192    /// Pattern matching (LIKE).
2193    Like,
2194    /// Regex matching (=~).
2195    Regex,
2196    /// Power/exponentiation (^).
2197    Pow,
2198}
2199
2200/// Unary operator.
2201#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2202pub enum UnaryOp {
2203    /// Logical NOT.
2204    Not,
2205    /// Numeric negation.
2206    Neg,
2207    /// IS NULL check.
2208    IsNull,
2209    /// IS NOT NULL check.
2210    IsNotNull,
2211}
2212
2213#[cfg(test)]
2214mod tests {
2215    use super::*;
2216
2217    #[test]
2218    fn test_simple_node_scan_plan() {
2219        let plan = LogicalPlan::new(LogicalOperator::Return(ReturnOp {
2220            items: vec![ReturnItem {
2221                expression: LogicalExpression::Variable("n".into()),
2222                alias: None,
2223            }],
2224            distinct: false,
2225            input: Box::new(LogicalOperator::NodeScan(NodeScanOp {
2226                variable: "n".into(),
2227                label: Some("Person".into()),
2228                input: None,
2229            })),
2230        }));
2231
2232        // Verify structure
2233        if let LogicalOperator::Return(ret) = &plan.root {
2234            assert_eq!(ret.items.len(), 1);
2235            assert!(!ret.distinct);
2236            if let LogicalOperator::NodeScan(scan) = ret.input.as_ref() {
2237                assert_eq!(scan.variable, "n");
2238                assert_eq!(scan.label, Some("Person".into()));
2239            } else {
2240                panic!("Expected NodeScan");
2241            }
2242        } else {
2243            panic!("Expected Return");
2244        }
2245    }
2246
2247    #[test]
2248    fn test_filter_plan() {
2249        let plan = LogicalPlan::new(LogicalOperator::Return(ReturnOp {
2250            items: vec![ReturnItem {
2251                expression: LogicalExpression::Property {
2252                    variable: "n".into(),
2253                    property: "name".into(),
2254                },
2255                alias: Some("name".into()),
2256            }],
2257            distinct: false,
2258            input: Box::new(LogicalOperator::Filter(FilterOp {
2259                predicate: LogicalExpression::Binary {
2260                    left: Box::new(LogicalExpression::Property {
2261                        variable: "n".into(),
2262                        property: "age".into(),
2263                    }),
2264                    op: BinaryOp::Gt,
2265                    right: Box::new(LogicalExpression::Literal(Value::Int64(30))),
2266                },
2267                input: Box::new(LogicalOperator::NodeScan(NodeScanOp {
2268                    variable: "n".into(),
2269                    label: Some("Person".into()),
2270                    input: None,
2271                })),
2272                pushdown_hint: None,
2273            })),
2274        }));
2275
2276        if let LogicalOperator::Return(ret) = &plan.root {
2277            if let LogicalOperator::Filter(filter) = ret.input.as_ref() {
2278                if let LogicalExpression::Binary { op, .. } = &filter.predicate {
2279                    assert_eq!(*op, BinaryOp::Gt);
2280                } else {
2281                    panic!("Expected Binary expression");
2282                }
2283            } else {
2284                panic!("Expected Filter");
2285            }
2286        } else {
2287            panic!("Expected Return");
2288        }
2289    }
2290}