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 CSV file, producing one row per CSV record.
285 LoadCsv(LoadCsvOp),
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::LoadCsv(_) => 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::LoadCsv(_) => 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::LoadCsv(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 let _ = writeln!(out, "{indent}LeftJoin");
741 op.left.fmt_tree(out, depth + 1);
742 op.right.fmt_tree(out, depth + 1);
743 }
744 Self::AntiJoin(op) => {
745 let _ = writeln!(out, "{indent}AntiJoin");
746 op.left.fmt_tree(out, depth + 1);
747 op.right.fmt_tree(out, depth + 1);
748 }
749 Self::Unwind(op) => {
750 let _ = writeln!(out, "{indent}Unwind ({var})", var = op.variable);
751 op.input.fmt_tree(out, depth + 1);
752 }
753 Self::Bind(op) => {
754 let _ = writeln!(out, "{indent}Bind ({var})", var = op.variable);
755 op.input.fmt_tree(out, depth + 1);
756 }
757 Self::MapCollect(op) => {
758 let _ = writeln!(
759 out,
760 "{indent}MapCollect ({key} -> {val} AS {alias})",
761 key = op.key_var,
762 val = op.value_var,
763 alias = op.alias
764 );
765 op.input.fmt_tree(out, depth + 1);
766 }
767 Self::Apply(op) => {
768 let _ = writeln!(out, "{indent}Apply");
769 op.input.fmt_tree(out, depth + 1);
770 op.subplan.fmt_tree(out, depth + 1);
771 }
772 Self::Except(op) => {
773 let all = if op.all { " ALL" } else { "" };
774 let _ = writeln!(out, "{indent}Except{all}");
775 op.left.fmt_tree(out, depth + 1);
776 op.right.fmt_tree(out, depth + 1);
777 }
778 Self::Intersect(op) => {
779 let all = if op.all { " ALL" } else { "" };
780 let _ = writeln!(out, "{indent}Intersect{all}");
781 op.left.fmt_tree(out, depth + 1);
782 op.right.fmt_tree(out, depth + 1);
783 }
784 Self::Otherwise(op) => {
785 let _ = writeln!(out, "{indent}Otherwise");
786 op.left.fmt_tree(out, depth + 1);
787 op.right.fmt_tree(out, depth + 1);
788 }
789 Self::ShortestPath(op) => {
790 let _ = writeln!(
791 out,
792 "{indent}ShortestPath ({from} -> {to})",
793 from = op.source_var,
794 to = op.target_var
795 );
796 op.input.fmt_tree(out, depth + 1);
797 }
798 Self::Merge(op) => {
799 let _ = writeln!(out, "{indent}Merge ({var})", var = op.variable);
800 op.input.fmt_tree(out, depth + 1);
801 }
802 Self::MergeRelationship(op) => {
803 let _ = writeln!(out, "{indent}MergeRelationship ({var})", var = op.variable);
804 op.input.fmt_tree(out, depth + 1);
805 }
806 Self::CreateNode(op) => {
807 let labels = op.labels.join(":");
808 let _ = writeln!(
809 out,
810 "{indent}CreateNode ({var}:{labels})",
811 var = op.variable
812 );
813 if let Some(input) = &op.input {
814 input.fmt_tree(out, depth + 1);
815 }
816 }
817 Self::CreateEdge(op) => {
818 let var = op.variable.as_deref().unwrap_or("?");
819 let _ = writeln!(
820 out,
821 "{indent}CreateEdge ({from})-[{var}:{ty}]->({to})",
822 from = op.from_variable,
823 ty = op.edge_type,
824 to = op.to_variable
825 );
826 op.input.fmt_tree(out, depth + 1);
827 }
828 Self::DeleteNode(op) => {
829 let _ = writeln!(out, "{indent}DeleteNode ({var})", var = op.variable);
830 op.input.fmt_tree(out, depth + 1);
831 }
832 Self::DeleteEdge(op) => {
833 let _ = writeln!(out, "{indent}DeleteEdge ({var})", var = op.variable);
834 op.input.fmt_tree(out, depth + 1);
835 }
836 Self::SetProperty(op) => {
837 let props: Vec<String> = op
838 .properties
839 .iter()
840 .map(|(k, _)| format!("{}.{k}", op.variable))
841 .collect();
842 let _ = writeln!(
843 out,
844 "{indent}SetProperty ({props})",
845 props = props.join(", ")
846 );
847 op.input.fmt_tree(out, depth + 1);
848 }
849 Self::AddLabel(op) => {
850 let labels = op.labels.join(":");
851 let _ = writeln!(out, "{indent}AddLabel ({var}:{labels})", var = op.variable);
852 op.input.fmt_tree(out, depth + 1);
853 }
854 Self::RemoveLabel(op) => {
855 let labels = op.labels.join(":");
856 let _ = writeln!(
857 out,
858 "{indent}RemoveLabel ({var}:{labels})",
859 var = op.variable
860 );
861 op.input.fmt_tree(out, depth + 1);
862 }
863 Self::CallProcedure(op) => {
864 let _ = writeln!(
865 out,
866 "{indent}CallProcedure ({name})",
867 name = op.name.join(".")
868 );
869 }
870 Self::LoadCsv(op) => {
871 let headers = if op.with_headers { " WITH HEADERS" } else { "" };
872 let _ = writeln!(
873 out,
874 "{indent}LoadCsv{headers} ('{path}' AS {var})",
875 path = op.path,
876 var = op.variable,
877 );
878 }
879 Self::TripleScan(op) => {
880 let _ = writeln!(
881 out,
882 "{indent}TripleScan ({s} {p} {o})",
883 s = fmt_triple_component(&op.subject),
884 p = fmt_triple_component(&op.predicate),
885 o = fmt_triple_component(&op.object)
886 );
887 if let Some(input) = &op.input {
888 input.fmt_tree(out, depth + 1);
889 }
890 }
891 Self::Empty => {
892 let _ = writeln!(out, "{indent}Empty");
893 }
894 // Remaining operators: show a simple name
895 _ => {
896 let _ = writeln!(out, "{indent}{:?}", std::mem::discriminant(self));
897 }
898 }
899 }
900}
901
902/// Format a logical expression compactly for EXPLAIN output.
903fn fmt_expr(expr: &LogicalExpression) -> String {
904 match expr {
905 LogicalExpression::Variable(name) => name.clone(),
906 LogicalExpression::Property { variable, property } => format!("{variable}.{property}"),
907 LogicalExpression::Literal(val) => format!("{val}"),
908 LogicalExpression::Binary { left, op, right } => {
909 format!("{} {op:?} {}", fmt_expr(left), fmt_expr(right))
910 }
911 LogicalExpression::Unary { op, operand } => {
912 format!("{op:?} {}", fmt_expr(operand))
913 }
914 LogicalExpression::FunctionCall { name, args, .. } => {
915 let arg_strs: Vec<String> = args.iter().map(fmt_expr).collect();
916 format!("{name}({})", arg_strs.join(", "))
917 }
918 _ => format!("{expr:?}"),
919 }
920}
921
922/// Format a triple component for EXPLAIN output.
923fn fmt_triple_component(comp: &TripleComponent) -> String {
924 match comp {
925 TripleComponent::Variable(name) => format!("?{name}"),
926 TripleComponent::Iri(iri) => format!("<{iri}>"),
927 TripleComponent::Literal(val) => format!("{val}"),
928 }
929}
930
931/// Scan nodes from the graph.
932#[derive(Debug, Clone)]
933pub struct NodeScanOp {
934 /// Variable name to bind the node to.
935 pub variable: String,
936 /// Optional label filter.
937 pub label: Option<String>,
938 /// Child operator (if any, for chained patterns).
939 pub input: Option<Box<LogicalOperator>>,
940}
941
942/// Scan edges from the graph.
943#[derive(Debug, Clone)]
944pub struct EdgeScanOp {
945 /// Variable name to bind the edge to.
946 pub variable: String,
947 /// Edge type filter (empty = match all types).
948 pub edge_types: Vec<String>,
949 /// Child operator (if any).
950 pub input: Option<Box<LogicalOperator>>,
951}
952
953/// Path traversal mode for variable-length expansion.
954#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
955pub enum PathMode {
956 /// Allows repeated nodes and edges (default).
957 #[default]
958 Walk,
959 /// No repeated edges.
960 Trail,
961 /// No repeated nodes except endpoints.
962 Simple,
963 /// No repeated nodes at all.
964 Acyclic,
965}
966
967/// Expand from nodes to their neighbors.
968#[derive(Debug, Clone)]
969pub struct ExpandOp {
970 /// Source node variable.
971 pub from_variable: String,
972 /// Target node variable to bind.
973 pub to_variable: String,
974 /// Edge variable to bind (optional).
975 pub edge_variable: Option<String>,
976 /// Direction of expansion.
977 pub direction: ExpandDirection,
978 /// Edge type filter (empty = match all types, multiple = match any).
979 pub edge_types: Vec<String>,
980 /// Minimum hops (for variable-length patterns).
981 pub min_hops: u32,
982 /// Maximum hops (for variable-length patterns).
983 pub max_hops: Option<u32>,
984 /// Input operator.
985 pub input: Box<LogicalOperator>,
986 /// Path alias for variable-length patterns (e.g., `p` in `p = (a)-[*1..3]->(b)`).
987 /// When set, a path length column will be output under this name.
988 pub path_alias: Option<String>,
989 /// Path traversal mode (WALK, TRAIL, SIMPLE, ACYCLIC).
990 pub path_mode: PathMode,
991}
992
993/// Direction for edge expansion.
994#[derive(Debug, Clone, Copy, PartialEq, Eq)]
995pub enum ExpandDirection {
996 /// Follow outgoing edges.
997 Outgoing,
998 /// Follow incoming edges.
999 Incoming,
1000 /// Follow edges in either direction.
1001 Both,
1002}
1003
1004/// Join two inputs.
1005#[derive(Debug, Clone)]
1006pub struct JoinOp {
1007 /// Left input.
1008 pub left: Box<LogicalOperator>,
1009 /// Right input.
1010 pub right: Box<LogicalOperator>,
1011 /// Join type.
1012 pub join_type: JoinType,
1013 /// Join conditions.
1014 pub conditions: Vec<JoinCondition>,
1015}
1016
1017/// Join type.
1018#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1019pub enum JoinType {
1020 /// Inner join.
1021 Inner,
1022 /// Left outer join.
1023 Left,
1024 /// Right outer join.
1025 Right,
1026 /// Full outer join.
1027 Full,
1028 /// Cross join (Cartesian product).
1029 Cross,
1030 /// Semi join (returns left rows with matching right rows).
1031 Semi,
1032 /// Anti join (returns left rows without matching right rows).
1033 Anti,
1034}
1035
1036/// A join condition.
1037#[derive(Debug, Clone)]
1038pub struct JoinCondition {
1039 /// Left expression.
1040 pub left: LogicalExpression,
1041 /// Right expression.
1042 pub right: LogicalExpression,
1043}
1044
1045/// Multi-way join for worst-case optimal joins (leapfrog).
1046///
1047/// Unlike binary `JoinOp`, this joins 3+ relations simultaneously
1048/// using the leapfrog trie join algorithm. Preferred for cyclic patterns
1049/// (triangles, cliques) where cascading binary joins hit O(N^2).
1050#[derive(Debug, Clone)]
1051pub struct MultiWayJoinOp {
1052 /// Input relations (one per relation in the join).
1053 pub inputs: Vec<LogicalOperator>,
1054 /// All pairwise join conditions.
1055 pub conditions: Vec<JoinCondition>,
1056 /// Variables shared across multiple inputs (intersection keys).
1057 pub shared_variables: Vec<String>,
1058}
1059
1060/// Aggregate with grouping.
1061#[derive(Debug, Clone)]
1062pub struct AggregateOp {
1063 /// Group by expressions.
1064 pub group_by: Vec<LogicalExpression>,
1065 /// Aggregate functions.
1066 pub aggregates: Vec<AggregateExpr>,
1067 /// Input operator.
1068 pub input: Box<LogicalOperator>,
1069 /// HAVING clause filter (applied after aggregation).
1070 pub having: Option<LogicalExpression>,
1071}
1072
1073/// Whether a horizontal aggregate operates on edges or nodes.
1074#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1075pub enum EntityKind {
1076 /// Aggregate over edges in a path.
1077 Edge,
1078 /// Aggregate over nodes in a path.
1079 Node,
1080}
1081
1082/// Per-row aggregation over a list-valued column (horizontal aggregation, GE09).
1083///
1084/// For each input row, reads a list of entity IDs from `list_column`, accesses
1085/// `property` on each entity, computes the aggregate, and emits the scalar result.
1086#[derive(Debug, Clone)]
1087pub struct HorizontalAggregateOp {
1088 /// The list column name (e.g., `_path_edges_p`).
1089 pub list_column: String,
1090 /// Whether the list contains edge IDs or node IDs.
1091 pub entity_kind: EntityKind,
1092 /// The aggregate function to apply.
1093 pub function: AggregateFunction,
1094 /// The property to access on each entity.
1095 pub property: String,
1096 /// Output alias for the result column.
1097 pub alias: String,
1098 /// Input operator.
1099 pub input: Box<LogicalOperator>,
1100}
1101
1102/// An aggregate expression.
1103#[derive(Debug, Clone)]
1104pub struct AggregateExpr {
1105 /// Aggregate function.
1106 pub function: AggregateFunction,
1107 /// Expression to aggregate (first/only argument, y for binary set functions).
1108 pub expression: Option<LogicalExpression>,
1109 /// Second expression for binary set functions (x for COVAR, CORR, REGR_*).
1110 pub expression2: Option<LogicalExpression>,
1111 /// Whether to use DISTINCT.
1112 pub distinct: bool,
1113 /// Alias for the result.
1114 pub alias: Option<String>,
1115 /// Percentile parameter for PERCENTILE_DISC/PERCENTILE_CONT (0.0 to 1.0).
1116 pub percentile: Option<f64>,
1117 /// Separator string for GROUP_CONCAT / LISTAGG (defaults to space for GROUP_CONCAT, comma for LISTAGG).
1118 pub separator: Option<String>,
1119}
1120
1121/// Aggregate function.
1122#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1123pub enum AggregateFunction {
1124 /// Count all rows (COUNT(*)).
1125 Count,
1126 /// Count non-null values (COUNT(expr)).
1127 CountNonNull,
1128 /// Sum values.
1129 Sum,
1130 /// Average values.
1131 Avg,
1132 /// Minimum value.
1133 Min,
1134 /// Maximum value.
1135 Max,
1136 /// Collect into list.
1137 Collect,
1138 /// Sample standard deviation (STDEV).
1139 StdDev,
1140 /// Population standard deviation (STDEVP).
1141 StdDevPop,
1142 /// Sample variance (VAR_SAMP / VARIANCE).
1143 Variance,
1144 /// Population variance (VAR_POP).
1145 VariancePop,
1146 /// Discrete percentile (PERCENTILE_DISC).
1147 PercentileDisc,
1148 /// Continuous percentile (PERCENTILE_CONT).
1149 PercentileCont,
1150 /// Concatenate values with separator (GROUP_CONCAT).
1151 GroupConcat,
1152 /// Return an arbitrary value from the group (SAMPLE).
1153 Sample,
1154 /// Sample covariance (COVAR_SAMP(y, x)).
1155 CovarSamp,
1156 /// Population covariance (COVAR_POP(y, x)).
1157 CovarPop,
1158 /// Pearson correlation coefficient (CORR(y, x)).
1159 Corr,
1160 /// Regression slope (REGR_SLOPE(y, x)).
1161 RegrSlope,
1162 /// Regression intercept (REGR_INTERCEPT(y, x)).
1163 RegrIntercept,
1164 /// Coefficient of determination (REGR_R2(y, x)).
1165 RegrR2,
1166 /// Regression count of non-null pairs (REGR_COUNT(y, x)).
1167 RegrCount,
1168 /// Regression sum of squares for x (REGR_SXX(y, x)).
1169 RegrSxx,
1170 /// Regression sum of squares for y (REGR_SYY(y, x)).
1171 RegrSyy,
1172 /// Regression sum of cross-products (REGR_SXY(y, x)).
1173 RegrSxy,
1174 /// Regression average of x (REGR_AVGX(y, x)).
1175 RegrAvgx,
1176 /// Regression average of y (REGR_AVGY(y, x)).
1177 RegrAvgy,
1178}
1179
1180/// Hint about how a filter will be executed at the physical level.
1181///
1182/// Set during EXPLAIN annotation to communicate pushdown decisions.
1183#[derive(Debug, Clone)]
1184pub enum PushdownHint {
1185 /// Equality predicate resolved via a property index.
1186 IndexLookup {
1187 /// The indexed property name.
1188 property: String,
1189 },
1190 /// Range predicate resolved via a range/btree index.
1191 RangeScan {
1192 /// The indexed property name.
1193 property: String,
1194 },
1195 /// No index available, but label narrows the scan before filtering.
1196 LabelFirst,
1197}
1198
1199/// Filter rows based on a predicate.
1200#[derive(Debug, Clone)]
1201pub struct FilterOp {
1202 /// The filter predicate.
1203 pub predicate: LogicalExpression,
1204 /// Input operator.
1205 pub input: Box<LogicalOperator>,
1206 /// Optional hint about pushdown strategy (populated by EXPLAIN).
1207 pub pushdown_hint: Option<PushdownHint>,
1208}
1209
1210/// Project specific columns.
1211#[derive(Debug, Clone)]
1212pub struct ProjectOp {
1213 /// Columns to project.
1214 pub projections: Vec<Projection>,
1215 /// Input operator.
1216 pub input: Box<LogicalOperator>,
1217 /// When true, all input columns are passed through and the explicit
1218 /// projections are appended as additional output columns. Used by GQL
1219 /// LET clauses which add bindings without replacing the existing scope.
1220 pub pass_through_input: bool,
1221}
1222
1223/// A single projection (column selection or computation).
1224#[derive(Debug, Clone)]
1225pub struct Projection {
1226 /// Expression to compute.
1227 pub expression: LogicalExpression,
1228 /// Alias for the result.
1229 pub alias: Option<String>,
1230}
1231
1232/// Limit the number of results.
1233#[derive(Debug, Clone)]
1234pub struct LimitOp {
1235 /// Maximum number of rows to return (literal or parameter reference).
1236 pub count: CountExpr,
1237 /// Input operator.
1238 pub input: Box<LogicalOperator>,
1239}
1240
1241/// Skip a number of results.
1242#[derive(Debug, Clone)]
1243pub struct SkipOp {
1244 /// Number of rows to skip (literal or parameter reference).
1245 pub count: CountExpr,
1246 /// Input operator.
1247 pub input: Box<LogicalOperator>,
1248}
1249
1250/// Sort results.
1251#[derive(Debug, Clone)]
1252pub struct SortOp {
1253 /// Sort keys.
1254 pub keys: Vec<SortKey>,
1255 /// Input operator.
1256 pub input: Box<LogicalOperator>,
1257}
1258
1259/// A sort key.
1260#[derive(Debug, Clone)]
1261pub struct SortKey {
1262 /// Expression to sort by.
1263 pub expression: LogicalExpression,
1264 /// Sort order.
1265 pub order: SortOrder,
1266 /// Optional null ordering (NULLS FIRST / NULLS LAST).
1267 pub nulls: Option<NullsOrdering>,
1268}
1269
1270/// Sort order.
1271#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1272pub enum SortOrder {
1273 /// Ascending order.
1274 Ascending,
1275 /// Descending order.
1276 Descending,
1277}
1278
1279/// Null ordering for sort operations.
1280#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1281pub enum NullsOrdering {
1282 /// Nulls sort before all non-null values.
1283 First,
1284 /// Nulls sort after all non-null values.
1285 Last,
1286}
1287
1288/// Remove duplicate results.
1289#[derive(Debug, Clone)]
1290pub struct DistinctOp {
1291 /// Input operator.
1292 pub input: Box<LogicalOperator>,
1293 /// Optional columns to use for deduplication.
1294 /// If None, all columns are used.
1295 pub columns: Option<Vec<String>>,
1296}
1297
1298/// Create a new node.
1299#[derive(Debug, Clone)]
1300pub struct CreateNodeOp {
1301 /// Variable name to bind the created node to.
1302 pub variable: String,
1303 /// Labels for the new node.
1304 pub labels: Vec<String>,
1305 /// Properties for the new node.
1306 pub properties: Vec<(String, LogicalExpression)>,
1307 /// Input operator (for chained creates).
1308 pub input: Option<Box<LogicalOperator>>,
1309}
1310
1311/// Create a new edge.
1312#[derive(Debug, Clone)]
1313pub struct CreateEdgeOp {
1314 /// Variable name to bind the created edge to.
1315 pub variable: Option<String>,
1316 /// Source node variable.
1317 pub from_variable: String,
1318 /// Target node variable.
1319 pub to_variable: String,
1320 /// Edge type.
1321 pub edge_type: String,
1322 /// Properties for the new edge.
1323 pub properties: Vec<(String, LogicalExpression)>,
1324 /// Input operator.
1325 pub input: Box<LogicalOperator>,
1326}
1327
1328/// Delete a node.
1329#[derive(Debug, Clone)]
1330pub struct DeleteNodeOp {
1331 /// Variable of the node to delete.
1332 pub variable: String,
1333 /// Whether to detach (delete connected edges) before deleting.
1334 pub detach: bool,
1335 /// Input operator.
1336 pub input: Box<LogicalOperator>,
1337}
1338
1339/// Delete an edge.
1340#[derive(Debug, Clone)]
1341pub struct DeleteEdgeOp {
1342 /// Variable of the edge to delete.
1343 pub variable: String,
1344 /// Input operator.
1345 pub input: Box<LogicalOperator>,
1346}
1347
1348/// Set properties on a node or edge.
1349#[derive(Debug, Clone)]
1350pub struct SetPropertyOp {
1351 /// Variable of the entity to update.
1352 pub variable: String,
1353 /// Properties to set (name -> expression).
1354 pub properties: Vec<(String, LogicalExpression)>,
1355 /// Whether to replace all properties (vs. merge).
1356 pub replace: bool,
1357 /// Whether the target variable is an edge (vs. node).
1358 pub is_edge: bool,
1359 /// Input operator.
1360 pub input: Box<LogicalOperator>,
1361}
1362
1363/// Add labels to a node.
1364#[derive(Debug, Clone)]
1365pub struct AddLabelOp {
1366 /// Variable of the node to update.
1367 pub variable: String,
1368 /// Labels to add.
1369 pub labels: Vec<String>,
1370 /// Input operator.
1371 pub input: Box<LogicalOperator>,
1372}
1373
1374/// Remove labels from a node.
1375#[derive(Debug, Clone)]
1376pub struct RemoveLabelOp {
1377 /// Variable of the node to update.
1378 pub variable: String,
1379 /// Labels to remove.
1380 pub labels: Vec<String>,
1381 /// Input operator.
1382 pub input: Box<LogicalOperator>,
1383}
1384
1385// ==================== RDF/SPARQL Operators ====================
1386
1387/// Scan RDF triples matching a pattern.
1388#[derive(Debug, Clone)]
1389pub struct TripleScanOp {
1390 /// Subject pattern (variable name or IRI).
1391 pub subject: TripleComponent,
1392 /// Predicate pattern (variable name or IRI).
1393 pub predicate: TripleComponent,
1394 /// Object pattern (variable name, IRI, or literal).
1395 pub object: TripleComponent,
1396 /// Named graph (optional).
1397 pub graph: Option<TripleComponent>,
1398 /// Input operator (for chained patterns).
1399 pub input: Option<Box<LogicalOperator>>,
1400}
1401
1402/// A component of a triple pattern.
1403#[derive(Debug, Clone)]
1404pub enum TripleComponent {
1405 /// A variable to bind.
1406 Variable(String),
1407 /// A constant IRI.
1408 Iri(String),
1409 /// A constant literal value.
1410 Literal(Value),
1411}
1412
1413/// Union of multiple result sets.
1414#[derive(Debug, Clone)]
1415pub struct UnionOp {
1416 /// Inputs to union together.
1417 pub inputs: Vec<LogicalOperator>,
1418}
1419
1420/// Set difference: rows in left that are not in right.
1421#[derive(Debug, Clone)]
1422pub struct ExceptOp {
1423 /// Left input.
1424 pub left: Box<LogicalOperator>,
1425 /// Right input (rows to exclude).
1426 pub right: Box<LogicalOperator>,
1427 /// If true, preserve duplicates (EXCEPT ALL); if false, deduplicate (EXCEPT DISTINCT).
1428 pub all: bool,
1429}
1430
1431/// Set intersection: rows common to both inputs.
1432#[derive(Debug, Clone)]
1433pub struct IntersectOp {
1434 /// Left input.
1435 pub left: Box<LogicalOperator>,
1436 /// Right input.
1437 pub right: Box<LogicalOperator>,
1438 /// If true, preserve duplicates (INTERSECT ALL); if false, deduplicate (INTERSECT DISTINCT).
1439 pub all: bool,
1440}
1441
1442/// Fallback operator: use left result if non-empty, otherwise use right.
1443#[derive(Debug, Clone)]
1444pub struct OtherwiseOp {
1445 /// Primary input (preferred).
1446 pub left: Box<LogicalOperator>,
1447 /// Fallback input (used only if left produces zero rows).
1448 pub right: Box<LogicalOperator>,
1449}
1450
1451/// Apply (lateral join): evaluate a subplan for each row of the outer input.
1452///
1453/// The subplan can reference variables bound by the outer input. Results are
1454/// concatenated (cross-product per row).
1455#[derive(Debug, Clone)]
1456pub struct ApplyOp {
1457 /// Outer input providing rows.
1458 pub input: Box<LogicalOperator>,
1459 /// Subplan to evaluate per outer row.
1460 pub subplan: Box<LogicalOperator>,
1461 /// Variables imported from the outer scope into the inner plan.
1462 /// When non-empty, the planner injects these via `ParameterState`.
1463 pub shared_variables: Vec<String>,
1464 /// When true, uses left-join semantics: outer rows with no matching inner
1465 /// rows are emitted with NULLs for the inner columns (OPTIONAL CALL).
1466 pub optional: bool,
1467}
1468
1469/// Parameter scan: leaf operator for correlated subquery inner plans.
1470///
1471/// Emits a single row containing the values injected from the outer Apply.
1472/// Column names correspond to the outer variables imported via WITH.
1473#[derive(Debug, Clone)]
1474pub struct ParameterScanOp {
1475 /// Column names for the injected parameters.
1476 pub columns: Vec<String>,
1477}
1478
1479/// Left outer join for OPTIONAL patterns.
1480#[derive(Debug, Clone)]
1481pub struct LeftJoinOp {
1482 /// Left (required) input.
1483 pub left: Box<LogicalOperator>,
1484 /// Right (optional) input.
1485 pub right: Box<LogicalOperator>,
1486 /// Optional filter condition.
1487 pub condition: Option<LogicalExpression>,
1488}
1489
1490/// Anti-join for MINUS patterns.
1491#[derive(Debug, Clone)]
1492pub struct AntiJoinOp {
1493 /// Left input (results to keep if no match on right).
1494 pub left: Box<LogicalOperator>,
1495 /// Right input (patterns to exclude).
1496 pub right: Box<LogicalOperator>,
1497}
1498
1499/// Bind a variable to an expression.
1500#[derive(Debug, Clone)]
1501pub struct BindOp {
1502 /// Expression to compute.
1503 pub expression: LogicalExpression,
1504 /// Variable to bind the result to.
1505 pub variable: String,
1506 /// Input operator.
1507 pub input: Box<LogicalOperator>,
1508}
1509
1510/// Unwind a list into individual rows.
1511///
1512/// For each input row, evaluates the expression (which should return a list)
1513/// and emits one row for each element in the list.
1514#[derive(Debug, Clone)]
1515pub struct UnwindOp {
1516 /// The list expression to unwind.
1517 pub expression: LogicalExpression,
1518 /// The variable name for each element.
1519 pub variable: String,
1520 /// Optional variable for 1-based element position (ORDINALITY).
1521 pub ordinality_var: Option<String>,
1522 /// Optional variable for 0-based element position (OFFSET).
1523 pub offset_var: Option<String>,
1524 /// Input operator.
1525 pub input: Box<LogicalOperator>,
1526}
1527
1528/// Collect grouped key-value rows into a single Map value.
1529/// Used for Gremlin `groupCount()` semantics.
1530#[derive(Debug, Clone)]
1531pub struct MapCollectOp {
1532 /// Variable holding the map key.
1533 pub key_var: String,
1534 /// Variable holding the map value.
1535 pub value_var: String,
1536 /// Output variable alias.
1537 pub alias: String,
1538 /// Input operator (typically a grouped aggregate).
1539 pub input: Box<LogicalOperator>,
1540}
1541
1542/// Merge a pattern (match or create).
1543///
1544/// MERGE tries to match a pattern in the graph. If found, returns the existing
1545/// elements (optionally applying ON MATCH SET). If not found, creates the pattern
1546/// (optionally applying ON CREATE SET).
1547#[derive(Debug, Clone)]
1548pub struct MergeOp {
1549 /// The node to merge.
1550 pub variable: String,
1551 /// Labels to match/create.
1552 pub labels: Vec<String>,
1553 /// Properties that must match (used for both matching and creation).
1554 pub match_properties: Vec<(String, LogicalExpression)>,
1555 /// Properties to set on CREATE.
1556 pub on_create: Vec<(String, LogicalExpression)>,
1557 /// Properties to set on MATCH.
1558 pub on_match: Vec<(String, LogicalExpression)>,
1559 /// Input operator.
1560 pub input: Box<LogicalOperator>,
1561}
1562
1563/// Merge a relationship pattern (match or create between two bound nodes).
1564///
1565/// MERGE on a relationship tries to find an existing relationship of the given type
1566/// between the source and target nodes. If found, returns the existing relationship
1567/// (optionally applying ON MATCH SET). If not found, creates it (optionally applying
1568/// ON CREATE SET).
1569#[derive(Debug, Clone)]
1570pub struct MergeRelationshipOp {
1571 /// Variable to bind the relationship to.
1572 pub variable: String,
1573 /// Source node variable (must already be bound).
1574 pub source_variable: String,
1575 /// Target node variable (must already be bound).
1576 pub target_variable: String,
1577 /// Relationship type.
1578 pub edge_type: String,
1579 /// Properties that must match (used for both matching and creation).
1580 pub match_properties: Vec<(String, LogicalExpression)>,
1581 /// Properties to set on CREATE.
1582 pub on_create: Vec<(String, LogicalExpression)>,
1583 /// Properties to set on MATCH.
1584 pub on_match: Vec<(String, LogicalExpression)>,
1585 /// Input operator.
1586 pub input: Box<LogicalOperator>,
1587}
1588
1589/// Find shortest path between two nodes.
1590///
1591/// This operator uses Dijkstra's algorithm to find the shortest path(s)
1592/// between a source node and a target node, optionally filtered by edge type.
1593#[derive(Debug, Clone)]
1594pub struct ShortestPathOp {
1595 /// Input operator providing source/target nodes.
1596 pub input: Box<LogicalOperator>,
1597 /// Variable name for the source node.
1598 pub source_var: String,
1599 /// Variable name for the target node.
1600 pub target_var: String,
1601 /// Edge type filter (empty = match all types, multiple = match any).
1602 pub edge_types: Vec<String>,
1603 /// Direction of edge traversal.
1604 pub direction: ExpandDirection,
1605 /// Variable name to bind the path result.
1606 pub path_alias: String,
1607 /// Whether to find all shortest paths (vs. just one).
1608 pub all_paths: bool,
1609}
1610
1611// ==================== SPARQL Update Operators ====================
1612
1613/// Insert RDF triples.
1614#[derive(Debug, Clone)]
1615pub struct InsertTripleOp {
1616 /// Subject of the triple.
1617 pub subject: TripleComponent,
1618 /// Predicate of the triple.
1619 pub predicate: TripleComponent,
1620 /// Object of the triple.
1621 pub object: TripleComponent,
1622 /// Named graph (optional).
1623 pub graph: Option<String>,
1624 /// Input operator (provides variable bindings).
1625 pub input: Option<Box<LogicalOperator>>,
1626}
1627
1628/// Delete RDF triples.
1629#[derive(Debug, Clone)]
1630pub struct DeleteTripleOp {
1631 /// Subject pattern.
1632 pub subject: TripleComponent,
1633 /// Predicate pattern.
1634 pub predicate: TripleComponent,
1635 /// Object pattern.
1636 pub object: TripleComponent,
1637 /// Named graph (optional).
1638 pub graph: Option<String>,
1639 /// Input operator (provides variable bindings).
1640 pub input: Option<Box<LogicalOperator>>,
1641}
1642
1643/// SPARQL MODIFY operation (DELETE/INSERT WHERE).
1644///
1645/// Per SPARQL 1.1 Update spec, this operator:
1646/// 1. Evaluates the WHERE clause once to get bindings
1647/// 2. Applies DELETE templates using those bindings
1648/// 3. Applies INSERT templates using the SAME bindings
1649///
1650/// This ensures DELETE and INSERT see consistent data.
1651#[derive(Debug, Clone)]
1652pub struct ModifyOp {
1653 /// DELETE triple templates (patterns with variables).
1654 pub delete_templates: Vec<TripleTemplate>,
1655 /// INSERT triple templates (patterns with variables).
1656 pub insert_templates: Vec<TripleTemplate>,
1657 /// WHERE clause that provides variable bindings.
1658 pub where_clause: Box<LogicalOperator>,
1659 /// Named graph context (for WITH clause).
1660 pub graph: Option<String>,
1661}
1662
1663/// A triple template for DELETE/INSERT operations.
1664#[derive(Debug, Clone)]
1665pub struct TripleTemplate {
1666 /// Subject (may be a variable).
1667 pub subject: TripleComponent,
1668 /// Predicate (may be a variable).
1669 pub predicate: TripleComponent,
1670 /// Object (may be a variable or literal).
1671 pub object: TripleComponent,
1672 /// Named graph (optional).
1673 pub graph: Option<String>,
1674}
1675
1676/// Clear all triples from a graph.
1677#[derive(Debug, Clone)]
1678pub struct ClearGraphOp {
1679 /// Target graph (None = default graph, Some("") = all named, Some(iri) = specific graph).
1680 pub graph: Option<String>,
1681 /// Whether to silently ignore errors.
1682 pub silent: bool,
1683}
1684
1685/// Create a new named graph.
1686#[derive(Debug, Clone)]
1687pub struct CreateGraphOp {
1688 /// IRI of the graph to create.
1689 pub graph: String,
1690 /// Whether to silently ignore if graph already exists.
1691 pub silent: bool,
1692}
1693
1694/// Drop (remove) a named graph.
1695#[derive(Debug, Clone)]
1696pub struct DropGraphOp {
1697 /// Target graph (None = default graph).
1698 pub graph: Option<String>,
1699 /// Whether to silently ignore errors.
1700 pub silent: bool,
1701}
1702
1703/// Load data from a URL into a graph.
1704#[derive(Debug, Clone)]
1705pub struct LoadGraphOp {
1706 /// Source URL to load data from.
1707 pub source: String,
1708 /// Destination graph (None = default graph).
1709 pub destination: Option<String>,
1710 /// Whether to silently ignore errors.
1711 pub silent: bool,
1712}
1713
1714/// Copy triples from one graph to another.
1715#[derive(Debug, Clone)]
1716pub struct CopyGraphOp {
1717 /// Source graph.
1718 pub source: Option<String>,
1719 /// Destination graph.
1720 pub destination: Option<String>,
1721 /// Whether to silently ignore errors.
1722 pub silent: bool,
1723}
1724
1725/// Move triples from one graph to another.
1726#[derive(Debug, Clone)]
1727pub struct MoveGraphOp {
1728 /// Source graph.
1729 pub source: Option<String>,
1730 /// Destination graph.
1731 pub destination: Option<String>,
1732 /// Whether to silently ignore errors.
1733 pub silent: bool,
1734}
1735
1736/// Add (merge) triples from one graph to another.
1737#[derive(Debug, Clone)]
1738pub struct AddGraphOp {
1739 /// Source graph.
1740 pub source: Option<String>,
1741 /// Destination graph.
1742 pub destination: Option<String>,
1743 /// Whether to silently ignore errors.
1744 pub silent: bool,
1745}
1746
1747// ==================== Vector Search Operators ====================
1748
1749/// Vector similarity scan operation.
1750///
1751/// Performs approximate nearest neighbor search using a vector index (HNSW)
1752/// or brute-force search for small datasets. Returns nodes/edges whose
1753/// embeddings are similar to the query vector.
1754///
1755/// # Example GQL
1756///
1757/// ```gql
1758/// MATCH (m:Movie)
1759/// WHERE vector_similarity(m.embedding, $query_vector) > 0.8
1760/// RETURN m.title
1761/// ```
1762#[derive(Debug, Clone)]
1763pub struct VectorScanOp {
1764 /// Variable name to bind matching entities to.
1765 pub variable: String,
1766 /// Name of the vector index to use (None = brute-force).
1767 pub index_name: Option<String>,
1768 /// Property containing the vector embedding.
1769 pub property: String,
1770 /// Optional label filter (scan only nodes with this label).
1771 pub label: Option<String>,
1772 /// The query vector expression.
1773 pub query_vector: LogicalExpression,
1774 /// Number of nearest neighbors to return.
1775 pub k: usize,
1776 /// Distance metric (None = use index default, typically cosine).
1777 pub metric: Option<VectorMetric>,
1778 /// Minimum similarity threshold (filters results below this).
1779 pub min_similarity: Option<f32>,
1780 /// Maximum distance threshold (filters results above this).
1781 pub max_distance: Option<f32>,
1782 /// Input operator (for hybrid queries combining graph + vector).
1783 pub input: Option<Box<LogicalOperator>>,
1784}
1785
1786/// Vector distance/similarity metric for vector scan operations.
1787#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1788pub enum VectorMetric {
1789 /// Cosine similarity (1 - cosine_distance). Best for normalized embeddings.
1790 Cosine,
1791 /// Euclidean (L2) distance. Best when magnitude matters.
1792 Euclidean,
1793 /// Dot product. Best for maximum inner product search.
1794 DotProduct,
1795 /// Manhattan (L1) distance. Less sensitive to outliers.
1796 Manhattan,
1797}
1798
1799/// Join graph patterns with vector similarity search.
1800///
1801/// This operator takes entities from the left input and computes vector
1802/// similarity against a query vector, outputting (entity, distance) pairs.
1803///
1804/// # Use Cases
1805///
1806/// 1. **Hybrid graph + vector queries**: Find similar nodes after graph traversal
1807/// 2. **Aggregated embeddings**: Use AVG(embeddings) as query vector
1808/// 3. **Filtering by similarity**: Join with threshold-based filtering
1809///
1810/// # Example
1811///
1812/// ```gql
1813/// // Find movies similar to what the user liked
1814/// MATCH (u:User {id: $user_id})-[:LIKED]->(liked:Movie)
1815/// WITH avg(liked.embedding) AS user_taste
1816/// VECTOR JOIN (m:Movie) ON m.embedding
1817/// WHERE vector_similarity(m.embedding, user_taste) > 0.7
1818/// RETURN m.title
1819/// ```
1820#[derive(Debug, Clone)]
1821pub struct VectorJoinOp {
1822 /// Input operator providing entities to match against.
1823 pub input: Box<LogicalOperator>,
1824 /// Variable from input to extract vectors from (for entity-to-entity similarity).
1825 /// If None, uses `query_vector` directly.
1826 pub left_vector_variable: Option<String>,
1827 /// Property containing the left vector (used with `left_vector_variable`).
1828 pub left_property: Option<String>,
1829 /// The query vector expression (constant or computed).
1830 pub query_vector: LogicalExpression,
1831 /// Variable name to bind the right-side matching entities.
1832 pub right_variable: String,
1833 /// Property containing the right-side vector embeddings.
1834 pub right_property: String,
1835 /// Optional label filter for right-side entities.
1836 pub right_label: Option<String>,
1837 /// Name of vector index on right side (None = brute-force).
1838 pub index_name: Option<String>,
1839 /// Number of nearest neighbors per left-side entity.
1840 pub k: usize,
1841 /// Distance metric.
1842 pub metric: Option<VectorMetric>,
1843 /// Minimum similarity threshold.
1844 pub min_similarity: Option<f32>,
1845 /// Maximum distance threshold.
1846 pub max_distance: Option<f32>,
1847 /// Variable to bind the distance/similarity score.
1848 pub score_variable: Option<String>,
1849}
1850
1851/// Return results (terminal operator).
1852#[derive(Debug, Clone)]
1853pub struct ReturnOp {
1854 /// Items to return.
1855 pub items: Vec<ReturnItem>,
1856 /// Whether to return distinct results.
1857 pub distinct: bool,
1858 /// Input operator.
1859 pub input: Box<LogicalOperator>,
1860}
1861
1862/// A single return item.
1863#[derive(Debug, Clone)]
1864pub struct ReturnItem {
1865 /// Expression to return.
1866 pub expression: LogicalExpression,
1867 /// Alias for the result column.
1868 pub alias: Option<String>,
1869}
1870
1871/// Define a property graph schema (SQL/PGQ DDL).
1872#[derive(Debug, Clone)]
1873pub struct CreatePropertyGraphOp {
1874 /// Graph name.
1875 pub name: String,
1876 /// Node table schemas (label name + column definitions).
1877 pub node_tables: Vec<PropertyGraphNodeTable>,
1878 /// Edge table schemas (type name + column definitions + references).
1879 pub edge_tables: Vec<PropertyGraphEdgeTable>,
1880}
1881
1882/// A node table in a property graph definition.
1883#[derive(Debug, Clone)]
1884pub struct PropertyGraphNodeTable {
1885 /// Table name (maps to a node label).
1886 pub name: String,
1887 /// Column definitions as (name, type_name) pairs.
1888 pub columns: Vec<(String, String)>,
1889}
1890
1891/// An edge table in a property graph definition.
1892#[derive(Debug, Clone)]
1893pub struct PropertyGraphEdgeTable {
1894 /// Table name (maps to an edge type).
1895 pub name: String,
1896 /// Column definitions as (name, type_name) pairs.
1897 pub columns: Vec<(String, String)>,
1898 /// Source node table name.
1899 pub source_table: String,
1900 /// Target node table name.
1901 pub target_table: String,
1902}
1903
1904// ==================== Procedure Call Types ====================
1905
1906/// A CALL procedure operation.
1907///
1908/// ```text
1909/// CALL grafeo.pagerank({damping: 0.85}) YIELD nodeId, score
1910/// ```
1911#[derive(Debug, Clone)]
1912pub struct CallProcedureOp {
1913 /// Dotted procedure name, e.g. `["grafeo", "pagerank"]`.
1914 pub name: Vec<String>,
1915 /// Argument expressions (constants in Phase 1).
1916 pub arguments: Vec<LogicalExpression>,
1917 /// Optional YIELD clause: which columns to expose + aliases.
1918 pub yield_items: Option<Vec<ProcedureYield>>,
1919}
1920
1921/// A single YIELD item in a procedure call.
1922#[derive(Debug, Clone)]
1923pub struct ProcedureYield {
1924 /// Column name from the procedure result.
1925 pub field_name: String,
1926 /// Optional alias (YIELD score AS rank).
1927 pub alias: Option<String>,
1928}
1929
1930/// LOAD CSV operator: reads a CSV file and produces rows.
1931///
1932/// With headers, each row is bound as a `Value::Map` with column names as keys.
1933/// Without headers, each row is bound as a `Value::List` of string values.
1934#[derive(Debug, Clone)]
1935pub struct LoadCsvOp {
1936 /// Whether the CSV file has a header row.
1937 pub with_headers: bool,
1938 /// File path (local filesystem).
1939 pub path: String,
1940 /// Variable name to bind each row to.
1941 pub variable: String,
1942 /// Field separator character (default: comma).
1943 pub field_terminator: Option<char>,
1944}
1945
1946/// A logical expression.
1947#[derive(Debug, Clone)]
1948pub enum LogicalExpression {
1949 /// A literal value.
1950 Literal(Value),
1951
1952 /// A variable reference.
1953 Variable(String),
1954
1955 /// Property access (e.g., n.name).
1956 Property {
1957 /// The variable to access.
1958 variable: String,
1959 /// The property name.
1960 property: String,
1961 },
1962
1963 /// Binary operation.
1964 Binary {
1965 /// Left operand.
1966 left: Box<LogicalExpression>,
1967 /// Operator.
1968 op: BinaryOp,
1969 /// Right operand.
1970 right: Box<LogicalExpression>,
1971 },
1972
1973 /// Unary operation.
1974 Unary {
1975 /// Operator.
1976 op: UnaryOp,
1977 /// Operand.
1978 operand: Box<LogicalExpression>,
1979 },
1980
1981 /// Function call.
1982 FunctionCall {
1983 /// Function name.
1984 name: String,
1985 /// Arguments.
1986 args: Vec<LogicalExpression>,
1987 /// Whether DISTINCT is applied (e.g., COUNT(DISTINCT x)).
1988 distinct: bool,
1989 },
1990
1991 /// List literal.
1992 List(Vec<LogicalExpression>),
1993
1994 /// Map literal (e.g., {name: 'Alix', age: 30}).
1995 Map(Vec<(String, LogicalExpression)>),
1996
1997 /// Index access (e.g., `list[0]`).
1998 IndexAccess {
1999 /// The base expression (typically a list or string).
2000 base: Box<LogicalExpression>,
2001 /// The index expression.
2002 index: Box<LogicalExpression>,
2003 },
2004
2005 /// Slice access (e.g., list[1..3]).
2006 SliceAccess {
2007 /// The base expression (typically a list or string).
2008 base: Box<LogicalExpression>,
2009 /// Start index (None means from beginning).
2010 start: Option<Box<LogicalExpression>>,
2011 /// End index (None means to end).
2012 end: Option<Box<LogicalExpression>>,
2013 },
2014
2015 /// CASE expression.
2016 Case {
2017 /// Test expression (for simple CASE).
2018 operand: Option<Box<LogicalExpression>>,
2019 /// WHEN clauses.
2020 when_clauses: Vec<(LogicalExpression, LogicalExpression)>,
2021 /// ELSE clause.
2022 else_clause: Option<Box<LogicalExpression>>,
2023 },
2024
2025 /// Parameter reference.
2026 Parameter(String),
2027
2028 /// Labels of a node.
2029 Labels(String),
2030
2031 /// Type of an edge.
2032 Type(String),
2033
2034 /// ID of a node or edge.
2035 Id(String),
2036
2037 /// List comprehension: [x IN list WHERE predicate | expression]
2038 ListComprehension {
2039 /// Variable name for each element.
2040 variable: String,
2041 /// The source list expression.
2042 list_expr: Box<LogicalExpression>,
2043 /// Optional filter predicate.
2044 filter_expr: Option<Box<LogicalExpression>>,
2045 /// The mapping expression for each element.
2046 map_expr: Box<LogicalExpression>,
2047 },
2048
2049 /// List predicate: all/any/none/single(x IN list WHERE pred).
2050 ListPredicate {
2051 /// The kind of list predicate.
2052 kind: ListPredicateKind,
2053 /// The iteration variable name.
2054 variable: String,
2055 /// The source list expression.
2056 list_expr: Box<LogicalExpression>,
2057 /// The predicate to test for each element.
2058 predicate: Box<LogicalExpression>,
2059 },
2060
2061 /// EXISTS subquery.
2062 ExistsSubquery(Box<LogicalOperator>),
2063
2064 /// COUNT subquery.
2065 CountSubquery(Box<LogicalOperator>),
2066
2067 /// VALUE subquery: returns scalar value from first row of inner query.
2068 ValueSubquery(Box<LogicalOperator>),
2069
2070 /// Map projection: `node { .prop1, .prop2, key: expr, .* }`.
2071 MapProjection {
2072 /// The base variable name.
2073 base: String,
2074 /// Projection entries (property selectors, literal entries, all-properties).
2075 entries: Vec<MapProjectionEntry>,
2076 },
2077
2078 /// reduce() accumulator: `reduce(acc = init, x IN list | expr)`.
2079 Reduce {
2080 /// Accumulator variable name.
2081 accumulator: String,
2082 /// Initial value for the accumulator.
2083 initial: Box<LogicalExpression>,
2084 /// Iteration variable name.
2085 variable: String,
2086 /// List to iterate over.
2087 list: Box<LogicalExpression>,
2088 /// Body expression evaluated per iteration (references both accumulator and variable).
2089 expression: Box<LogicalExpression>,
2090 },
2091
2092 /// Pattern comprehension: `[(pattern) WHERE pred | expr]`.
2093 ///
2094 /// Executes the inner subplan, evaluates the projection for each row,
2095 /// and collects the results into a list.
2096 PatternComprehension {
2097 /// The subplan produced by translating the pattern (+optional WHERE).
2098 subplan: Box<LogicalOperator>,
2099 /// The projection expression evaluated for each match.
2100 projection: Box<LogicalExpression>,
2101 },
2102}
2103
2104/// An entry in a map projection.
2105#[derive(Debug, Clone)]
2106pub enum MapProjectionEntry {
2107 /// `.propertyName`: shorthand for `propertyName: base.propertyName`.
2108 PropertySelector(String),
2109 /// `key: expression`: explicit key-value pair.
2110 LiteralEntry(String, LogicalExpression),
2111 /// `.*`: include all properties of the base entity.
2112 AllProperties,
2113}
2114
2115/// The kind of list predicate function.
2116#[derive(Debug, Clone, PartialEq, Eq)]
2117pub enum ListPredicateKind {
2118 /// all(x IN list WHERE pred): true if pred holds for every element.
2119 All,
2120 /// any(x IN list WHERE pred): true if pred holds for at least one element.
2121 Any,
2122 /// none(x IN list WHERE pred): true if pred holds for no element.
2123 None,
2124 /// single(x IN list WHERE pred): true if pred holds for exactly one element.
2125 Single,
2126}
2127
2128/// Binary operator.
2129#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2130pub enum BinaryOp {
2131 /// Equality comparison (=).
2132 Eq,
2133 /// Inequality comparison (<>).
2134 Ne,
2135 /// Less than (<).
2136 Lt,
2137 /// Less than or equal (<=).
2138 Le,
2139 /// Greater than (>).
2140 Gt,
2141 /// Greater than or equal (>=).
2142 Ge,
2143
2144 /// Logical AND.
2145 And,
2146 /// Logical OR.
2147 Or,
2148 /// Logical XOR.
2149 Xor,
2150
2151 /// Addition (+).
2152 Add,
2153 /// Subtraction (-).
2154 Sub,
2155 /// Multiplication (*).
2156 Mul,
2157 /// Division (/).
2158 Div,
2159 /// Modulo (%).
2160 Mod,
2161
2162 /// String concatenation.
2163 Concat,
2164 /// String starts with.
2165 StartsWith,
2166 /// String ends with.
2167 EndsWith,
2168 /// String contains.
2169 Contains,
2170
2171 /// Collection membership (IN).
2172 In,
2173 /// Pattern matching (LIKE).
2174 Like,
2175 /// Regex matching (=~).
2176 Regex,
2177 /// Power/exponentiation (^).
2178 Pow,
2179}
2180
2181/// Unary operator.
2182#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2183pub enum UnaryOp {
2184 /// Logical NOT.
2185 Not,
2186 /// Numeric negation.
2187 Neg,
2188 /// IS NULL check.
2189 IsNull,
2190 /// IS NOT NULL check.
2191 IsNotNull,
2192}
2193
2194#[cfg(test)]
2195mod tests {
2196 use super::*;
2197
2198 #[test]
2199 fn test_simple_node_scan_plan() {
2200 let plan = LogicalPlan::new(LogicalOperator::Return(ReturnOp {
2201 items: vec![ReturnItem {
2202 expression: LogicalExpression::Variable("n".into()),
2203 alias: None,
2204 }],
2205 distinct: false,
2206 input: Box::new(LogicalOperator::NodeScan(NodeScanOp {
2207 variable: "n".into(),
2208 label: Some("Person".into()),
2209 input: None,
2210 })),
2211 }));
2212
2213 // Verify structure
2214 if let LogicalOperator::Return(ret) = &plan.root {
2215 assert_eq!(ret.items.len(), 1);
2216 assert!(!ret.distinct);
2217 if let LogicalOperator::NodeScan(scan) = ret.input.as_ref() {
2218 assert_eq!(scan.variable, "n");
2219 assert_eq!(scan.label, Some("Person".into()));
2220 } else {
2221 panic!("Expected NodeScan");
2222 }
2223 } else {
2224 panic!("Expected Return");
2225 }
2226 }
2227
2228 #[test]
2229 fn test_filter_plan() {
2230 let plan = LogicalPlan::new(LogicalOperator::Return(ReturnOp {
2231 items: vec![ReturnItem {
2232 expression: LogicalExpression::Property {
2233 variable: "n".into(),
2234 property: "name".into(),
2235 },
2236 alias: Some("name".into()),
2237 }],
2238 distinct: false,
2239 input: Box::new(LogicalOperator::Filter(FilterOp {
2240 predicate: LogicalExpression::Binary {
2241 left: Box::new(LogicalExpression::Property {
2242 variable: "n".into(),
2243 property: "age".into(),
2244 }),
2245 op: BinaryOp::Gt,
2246 right: Box::new(LogicalExpression::Literal(Value::Int64(30))),
2247 },
2248 input: Box::new(LogicalOperator::NodeScan(NodeScanOp {
2249 variable: "n".into(),
2250 label: Some("Person".into()),
2251 input: None,
2252 })),
2253 pushdown_hint: None,
2254 })),
2255 }));
2256
2257 if let LogicalOperator::Return(ret) = &plan.root {
2258 if let LogicalOperator::Filter(filter) = ret.input.as_ref() {
2259 if let LogicalExpression::Binary { op, .. } = &filter.predicate {
2260 assert_eq!(*op, BinaryOp::Gt);
2261 } else {
2262 panic!("Expected Binary expression");
2263 }
2264 } else {
2265 panic!("Expected Filter");
2266 }
2267 } else {
2268 panic!("Expected Return");
2269 }
2270 }
2271}