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}
1218
1219/// A single projection (column selection or computation).
1220#[derive(Debug, Clone)]
1221pub struct Projection {
1222 /// Expression to compute.
1223 pub expression: LogicalExpression,
1224 /// Alias for the result.
1225 pub alias: Option<String>,
1226}
1227
1228/// Limit the number of results.
1229#[derive(Debug, Clone)]
1230pub struct LimitOp {
1231 /// Maximum number of rows to return (literal or parameter reference).
1232 pub count: CountExpr,
1233 /// Input operator.
1234 pub input: Box<LogicalOperator>,
1235}
1236
1237/// Skip a number of results.
1238#[derive(Debug, Clone)]
1239pub struct SkipOp {
1240 /// Number of rows to skip (literal or parameter reference).
1241 pub count: CountExpr,
1242 /// Input operator.
1243 pub input: Box<LogicalOperator>,
1244}
1245
1246/// Sort results.
1247#[derive(Debug, Clone)]
1248pub struct SortOp {
1249 /// Sort keys.
1250 pub keys: Vec<SortKey>,
1251 /// Input operator.
1252 pub input: Box<LogicalOperator>,
1253}
1254
1255/// A sort key.
1256#[derive(Debug, Clone)]
1257pub struct SortKey {
1258 /// Expression to sort by.
1259 pub expression: LogicalExpression,
1260 /// Sort order.
1261 pub order: SortOrder,
1262 /// Optional null ordering (NULLS FIRST / NULLS LAST).
1263 pub nulls: Option<NullsOrdering>,
1264}
1265
1266/// Sort order.
1267#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1268pub enum SortOrder {
1269 /// Ascending order.
1270 Ascending,
1271 /// Descending order.
1272 Descending,
1273}
1274
1275/// Null ordering for sort operations.
1276#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1277pub enum NullsOrdering {
1278 /// Nulls sort before all non-null values.
1279 First,
1280 /// Nulls sort after all non-null values.
1281 Last,
1282}
1283
1284/// Remove duplicate results.
1285#[derive(Debug, Clone)]
1286pub struct DistinctOp {
1287 /// Input operator.
1288 pub input: Box<LogicalOperator>,
1289 /// Optional columns to use for deduplication.
1290 /// If None, all columns are used.
1291 pub columns: Option<Vec<String>>,
1292}
1293
1294/// Create a new node.
1295#[derive(Debug, Clone)]
1296pub struct CreateNodeOp {
1297 /// Variable name to bind the created node to.
1298 pub variable: String,
1299 /// Labels for the new node.
1300 pub labels: Vec<String>,
1301 /// Properties for the new node.
1302 pub properties: Vec<(String, LogicalExpression)>,
1303 /// Input operator (for chained creates).
1304 pub input: Option<Box<LogicalOperator>>,
1305}
1306
1307/// Create a new edge.
1308#[derive(Debug, Clone)]
1309pub struct CreateEdgeOp {
1310 /// Variable name to bind the created edge to.
1311 pub variable: Option<String>,
1312 /// Source node variable.
1313 pub from_variable: String,
1314 /// Target node variable.
1315 pub to_variable: String,
1316 /// Edge type.
1317 pub edge_type: String,
1318 /// Properties for the new edge.
1319 pub properties: Vec<(String, LogicalExpression)>,
1320 /// Input operator.
1321 pub input: Box<LogicalOperator>,
1322}
1323
1324/// Delete a node.
1325#[derive(Debug, Clone)]
1326pub struct DeleteNodeOp {
1327 /// Variable of the node to delete.
1328 pub variable: String,
1329 /// Whether to detach (delete connected edges) before deleting.
1330 pub detach: bool,
1331 /// Input operator.
1332 pub input: Box<LogicalOperator>,
1333}
1334
1335/// Delete an edge.
1336#[derive(Debug, Clone)]
1337pub struct DeleteEdgeOp {
1338 /// Variable of the edge to delete.
1339 pub variable: String,
1340 /// Input operator.
1341 pub input: Box<LogicalOperator>,
1342}
1343
1344/// Set properties on a node or edge.
1345#[derive(Debug, Clone)]
1346pub struct SetPropertyOp {
1347 /// Variable of the entity to update.
1348 pub variable: String,
1349 /// Properties to set (name -> expression).
1350 pub properties: Vec<(String, LogicalExpression)>,
1351 /// Whether to replace all properties (vs. merge).
1352 pub replace: bool,
1353 /// Whether the target variable is an edge (vs. node).
1354 pub is_edge: bool,
1355 /// Input operator.
1356 pub input: Box<LogicalOperator>,
1357}
1358
1359/// Add labels to a node.
1360#[derive(Debug, Clone)]
1361pub struct AddLabelOp {
1362 /// Variable of the node to update.
1363 pub variable: String,
1364 /// Labels to add.
1365 pub labels: Vec<String>,
1366 /// Input operator.
1367 pub input: Box<LogicalOperator>,
1368}
1369
1370/// Remove labels from a node.
1371#[derive(Debug, Clone)]
1372pub struct RemoveLabelOp {
1373 /// Variable of the node to update.
1374 pub variable: String,
1375 /// Labels to remove.
1376 pub labels: Vec<String>,
1377 /// Input operator.
1378 pub input: Box<LogicalOperator>,
1379}
1380
1381// ==================== RDF/SPARQL Operators ====================
1382
1383/// Scan RDF triples matching a pattern.
1384#[derive(Debug, Clone)]
1385pub struct TripleScanOp {
1386 /// Subject pattern (variable name or IRI).
1387 pub subject: TripleComponent,
1388 /// Predicate pattern (variable name or IRI).
1389 pub predicate: TripleComponent,
1390 /// Object pattern (variable name, IRI, or literal).
1391 pub object: TripleComponent,
1392 /// Named graph (optional).
1393 pub graph: Option<TripleComponent>,
1394 /// Input operator (for chained patterns).
1395 pub input: Option<Box<LogicalOperator>>,
1396}
1397
1398/// A component of a triple pattern.
1399#[derive(Debug, Clone)]
1400pub enum TripleComponent {
1401 /// A variable to bind.
1402 Variable(String),
1403 /// A constant IRI.
1404 Iri(String),
1405 /// A constant literal value.
1406 Literal(Value),
1407}
1408
1409/// Union of multiple result sets.
1410#[derive(Debug, Clone)]
1411pub struct UnionOp {
1412 /// Inputs to union together.
1413 pub inputs: Vec<LogicalOperator>,
1414}
1415
1416/// Set difference: rows in left that are not in right.
1417#[derive(Debug, Clone)]
1418pub struct ExceptOp {
1419 /// Left input.
1420 pub left: Box<LogicalOperator>,
1421 /// Right input (rows to exclude).
1422 pub right: Box<LogicalOperator>,
1423 /// If true, preserve duplicates (EXCEPT ALL); if false, deduplicate (EXCEPT DISTINCT).
1424 pub all: bool,
1425}
1426
1427/// Set intersection: rows common to both inputs.
1428#[derive(Debug, Clone)]
1429pub struct IntersectOp {
1430 /// Left input.
1431 pub left: Box<LogicalOperator>,
1432 /// Right input.
1433 pub right: Box<LogicalOperator>,
1434 /// If true, preserve duplicates (INTERSECT ALL); if false, deduplicate (INTERSECT DISTINCT).
1435 pub all: bool,
1436}
1437
1438/// Fallback operator: use left result if non-empty, otherwise use right.
1439#[derive(Debug, Clone)]
1440pub struct OtherwiseOp {
1441 /// Primary input (preferred).
1442 pub left: Box<LogicalOperator>,
1443 /// Fallback input (used only if left produces zero rows).
1444 pub right: Box<LogicalOperator>,
1445}
1446
1447/// Apply (lateral join): evaluate a subplan for each row of the outer input.
1448///
1449/// The subplan can reference variables bound by the outer input. Results are
1450/// concatenated (cross-product per row).
1451#[derive(Debug, Clone)]
1452pub struct ApplyOp {
1453 /// Outer input providing rows.
1454 pub input: Box<LogicalOperator>,
1455 /// Subplan to evaluate per outer row.
1456 pub subplan: Box<LogicalOperator>,
1457 /// Variables imported from the outer scope into the inner plan.
1458 /// When non-empty, the planner injects these via `ParameterState`.
1459 pub shared_variables: Vec<String>,
1460}
1461
1462/// Parameter scan: leaf operator for correlated subquery inner plans.
1463///
1464/// Emits a single row containing the values injected from the outer Apply.
1465/// Column names correspond to the outer variables imported via WITH.
1466#[derive(Debug, Clone)]
1467pub struct ParameterScanOp {
1468 /// Column names for the injected parameters.
1469 pub columns: Vec<String>,
1470}
1471
1472/// Left outer join for OPTIONAL patterns.
1473#[derive(Debug, Clone)]
1474pub struct LeftJoinOp {
1475 /// Left (required) input.
1476 pub left: Box<LogicalOperator>,
1477 /// Right (optional) input.
1478 pub right: Box<LogicalOperator>,
1479 /// Optional filter condition.
1480 pub condition: Option<LogicalExpression>,
1481}
1482
1483/// Anti-join for MINUS patterns.
1484#[derive(Debug, Clone)]
1485pub struct AntiJoinOp {
1486 /// Left input (results to keep if no match on right).
1487 pub left: Box<LogicalOperator>,
1488 /// Right input (patterns to exclude).
1489 pub right: Box<LogicalOperator>,
1490}
1491
1492/// Bind a variable to an expression.
1493#[derive(Debug, Clone)]
1494pub struct BindOp {
1495 /// Expression to compute.
1496 pub expression: LogicalExpression,
1497 /// Variable to bind the result to.
1498 pub variable: String,
1499 /// Input operator.
1500 pub input: Box<LogicalOperator>,
1501}
1502
1503/// Unwind a list into individual rows.
1504///
1505/// For each input row, evaluates the expression (which should return a list)
1506/// and emits one row for each element in the list.
1507#[derive(Debug, Clone)]
1508pub struct UnwindOp {
1509 /// The list expression to unwind.
1510 pub expression: LogicalExpression,
1511 /// The variable name for each element.
1512 pub variable: String,
1513 /// Optional variable for 1-based element position (ORDINALITY).
1514 pub ordinality_var: Option<String>,
1515 /// Optional variable for 0-based element position (OFFSET).
1516 pub offset_var: Option<String>,
1517 /// Input operator.
1518 pub input: Box<LogicalOperator>,
1519}
1520
1521/// Collect grouped key-value rows into a single Map value.
1522/// Used for Gremlin `groupCount()` semantics.
1523#[derive(Debug, Clone)]
1524pub struct MapCollectOp {
1525 /// Variable holding the map key.
1526 pub key_var: String,
1527 /// Variable holding the map value.
1528 pub value_var: String,
1529 /// Output variable alias.
1530 pub alias: String,
1531 /// Input operator (typically a grouped aggregate).
1532 pub input: Box<LogicalOperator>,
1533}
1534
1535/// Merge a pattern (match or create).
1536///
1537/// MERGE tries to match a pattern in the graph. If found, returns the existing
1538/// elements (optionally applying ON MATCH SET). If not found, creates the pattern
1539/// (optionally applying ON CREATE SET).
1540#[derive(Debug, Clone)]
1541pub struct MergeOp {
1542 /// The node to merge.
1543 pub variable: String,
1544 /// Labels to match/create.
1545 pub labels: Vec<String>,
1546 /// Properties that must match (used for both matching and creation).
1547 pub match_properties: Vec<(String, LogicalExpression)>,
1548 /// Properties to set on CREATE.
1549 pub on_create: Vec<(String, LogicalExpression)>,
1550 /// Properties to set on MATCH.
1551 pub on_match: Vec<(String, LogicalExpression)>,
1552 /// Input operator.
1553 pub input: Box<LogicalOperator>,
1554}
1555
1556/// Merge a relationship pattern (match or create between two bound nodes).
1557///
1558/// MERGE on a relationship tries to find an existing relationship of the given type
1559/// between the source and target nodes. If found, returns the existing relationship
1560/// (optionally applying ON MATCH SET). If not found, creates it (optionally applying
1561/// ON CREATE SET).
1562#[derive(Debug, Clone)]
1563pub struct MergeRelationshipOp {
1564 /// Variable to bind the relationship to.
1565 pub variable: String,
1566 /// Source node variable (must already be bound).
1567 pub source_variable: String,
1568 /// Target node variable (must already be bound).
1569 pub target_variable: String,
1570 /// Relationship type.
1571 pub edge_type: String,
1572 /// Properties that must match (used for both matching and creation).
1573 pub match_properties: Vec<(String, LogicalExpression)>,
1574 /// Properties to set on CREATE.
1575 pub on_create: Vec<(String, LogicalExpression)>,
1576 /// Properties to set on MATCH.
1577 pub on_match: Vec<(String, LogicalExpression)>,
1578 /// Input operator.
1579 pub input: Box<LogicalOperator>,
1580}
1581
1582/// Find shortest path between two nodes.
1583///
1584/// This operator uses Dijkstra's algorithm to find the shortest path(s)
1585/// between a source node and a target node, optionally filtered by edge type.
1586#[derive(Debug, Clone)]
1587pub struct ShortestPathOp {
1588 /// Input operator providing source/target nodes.
1589 pub input: Box<LogicalOperator>,
1590 /// Variable name for the source node.
1591 pub source_var: String,
1592 /// Variable name for the target node.
1593 pub target_var: String,
1594 /// Edge type filter (empty = match all types, multiple = match any).
1595 pub edge_types: Vec<String>,
1596 /// Direction of edge traversal.
1597 pub direction: ExpandDirection,
1598 /// Variable name to bind the path result.
1599 pub path_alias: String,
1600 /// Whether to find all shortest paths (vs. just one).
1601 pub all_paths: bool,
1602}
1603
1604// ==================== SPARQL Update Operators ====================
1605
1606/// Insert RDF triples.
1607#[derive(Debug, Clone)]
1608pub struct InsertTripleOp {
1609 /// Subject of the triple.
1610 pub subject: TripleComponent,
1611 /// Predicate of the triple.
1612 pub predicate: TripleComponent,
1613 /// Object of the triple.
1614 pub object: TripleComponent,
1615 /// Named graph (optional).
1616 pub graph: Option<String>,
1617 /// Input operator (provides variable bindings).
1618 pub input: Option<Box<LogicalOperator>>,
1619}
1620
1621/// Delete RDF triples.
1622#[derive(Debug, Clone)]
1623pub struct DeleteTripleOp {
1624 /// Subject pattern.
1625 pub subject: TripleComponent,
1626 /// Predicate pattern.
1627 pub predicate: TripleComponent,
1628 /// Object pattern.
1629 pub object: TripleComponent,
1630 /// Named graph (optional).
1631 pub graph: Option<String>,
1632 /// Input operator (provides variable bindings).
1633 pub input: Option<Box<LogicalOperator>>,
1634}
1635
1636/// SPARQL MODIFY operation (DELETE/INSERT WHERE).
1637///
1638/// Per SPARQL 1.1 Update spec, this operator:
1639/// 1. Evaluates the WHERE clause once to get bindings
1640/// 2. Applies DELETE templates using those bindings
1641/// 3. Applies INSERT templates using the SAME bindings
1642///
1643/// This ensures DELETE and INSERT see consistent data.
1644#[derive(Debug, Clone)]
1645pub struct ModifyOp {
1646 /// DELETE triple templates (patterns with variables).
1647 pub delete_templates: Vec<TripleTemplate>,
1648 /// INSERT triple templates (patterns with variables).
1649 pub insert_templates: Vec<TripleTemplate>,
1650 /// WHERE clause that provides variable bindings.
1651 pub where_clause: Box<LogicalOperator>,
1652 /// Named graph context (for WITH clause).
1653 pub graph: Option<String>,
1654}
1655
1656/// A triple template for DELETE/INSERT operations.
1657#[derive(Debug, Clone)]
1658pub struct TripleTemplate {
1659 /// Subject (may be a variable).
1660 pub subject: TripleComponent,
1661 /// Predicate (may be a variable).
1662 pub predicate: TripleComponent,
1663 /// Object (may be a variable or literal).
1664 pub object: TripleComponent,
1665 /// Named graph (optional).
1666 pub graph: Option<String>,
1667}
1668
1669/// Clear all triples from a graph.
1670#[derive(Debug, Clone)]
1671pub struct ClearGraphOp {
1672 /// Target graph (None = default graph, Some("") = all named, Some(iri) = specific graph).
1673 pub graph: Option<String>,
1674 /// Whether to silently ignore errors.
1675 pub silent: bool,
1676}
1677
1678/// Create a new named graph.
1679#[derive(Debug, Clone)]
1680pub struct CreateGraphOp {
1681 /// IRI of the graph to create.
1682 pub graph: String,
1683 /// Whether to silently ignore if graph already exists.
1684 pub silent: bool,
1685}
1686
1687/// Drop (remove) a named graph.
1688#[derive(Debug, Clone)]
1689pub struct DropGraphOp {
1690 /// Target graph (None = default graph).
1691 pub graph: Option<String>,
1692 /// Whether to silently ignore errors.
1693 pub silent: bool,
1694}
1695
1696/// Load data from a URL into a graph.
1697#[derive(Debug, Clone)]
1698pub struct LoadGraphOp {
1699 /// Source URL to load data from.
1700 pub source: String,
1701 /// Destination graph (None = default graph).
1702 pub destination: Option<String>,
1703 /// Whether to silently ignore errors.
1704 pub silent: bool,
1705}
1706
1707/// Copy triples from one graph to another.
1708#[derive(Debug, Clone)]
1709pub struct CopyGraphOp {
1710 /// Source graph.
1711 pub source: Option<String>,
1712 /// Destination graph.
1713 pub destination: Option<String>,
1714 /// Whether to silently ignore errors.
1715 pub silent: bool,
1716}
1717
1718/// Move triples from one graph to another.
1719#[derive(Debug, Clone)]
1720pub struct MoveGraphOp {
1721 /// Source graph.
1722 pub source: Option<String>,
1723 /// Destination graph.
1724 pub destination: Option<String>,
1725 /// Whether to silently ignore errors.
1726 pub silent: bool,
1727}
1728
1729/// Add (merge) triples from one graph to another.
1730#[derive(Debug, Clone)]
1731pub struct AddGraphOp {
1732 /// Source graph.
1733 pub source: Option<String>,
1734 /// Destination graph.
1735 pub destination: Option<String>,
1736 /// Whether to silently ignore errors.
1737 pub silent: bool,
1738}
1739
1740// ==================== Vector Search Operators ====================
1741
1742/// Vector similarity scan operation.
1743///
1744/// Performs approximate nearest neighbor search using a vector index (HNSW)
1745/// or brute-force search for small datasets. Returns nodes/edges whose
1746/// embeddings are similar to the query vector.
1747///
1748/// # Example GQL
1749///
1750/// ```gql
1751/// MATCH (m:Movie)
1752/// WHERE vector_similarity(m.embedding, $query_vector) > 0.8
1753/// RETURN m.title
1754/// ```
1755#[derive(Debug, Clone)]
1756pub struct VectorScanOp {
1757 /// Variable name to bind matching entities to.
1758 pub variable: String,
1759 /// Name of the vector index to use (None = brute-force).
1760 pub index_name: Option<String>,
1761 /// Property containing the vector embedding.
1762 pub property: String,
1763 /// Optional label filter (scan only nodes with this label).
1764 pub label: Option<String>,
1765 /// The query vector expression.
1766 pub query_vector: LogicalExpression,
1767 /// Number of nearest neighbors to return.
1768 pub k: usize,
1769 /// Distance metric (None = use index default, typically cosine).
1770 pub metric: Option<VectorMetric>,
1771 /// Minimum similarity threshold (filters results below this).
1772 pub min_similarity: Option<f32>,
1773 /// Maximum distance threshold (filters results above this).
1774 pub max_distance: Option<f32>,
1775 /// Input operator (for hybrid queries combining graph + vector).
1776 pub input: Option<Box<LogicalOperator>>,
1777}
1778
1779/// Vector distance/similarity metric for vector scan operations.
1780#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1781pub enum VectorMetric {
1782 /// Cosine similarity (1 - cosine_distance). Best for normalized embeddings.
1783 Cosine,
1784 /// Euclidean (L2) distance. Best when magnitude matters.
1785 Euclidean,
1786 /// Dot product. Best for maximum inner product search.
1787 DotProduct,
1788 /// Manhattan (L1) distance. Less sensitive to outliers.
1789 Manhattan,
1790}
1791
1792/// Join graph patterns with vector similarity search.
1793///
1794/// This operator takes entities from the left input and computes vector
1795/// similarity against a query vector, outputting (entity, distance) pairs.
1796///
1797/// # Use Cases
1798///
1799/// 1. **Hybrid graph + vector queries**: Find similar nodes after graph traversal
1800/// 2. **Aggregated embeddings**: Use AVG(embeddings) as query vector
1801/// 3. **Filtering by similarity**: Join with threshold-based filtering
1802///
1803/// # Example
1804///
1805/// ```gql
1806/// // Find movies similar to what the user liked
1807/// MATCH (u:User {id: $user_id})-[:LIKED]->(liked:Movie)
1808/// WITH avg(liked.embedding) AS user_taste
1809/// VECTOR JOIN (m:Movie) ON m.embedding
1810/// WHERE vector_similarity(m.embedding, user_taste) > 0.7
1811/// RETURN m.title
1812/// ```
1813#[derive(Debug, Clone)]
1814pub struct VectorJoinOp {
1815 /// Input operator providing entities to match against.
1816 pub input: Box<LogicalOperator>,
1817 /// Variable from input to extract vectors from (for entity-to-entity similarity).
1818 /// If None, uses `query_vector` directly.
1819 pub left_vector_variable: Option<String>,
1820 /// Property containing the left vector (used with `left_vector_variable`).
1821 pub left_property: Option<String>,
1822 /// The query vector expression (constant or computed).
1823 pub query_vector: LogicalExpression,
1824 /// Variable name to bind the right-side matching entities.
1825 pub right_variable: String,
1826 /// Property containing the right-side vector embeddings.
1827 pub right_property: String,
1828 /// Optional label filter for right-side entities.
1829 pub right_label: Option<String>,
1830 /// Name of vector index on right side (None = brute-force).
1831 pub index_name: Option<String>,
1832 /// Number of nearest neighbors per left-side entity.
1833 pub k: usize,
1834 /// Distance metric.
1835 pub metric: Option<VectorMetric>,
1836 /// Minimum similarity threshold.
1837 pub min_similarity: Option<f32>,
1838 /// Maximum distance threshold.
1839 pub max_distance: Option<f32>,
1840 /// Variable to bind the distance/similarity score.
1841 pub score_variable: Option<String>,
1842}
1843
1844/// Return results (terminal operator).
1845#[derive(Debug, Clone)]
1846pub struct ReturnOp {
1847 /// Items to return.
1848 pub items: Vec<ReturnItem>,
1849 /// Whether to return distinct results.
1850 pub distinct: bool,
1851 /// Input operator.
1852 pub input: Box<LogicalOperator>,
1853}
1854
1855/// A single return item.
1856#[derive(Debug, Clone)]
1857pub struct ReturnItem {
1858 /// Expression to return.
1859 pub expression: LogicalExpression,
1860 /// Alias for the result column.
1861 pub alias: Option<String>,
1862}
1863
1864/// Define a property graph schema (SQL/PGQ DDL).
1865#[derive(Debug, Clone)]
1866pub struct CreatePropertyGraphOp {
1867 /// Graph name.
1868 pub name: String,
1869 /// Node table schemas (label name + column definitions).
1870 pub node_tables: Vec<PropertyGraphNodeTable>,
1871 /// Edge table schemas (type name + column definitions + references).
1872 pub edge_tables: Vec<PropertyGraphEdgeTable>,
1873}
1874
1875/// A node table in a property graph definition.
1876#[derive(Debug, Clone)]
1877pub struct PropertyGraphNodeTable {
1878 /// Table name (maps to a node label).
1879 pub name: String,
1880 /// Column definitions as (name, type_name) pairs.
1881 pub columns: Vec<(String, String)>,
1882}
1883
1884/// An edge table in a property graph definition.
1885#[derive(Debug, Clone)]
1886pub struct PropertyGraphEdgeTable {
1887 /// Table name (maps to an edge type).
1888 pub name: String,
1889 /// Column definitions as (name, type_name) pairs.
1890 pub columns: Vec<(String, String)>,
1891 /// Source node table name.
1892 pub source_table: String,
1893 /// Target node table name.
1894 pub target_table: String,
1895}
1896
1897// ==================== Procedure Call Types ====================
1898
1899/// A CALL procedure operation.
1900///
1901/// ```text
1902/// CALL grafeo.pagerank({damping: 0.85}) YIELD nodeId, score
1903/// ```
1904#[derive(Debug, Clone)]
1905pub struct CallProcedureOp {
1906 /// Dotted procedure name, e.g. `["grafeo", "pagerank"]`.
1907 pub name: Vec<String>,
1908 /// Argument expressions (constants in Phase 1).
1909 pub arguments: Vec<LogicalExpression>,
1910 /// Optional YIELD clause: which columns to expose + aliases.
1911 pub yield_items: Option<Vec<ProcedureYield>>,
1912}
1913
1914/// A single YIELD item in a procedure call.
1915#[derive(Debug, Clone)]
1916pub struct ProcedureYield {
1917 /// Column name from the procedure result.
1918 pub field_name: String,
1919 /// Optional alias (YIELD score AS rank).
1920 pub alias: Option<String>,
1921}
1922
1923/// LOAD CSV operator: reads a CSV file and produces rows.
1924///
1925/// With headers, each row is bound as a `Value::Map` with column names as keys.
1926/// Without headers, each row is bound as a `Value::List` of string values.
1927#[derive(Debug, Clone)]
1928pub struct LoadCsvOp {
1929 /// Whether the CSV file has a header row.
1930 pub with_headers: bool,
1931 /// File path (local filesystem).
1932 pub path: String,
1933 /// Variable name to bind each row to.
1934 pub variable: String,
1935 /// Field separator character (default: comma).
1936 pub field_terminator: Option<char>,
1937}
1938
1939/// A logical expression.
1940#[derive(Debug, Clone)]
1941pub enum LogicalExpression {
1942 /// A literal value.
1943 Literal(Value),
1944
1945 /// A variable reference.
1946 Variable(String),
1947
1948 /// Property access (e.g., n.name).
1949 Property {
1950 /// The variable to access.
1951 variable: String,
1952 /// The property name.
1953 property: String,
1954 },
1955
1956 /// Binary operation.
1957 Binary {
1958 /// Left operand.
1959 left: Box<LogicalExpression>,
1960 /// Operator.
1961 op: BinaryOp,
1962 /// Right operand.
1963 right: Box<LogicalExpression>,
1964 },
1965
1966 /// Unary operation.
1967 Unary {
1968 /// Operator.
1969 op: UnaryOp,
1970 /// Operand.
1971 operand: Box<LogicalExpression>,
1972 },
1973
1974 /// Function call.
1975 FunctionCall {
1976 /// Function name.
1977 name: String,
1978 /// Arguments.
1979 args: Vec<LogicalExpression>,
1980 /// Whether DISTINCT is applied (e.g., COUNT(DISTINCT x)).
1981 distinct: bool,
1982 },
1983
1984 /// List literal.
1985 List(Vec<LogicalExpression>),
1986
1987 /// Map literal (e.g., {name: 'Alix', age: 30}).
1988 Map(Vec<(String, LogicalExpression)>),
1989
1990 /// Index access (e.g., `list[0]`).
1991 IndexAccess {
1992 /// The base expression (typically a list or string).
1993 base: Box<LogicalExpression>,
1994 /// The index expression.
1995 index: Box<LogicalExpression>,
1996 },
1997
1998 /// Slice access (e.g., list[1..3]).
1999 SliceAccess {
2000 /// The base expression (typically a list or string).
2001 base: Box<LogicalExpression>,
2002 /// Start index (None means from beginning).
2003 start: Option<Box<LogicalExpression>>,
2004 /// End index (None means to end).
2005 end: Option<Box<LogicalExpression>>,
2006 },
2007
2008 /// CASE expression.
2009 Case {
2010 /// Test expression (for simple CASE).
2011 operand: Option<Box<LogicalExpression>>,
2012 /// WHEN clauses.
2013 when_clauses: Vec<(LogicalExpression, LogicalExpression)>,
2014 /// ELSE clause.
2015 else_clause: Option<Box<LogicalExpression>>,
2016 },
2017
2018 /// Parameter reference.
2019 Parameter(String),
2020
2021 /// Labels of a node.
2022 Labels(String),
2023
2024 /// Type of an edge.
2025 Type(String),
2026
2027 /// ID of a node or edge.
2028 Id(String),
2029
2030 /// List comprehension: [x IN list WHERE predicate | expression]
2031 ListComprehension {
2032 /// Variable name for each element.
2033 variable: String,
2034 /// The source list expression.
2035 list_expr: Box<LogicalExpression>,
2036 /// Optional filter predicate.
2037 filter_expr: Option<Box<LogicalExpression>>,
2038 /// The mapping expression for each element.
2039 map_expr: Box<LogicalExpression>,
2040 },
2041
2042 /// List predicate: all/any/none/single(x IN list WHERE pred).
2043 ListPredicate {
2044 /// The kind of list predicate.
2045 kind: ListPredicateKind,
2046 /// The iteration variable name.
2047 variable: String,
2048 /// The source list expression.
2049 list_expr: Box<LogicalExpression>,
2050 /// The predicate to test for each element.
2051 predicate: Box<LogicalExpression>,
2052 },
2053
2054 /// EXISTS subquery.
2055 ExistsSubquery(Box<LogicalOperator>),
2056
2057 /// COUNT subquery.
2058 CountSubquery(Box<LogicalOperator>),
2059
2060 /// Map projection: `node { .prop1, .prop2, key: expr, .* }`.
2061 MapProjection {
2062 /// The base variable name.
2063 base: String,
2064 /// Projection entries (property selectors, literal entries, all-properties).
2065 entries: Vec<MapProjectionEntry>,
2066 },
2067
2068 /// reduce() accumulator: `reduce(acc = init, x IN list | expr)`.
2069 Reduce {
2070 /// Accumulator variable name.
2071 accumulator: String,
2072 /// Initial value for the accumulator.
2073 initial: Box<LogicalExpression>,
2074 /// Iteration variable name.
2075 variable: String,
2076 /// List to iterate over.
2077 list: Box<LogicalExpression>,
2078 /// Body expression evaluated per iteration (references both accumulator and variable).
2079 expression: Box<LogicalExpression>,
2080 },
2081
2082 /// Pattern comprehension: `[(pattern) WHERE pred | expr]`.
2083 ///
2084 /// Executes the inner subplan, evaluates the projection for each row,
2085 /// and collects the results into a list.
2086 PatternComprehension {
2087 /// The subplan produced by translating the pattern (+optional WHERE).
2088 subplan: Box<LogicalOperator>,
2089 /// The projection expression evaluated for each match.
2090 projection: Box<LogicalExpression>,
2091 },
2092}
2093
2094/// An entry in a map projection.
2095#[derive(Debug, Clone)]
2096pub enum MapProjectionEntry {
2097 /// `.propertyName`: shorthand for `propertyName: base.propertyName`.
2098 PropertySelector(String),
2099 /// `key: expression`: explicit key-value pair.
2100 LiteralEntry(String, LogicalExpression),
2101 /// `.*`: include all properties of the base entity.
2102 AllProperties,
2103}
2104
2105/// The kind of list predicate function.
2106#[derive(Debug, Clone, PartialEq, Eq)]
2107pub enum ListPredicateKind {
2108 /// all(x IN list WHERE pred): true if pred holds for every element.
2109 All,
2110 /// any(x IN list WHERE pred): true if pred holds for at least one element.
2111 Any,
2112 /// none(x IN list WHERE pred): true if pred holds for no element.
2113 None,
2114 /// single(x IN list WHERE pred): true if pred holds for exactly one element.
2115 Single,
2116}
2117
2118/// Binary operator.
2119#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2120pub enum BinaryOp {
2121 /// Equality comparison (=).
2122 Eq,
2123 /// Inequality comparison (<>).
2124 Ne,
2125 /// Less than (<).
2126 Lt,
2127 /// Less than or equal (<=).
2128 Le,
2129 /// Greater than (>).
2130 Gt,
2131 /// Greater than or equal (>=).
2132 Ge,
2133
2134 /// Logical AND.
2135 And,
2136 /// Logical OR.
2137 Or,
2138 /// Logical XOR.
2139 Xor,
2140
2141 /// Addition (+).
2142 Add,
2143 /// Subtraction (-).
2144 Sub,
2145 /// Multiplication (*).
2146 Mul,
2147 /// Division (/).
2148 Div,
2149 /// Modulo (%).
2150 Mod,
2151
2152 /// String concatenation.
2153 Concat,
2154 /// String starts with.
2155 StartsWith,
2156 /// String ends with.
2157 EndsWith,
2158 /// String contains.
2159 Contains,
2160
2161 /// Collection membership (IN).
2162 In,
2163 /// Pattern matching (LIKE).
2164 Like,
2165 /// Regex matching (=~).
2166 Regex,
2167 /// Power/exponentiation (^).
2168 Pow,
2169}
2170
2171/// Unary operator.
2172#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2173pub enum UnaryOp {
2174 /// Logical NOT.
2175 Not,
2176 /// Numeric negation.
2177 Neg,
2178 /// IS NULL check.
2179 IsNull,
2180 /// IS NOT NULL check.
2181 IsNotNull,
2182}
2183
2184#[cfg(test)]
2185mod tests {
2186 use super::*;
2187
2188 #[test]
2189 fn test_simple_node_scan_plan() {
2190 let plan = LogicalPlan::new(LogicalOperator::Return(ReturnOp {
2191 items: vec![ReturnItem {
2192 expression: LogicalExpression::Variable("n".into()),
2193 alias: None,
2194 }],
2195 distinct: false,
2196 input: Box::new(LogicalOperator::NodeScan(NodeScanOp {
2197 variable: "n".into(),
2198 label: Some("Person".into()),
2199 input: None,
2200 })),
2201 }));
2202
2203 // Verify structure
2204 if let LogicalOperator::Return(ret) = &plan.root {
2205 assert_eq!(ret.items.len(), 1);
2206 assert!(!ret.distinct);
2207 if let LogicalOperator::NodeScan(scan) = ret.input.as_ref() {
2208 assert_eq!(scan.variable, "n");
2209 assert_eq!(scan.label, Some("Person".into()));
2210 } else {
2211 panic!("Expected NodeScan");
2212 }
2213 } else {
2214 panic!("Expected Return");
2215 }
2216 }
2217
2218 #[test]
2219 fn test_filter_plan() {
2220 let plan = LogicalPlan::new(LogicalOperator::Return(ReturnOp {
2221 items: vec![ReturnItem {
2222 expression: LogicalExpression::Property {
2223 variable: "n".into(),
2224 property: "name".into(),
2225 },
2226 alias: Some("name".into()),
2227 }],
2228 distinct: false,
2229 input: Box::new(LogicalOperator::Filter(FilterOp {
2230 predicate: LogicalExpression::Binary {
2231 left: Box::new(LogicalExpression::Property {
2232 variable: "n".into(),
2233 property: "age".into(),
2234 }),
2235 op: BinaryOp::Gt,
2236 right: Box::new(LogicalExpression::Literal(Value::Int64(30))),
2237 },
2238 input: Box::new(LogicalOperator::NodeScan(NodeScanOp {
2239 variable: "n".into(),
2240 label: Some("Person".into()),
2241 input: None,
2242 })),
2243 pushdown_hint: None,
2244 })),
2245 }));
2246
2247 if let LogicalOperator::Return(ret) = &plan.root {
2248 if let LogicalOperator::Filter(filter) = ret.input.as_ref() {
2249 if let LogicalExpression::Binary { op, .. } = &filter.predicate {
2250 assert_eq!(*op, BinaryOp::Gt);
2251 } else {
2252 panic!("Expected Binary expression");
2253 }
2254 } else {
2255 panic!("Expected Filter");
2256 }
2257 } else {
2258 panic!("Expected Return");
2259 }
2260 }
2261}