Skip to main content

relate_parser/ast/
clause.rs

1//! The query and update clause nodes.
2
3use super::*;
4
5/// CIP-135 conditional clause: `WHEN <pred> THEN { <body> } [WHEN <pred>
6/// THEN { <body> }]* [ELSE { <body> }]`. Each branch's `body`/`else_body`
7/// is itself a `<single-query>` (own `Statement`, possibly carrying its own
8/// `.union` chain).
9#[derive(Debug, Clone, PartialEq)]
10pub struct ConditionalClause {
11    pub branches: Vec<WhenBranch>,
12    pub else_body: Option<Statement>,
13}
14
15impl ConditionalClause {
16    /// The one body that stands in for the whole clause's output shape:
17    /// every branch and the ELSE body project the same shape (validated
18    /// separately), so the first WHEN branch represents them, falling back
19    /// to ELSE. `None` only for a clause with neither.
20    pub fn representative_body(&self) -> Option<&Statement> {
21        self.branches
22            .first()
23            .map(|b| &b.body)
24            .or(self.else_body.as_ref())
25    }
26}
27
28/// One `WHEN <predicate> THEN <single-query>` branch of a `ConditionalClause`.
29#[derive(Debug, Clone, PartialEq)]
30pub struct WhenBranch {
31    pub predicate: Expr,
32    pub body: Statement,
33}
34
35/// MATCH clause.
36#[derive(Debug, Clone, PartialEq)]
37pub struct MatchClause {
38    pub optional: bool,
39    /// CIP-51/CIP-60 match mode: whether relationship uniqueness (the
40    /// default `DIFFERENT RELATIONSHIPS`) is enforced across the whole
41    /// comma-separated graph pattern, or relaxed (`REPEATABLE ELEMENTS`).
42    pub match_mode: MatchMode,
43    pub pattern: Vec<PatternPath>,
44    /// CIP-79 variables named by a `USING SCAN <var>:<Label>` hint.
45    /// Relate's planner is not cost-based, but a scan hint is not a
46    /// mere plan preference here: an indexed equality seek and a label
47    /// scan genuinely answer differently for a zoned-datetime DST overlap
48    /// (the index keys on instant plus zone, `=` on the wall clock), so
49    /// the hint must reach the executor — the one hint family that does;
50    /// `USING INDEX` stops at the front-end fulfillability check and
51    /// `USING JOIN ON` at the plan-time notification, per the two
52    /// fields below.
53    pub using_scan: Vec<ScanHint>,
54    /// CIP-79 `USING INDEX [SEEK] <var>:<Label>(<prop>[, …])` hints. The
55    /// planner is not cost-based so they steer nothing, but the front end
56    /// still validates that each hint is *fulfillable* — Neo4j rejects an
57    /// undefined hint variable and an unfulfillable hint at compile time
58    /// (SemanticErrorPart2 "An index hint … is rejected"), which needs the
59    /// hint preserved here.
60    pub using_index: Vec<IndexHint>,
61    /// CIP-79 `USING JOIN ON <var>[, <var>…]` hints. The planner is not
62    /// cost-based so a join hint steers nothing — every one is
63    /// unfulfillable, which the `01N30` plan-time notification reports
64    /// (ADR-0363); retaining the hint here is what lets the IR carry it
65    /// to that detector.
66    pub using_join: Vec<JoinHint>,
67    pub where_expr: Option<Expr>,
68    /// `<search clause>`: `SEARCH <binding var ref> IN (VECTOR
69    /// INDEX <index name> FOR <expr> LIMIT <expr>) [SCORE AS <var>]`, a
70    /// subclause of `<match statement>`. The grammar allows the `<graph
71    /// pattern where clause>` to appear either before or after the search
72    /// clause with no semantic difference (CIP-224 "Canonical syntax"), so
73    /// the parser folds both orderings into this same `where_expr` field --
74    /// the source order isn't tracked in the AST.
75    pub search: Option<SearchClause>,
76}
77
78/// One `USING SCAN <variable>:<Label>` hint. The label is retained at the
79/// same fidelity as [`IndexHint`]'s properties, so the hint family keeps
80/// one shape; the planner's scan fork keys on the variable.
81#[derive(Debug, Clone, PartialEq, Eq)]
82pub struct ScanHint {
83    pub variable: SmallName,
84    pub label: SmallName,
85}
86
87/// One `USING INDEX [SEEK] <variable>:<Label>(<property>[, …])` hint.
88#[derive(Debug, Clone, PartialEq, Eq)]
89pub struct IndexHint {
90    pub variable: SmallName,
91    pub label: SmallName,
92    pub properties: Vec<SmallName>,
93}
94
95impl IndexHint {
96    /// The hinted property list as one text — `name`, `name, surname` —
97    /// the one spelling both the front end's unfulfillable-hint error
98    /// (42N76) and the plan-time `01N31` description render.
99    pub fn properties_text(&self) -> String {
100        self.properties
101            .iter()
102            .map(|property| property.to_string())
103            .collect::<Vec<_>>()
104            .join(", ")
105    }
106}
107
108/// One `USING JOIN ON <variable>[, <variable>…]` hint: the join key
109/// identifiers, in written order.
110#[derive(Debug, Clone, PartialEq, Eq)]
111pub struct JoinHint {
112    pub variables: Vec<SmallName>,
113}
114
115/// CIP-51/CIP-60 match mode: governs the default relationship-uniqueness
116/// pool that spans one MATCH clause's entire comma-separated graph pattern.
117#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
118pub enum MatchMode {
119    /// `MATCH DIFFERENT RELATIONSHIPS ...` (also the implicit default): no
120    /// two relationship slots anywhere in the graph pattern may bind to the
121    /// same physical relationship.
122    #[default]
123    DifferentRelationships,
124    /// `MATCH REPEATABLE ELEMENTS ...`: relaxes the relationship-uniqueness
125    /// pool entirely -- nodes and relationships may repeat freely, subject
126    /// only to each path's own path mode (which must resolve to `WALK`
127    /// under this match mode).
128    RepeatableElements,
129}
130
131/// CIP-51 path mode: an explicit restrictor on one path pattern's candidate
132/// bindings. `PatternPath::mode` is `None` when no explicit keyword was
133/// written -- the resolved default is `Walk`.
134#[derive(Debug, Clone, Copy, PartialEq, Eq)]
135pub enum PathMode {
136    /// Nodes and relationships may repeat freely (subject to the enclosing
137    /// match mode's own relationship-uniqueness pool, which under the
138    /// default `DIFFERENT RELATIONSHIPS` match mode still applies).
139    Walk,
140    /// No two relationship bindings in this one path may bind the same
141    /// relationship (already the effective default under `DIFFERENT
142    /// RELATIONSHIPS`, since that pool subsumes a single path's own).
143    Trail,
144    /// No two node bindings in this one path may bind the same node, except
145    /// where two connectors are juxtaposed at a shared boundary node.
146    Acyclic,
147    /// Like `Acyclic`, but the very first and very last node of the path may
148    /// coincide (an equijoin on the endpoints).
149    Simple,
150}
151
152/// The `<number of paths>`/`<number of groups>` non-terminal (extended
153/// by CIP-191 to accept a `$parameter`). A literal is validated
154/// (`> 0`) at parse time; a parameter is validated at runtime once its value
155/// is known (CIP-191 "Non-negative integer" rule).
156#[derive(Debug, Clone, PartialEq)]
157pub enum PathCount {
158    Literal(u32),
159    Parameter(String),
160}
161
162/// CIP-73 path selector prefix (`<path search prefix>`). `PatternPath` has
163/// no selector when this is `None` -- the path pattern is then
164/// non-selective, equivalent to an implicit `ALL`.
165#[derive(Debug, Clone, PartialEq)]
166pub enum PathSelector {
167    /// `ALL [path mode] [PATH|PATHS]` -- also the implicit default.
168    All,
169    /// `ANY [<number of paths>] [path mode] [PATH|PATHS]`; `None` count
170    /// defaults to 1.
171    Any(Option<PathCount>),
172    /// `ANY SHORTEST [path mode] [PATH|PATHS]` -- normalizes to `SHORTEST 1
173    /// [path mode] PATH`.
174    AnyShortest,
175    /// `ALL SHORTEST [path mode] [PATH|PATHS]` -- normalizes to `SHORTEST 1
176    /// [path mode] GROUP`.
177    AllShortest,
178    /// `SHORTEST <number of paths> [path mode] [PATH|PATHS]` (`group` false)
179    /// or `SHORTEST [<number of groups>] [path mode] [PATH|PATHS]
180    /// (GROUP|GROUPS)` (`group` true); `count` is `None` only in the GROUP
181    /// form (defaults to 1).
182    Shortest {
183        count: Option<PathCount>,
184        group: bool,
185    },
186}
187
188/// CREATE clause.
189#[derive(Debug, Clone, PartialEq)]
190pub struct CreateClause {
191    pub pattern: Vec<PatternPath>,
192    /// True when this clause was written as `INSERT` (CIP-114) rather than
193    /// `CREATE` -- executed identically in every other respect, but the
194    /// `+labels` side-effect stat is *not* subject to CREATE's row-scoped
195    /// same-label-name dedup (empirically, INSERT counts every label
196    /// application on every node it creates, unlike CREATE/MERGE).
197    pub is_insert: bool,
198}
199
200/// MERGE clause.
201#[derive(Debug, Clone, PartialEq)]
202pub struct MergeClause {
203    pub pattern: PatternPath,
204    pub on_create: Vec<SetItem>,
205    pub on_match: Vec<SetItem>,
206}
207
208/// DELETE clause.
209#[derive(Debug, Clone, PartialEq)]
210pub struct DeleteClause {
211    pub detach: bool,
212    pub expressions: Vec<Expr>,
213}
214
215/// SET clause.
216#[derive(Debug, Clone, PartialEq)]
217pub struct SetClause {
218    pub items: Vec<SetItem>,
219}
220
221/// A single item in a SET clause.
222#[derive(Debug, Clone, PartialEq)]
223pub struct SetItem {
224    pub property: Option<PropertyAccess>,
225    pub variable: Option<SmallName>,
226    /// Each element is a `LabelExpr::Label` (static, `SET n:A`) or
227    /// `LabelExpr::Dynamic` (CIP-162, `SET n:$(<expr>)`/`SET n IS $(<expr>)`)
228    /// atom -- the parser never produces any other `LabelExpr` variant here
229    /// (no `&`/`|`/`!`/`%`/grouping). See `RemoveItem::labels`.
230    pub labels: Vec<LabelExpr>,
231    pub value: Option<Expr>,
232    pub merge: bool,
233    /// True if this label item used the CIP-126 `IS` keyword (`SET n IS A`)
234    /// rather than `:` (`SET n:A`). Only meaningful when `labels` is
235    /// non-empty. Used for the CIP-40/CIP-126 statement-level rule that
236    /// forbids mixing `IS` with a colon-conjunction (`:A:B`) anywhere in the
237    /// same statement.
238    pub is_keyword: bool,
239    /// CIP-162 "Alternatives" section: `SET labels(<expr>) = / += / -=
240    /// <expr>`. Per the proposal's own text this was never shipped in Neo4j
241    /// ("we have decided to implement the rest first, and leave this as a
242    /// potential future extension") -- Relate implements it anyway as
243    /// the CIP's stated target semantics. `Some((target_expr, op))` when
244    /// this item is that form, with `target_expr` the node expression
245    /// inside `labels(...)` and `value` (above) holding the RHS list
246    /// expression.
247    pub labels_function: Option<(Expr, LabelsFunctionOp)>,
248}
249
250impl SetItem {
251    /// `SET <property> = <value>`.
252    pub fn property_assignment(property: PropertyAccess, value: Expr) -> Self {
253        Self {
254            property: Some(property),
255            variable: None,
256            labels: Vec::new(),
257            value: Some(value),
258            merge: false,
259            is_keyword: false,
260            labels_function: None,
261        }
262    }
263
264    /// `SET <variable> = <value>`, or `SET <variable> += <value>` when
265    /// `merge` is set.
266    pub fn variable_assignment(variable: SmallName, value: Expr, merge: bool) -> Self {
267        Self {
268            property: None,
269            variable: Some(variable),
270            labels: Vec::new(),
271            value: Some(value),
272            merge,
273            is_keyword: false,
274            labels_function: None,
275        }
276    }
277
278    /// `SET <variable>:<labels>` (or `IS <labels>` when `is_keyword`).
279    pub fn label_set(variable: SmallName, labels: Vec<LabelExpr>, is_keyword: bool) -> Self {
280        Self {
281            property: None,
282            variable: Some(variable),
283            labels,
284            value: None,
285            merge: false,
286            is_keyword,
287            labels_function: None,
288        }
289    }
290
291    /// `SET labels(<target>) <op> <value>`.
292    pub fn labels_function(target: Expr, op: LabelsFunctionOp, value: Expr) -> Self {
293        Self {
294            property: None,
295            variable: None,
296            labels: Vec::new(),
297            value: Some(value),
298            merge: false,
299            is_keyword: false,
300            labels_function: Some((target, op)),
301        }
302    }
303}
304
305/// The operator of a `SET labels(<expr>) <op> <expr>` item.
306#[derive(Debug, Clone, Copy, PartialEq, Eq)]
307pub enum LabelsFunctionOp {
308    /// `=` -- replace the full label set.
309    Overwrite,
310    /// `+=` -- add every listed label, keep existing ones.
311    Extend,
312    /// `-=` -- remove every listed label that is present.
313    Remove,
314}
315
316/// REMOVE clause.
317#[derive(Debug, Clone, PartialEq)]
318pub struct RemoveClause {
319    pub items: Vec<RemoveItem>,
320}
321
322/// A single item in a REMOVE clause.
323#[derive(Debug, Clone, PartialEq)]
324pub struct RemoveItem {
325    pub property: Option<PropertyAccess>,
326    pub variable: Option<SmallName>,
327    /// See `SetItem::labels` (CIP-162 dynamic-label atoms allowed here too).
328    pub labels: Vec<LabelExpr>,
329    /// See `SetItem::is_keyword`.
330    pub is_keyword: bool,
331}
332
333/// RETURN clause.
334#[derive(Debug, Clone, PartialEq)]
335pub struct ReturnClause {
336    pub group_by: Option<GroupBySpec>,
337    pub distinct: bool,
338    pub items: Vec<ReturnItem>,
339    pub order_by: Vec<OrderByItem>,
340    pub skip: Option<Expr>,
341    pub limit: Option<Expr>,
342}
343
344/// A single item in a RETURN clause.
345#[derive(Debug, Clone, PartialEq)]
346pub struct ReturnItem {
347    pub expr: Expr,
348    pub alias: Option<SmallName>,
349    pub all: bool,
350    pub source_text: Option<String>,
351}
352
353/// An item in ORDER BY.
354#[derive(Debug, Clone, PartialEq)]
355pub struct OrderByItem {
356    pub expr: Expr,
357    pub descending: bool,
358}
359
360/// Which surface syntax produced a `WithClause`. Plain `WITH`, CIP-206's
361/// `LET`, and CIP-203's `FILTER` all desugar into the same `WithClause` so
362/// they share WITH's projection/aggregation/ORDER BY/SKIP/LIMIT/WHERE
363/// execution machinery and its generic variable-scope tracking -- but LET
364/// and FILTER each carry restrictions ordinary WITH does not (LET: no
365/// shadowing of an in-scope variable, no sibling/forward/self reference
366/// within one LET's item list, no aggregation function in a value
367/// expression; FILTER: its search condition's declared type must be
368/// Boolean). The origin is recorded so the validation passes enforcing
369/// those extra rules only fire for the syntax that actually carries them.
370#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
371pub enum WithOrigin {
372    #[default]
373    Explicit,
374    Let,
375    Filter,
376}
377
378/// `<group by clause>` on RETURN/WITH.
379#[derive(Debug, Clone, PartialEq)]
380pub enum GroupBySpec {
381    /// `GROUP BY <expr> [, <expr>...]`
382    Keys(Vec<Expr>),
383    /// `GROUP BY ()` -- the empty grouping set: one global group.
384    Empty,
385    /// `GROUP BY ALL` -- every non-aggregating return item is a key.
386    All,
387}
388
389/// WITH clause.
390#[derive(Debug, Clone, PartialEq)]
391pub struct WithClause {
392    pub group_by: Option<GroupBySpec>,
393    pub distinct: bool,
394    pub items: Vec<ReturnItem>,
395    pub order_by: Vec<OrderByItem>,
396    pub skip: Option<Expr>,
397    pub limit: Option<Expr>,
398    pub where_expr: Option<Expr>,
399    pub origin: WithOrigin,
400}
401
402/// One stage of a CIP-168 standalone `<order by and page statement>`.
403/// Neo4j 2026.05 accepts `ORDER BY`/`OFFSET`/`SKIP`/`LIMIT` in any order
404/// at the start of the clause and applies them sequentially in the order
405/// written -- not the fixed ORDER-BY-then-OFFSET-then-LIMIT semantic
406/// order the CIP-168 text describes (e.g. `LIMIT 3 OFFSET 1` keeps 3
407/// rows then drops the first 1 of those, rather than offsetting first).
408/// A `Vec<PageStage>` records exactly the
409/// written sequence so execution can replay it faithfully.
410#[derive(Debug, Clone, PartialEq)]
411pub enum PageStage {
412    OrderBy(Vec<OrderByItem>),
413    Skip(Expr),
414    Limit(Expr),
415}
416
417/// CIP-168: a standalone `<order by and page statement>`. See
418/// `Clause::StandaloneOrderBy`.
419#[derive(Debug, Clone, PartialEq)]
420pub struct StandaloneOrderByClause {
421    pub stages: Vec<PageStage>,
422}
423
424/// UNWIND clause. A `FOR <variable> IN <expression>`
425/// clause normalizes here at parse time -- the same expr/alias pair with
426/// [`UnwindClause::for_syntax`] recording the source spelling -- so every
427/// downstream consumer (validation, lowering, planning, execution) treats
428/// the two spellings identically, exactly as the CIP requires (no new
429/// operators). The flag is the parse-spelling record the FOREACH-body
430/// renderer reads (`FOR`, not `UNWIND`, in the 42I01 text) — the one
431/// consumer that must distinguish the spellings.
432#[derive(Debug, Clone, PartialEq)]
433pub struct UnwindClause {
434    pub expr: Expr,
435    pub alias: SmallName,
436    /// True when the clause was written `FOR <variable> IN <expression>`
437    /// (CIP-250) rather than `UNWIND <expression> AS <variable>`.
438    pub for_syntax: bool,
439}
440
441/// FOREACH clause.
442#[derive(Debug, Clone, PartialEq)]
443pub struct ForeachClause {
444    pub variable: SmallName,
445    pub list_expr: Expr,
446    pub clauses: Vec<Clause>,
447}
448
449/// LOAD CSV clause.
450#[derive(Debug, Clone, PartialEq)]
451pub struct LoadCSVClause {
452    pub with_headers: bool,
453    pub source: Expr,
454    pub alias: SmallName,
455    pub field_terminator: Option<String>,
456}
457
458/// CALL { ... } subquery clause.
459#[derive(Debug, Clone, PartialEq)]
460pub struct CallSubqueryClause {
461    pub statement: Statement,
462    /// CIP-141 variable scope clause: `None` for a naked `CALL { ... }`
463    /// (the deprecated legacy form, where an `IMPORTING WITH` as the
464    /// subquery's own first clause is the only way to correlate outer
465    /// variables in); `Some(CallScope::...)` for `CALL (...) { ... }`.
466    pub scope: CallScope,
467    /// `OPTIONAL CALL { ... }` -- when the inline subquery yields
468    /// zero rows for a given outer row, that outer row is null-padded
469    /// (every column the subquery would export set to `NULL`) instead of
470    /// being dropped.
471    pub optional: bool,
472    /// CIP-32/CIP-34/CIP-198/CIP-30 trailing `IN [<concExpr>] CONCURRENT?
473    /// TRANSACTIONS [OF <n> ROW(S)] [ON ERROR ...] [REPORT STATUS AS
474    /// <var>]` production. `None` for a plain `CALL { ... }` subquery.
475    pub in_transactions: Option<InTransactionsClause>,
476}
477
478/// The full `IN [<concExpr>] CONCURRENT? TRANSACTIONS [OF <n> ROW|ROWS] [ON
479/// ERROR ...] [REPORT STATUS AS <var>]` production trailing a CALL
480/// subquery. Parsed in its entirety (CIP-32 base batching, CIP-34
481/// concurrency, CIP-198 retry, CIP-30 status/error) so later CIPs only need
482/// to add validation/execution on top of this AST -- CIP-32 itself only
483/// implements sequential batching plus the nesting/preceding-write
484/// restrictions; concurrency and retry are parsed but currently execute as
485/// plain sequential batching (see `Engine`'s `Clause::CallSubquery` arm).
486#[derive(Debug, Clone, PartialEq)]
487pub struct InTransactionsClause {
488    /// `IN TRANSACTIONS` (no `CONCURRENT`) vs `IN [<expr>] CONCURRENT
489    /// TRANSACTIONS` (CIP-34).
490    pub concurrency: Concurrency,
491    /// `OF <n> ROW|ROWS`. `None` means the batch size is
492    /// implementation-chosen (batching[6]).
493    pub batch_size: Option<Expr>,
494    /// `ON ERROR CONTINUE|BREAK|FAIL|RETRY ...`. Defaults to `Fail` when
495    /// `ON ERROR` is omitted.
496    pub on_error: OnErrorMode,
497    /// `REPORT STATUS AS <var>` (CIP-30).
498    pub report_status: Option<SmallName>,
499    /// CIP-260 `DISJOINT BY <exprs> | AUTO | NONE`. A concurrency hint that
500    /// partitions the input rows by the listed key expressions (or lets the
501    /// implementation choose / disables disjointness); it never changes the
502    /// statement's result. Only legal on the `CONCURRENT` form.
503    pub disjoint: Option<DisjointBy>,
504}
505
506/// `DISJOINT BY` operand.
507#[derive(Debug, Clone, PartialEq)]
508pub enum DisjointBy {
509    /// `DISJOINT BY (<expr>, ...)`: partition rows by these deterministic
510    /// key expressions.
511    Expressions(Vec<Expr>),
512    /// `DISJOINT BY AUTO`: the implementation picks the partitioning.
513    Auto,
514    /// `DISJOINT BY NONE`: no disjointness requirement.
515    None,
516}
517
518impl InTransactionsClause {
519    /// Every value expression of the `IN TRANSACTIONS` tail, in visit
520    /// order: the CIP-34 concurrency value, the CIP-32 batch size, the
521    /// CIP-198 retry duration and the `DISJOINT BY` key
522    /// expressions. The exhaustive matches on the three operand enums are
523    /// the slot list: a new operand variant is a compile error here until
524    /// its expression is enumerated, so a consumer cannot drift from the
525    /// parser shape.
526    pub fn exprs(&self) -> Vec<&Expr> {
527        let mut out = Vec::new();
528        match &self.concurrency {
529            Concurrency::Value(expr) => out.push(expr),
530            Concurrency::Sequential | Concurrency::DefaultUnspecified => {}
531        }
532        out.extend(self.batch_size.as_ref());
533        match &self.on_error {
534            OnErrorMode::Retry { duration, .. } => out.extend(duration.as_ref()),
535            OnErrorMode::Fail | OnErrorMode::Continue | OnErrorMode::Break => {}
536        }
537        match &self.disjoint {
538            Some(DisjointBy::Expressions(keys)) => out.extend(keys),
539            Some(DisjointBy::Auto | DisjointBy::None) | None => {}
540        }
541        out
542    }
543}
544
545/// CIP-34 `IN [<concExpr>] CONCURRENT? TRANSACTIONS` concurrency modifier.
546#[derive(Debug, Clone, PartialEq)]
547pub enum Concurrency {
548    /// No `CONCURRENT` keyword -- sequential (base CIP-32 form).
549    Sequential,
550    /// `CONCURRENT` with no explicit value -- implementation-chosen
551    /// concurrency.
552    DefaultUnspecified,
553    /// `<expr> CONCURRENT` -- an explicit concurrency value.
554    Value(Expr),
555}
556
557/// `ON ERROR ...` mode.
558#[derive(Debug, Clone, PartialEq)]
559pub enum OnErrorMode {
560    /// The default when `ON ERROR` is omitted entirely.
561    Fail,
562    Continue,
563    Break,
564    /// CIP-198 `RETRY [FOR]? [<dur> SEC|SECOND|SECONDS]? [THEN
565    /// CONTINUE|BREAK|FAIL]?`.
566    Retry {
567        /// `FOR <dur> SEC[OND[S]]`; `None` means the retry duration is
568        /// implementation-chosen.
569        duration: Option<Expr>,
570        /// The mode to fall back to once retries are exhausted. Defaults to
571        /// `Fail` when no `THEN` clause is given (CIP-198's documented
572        /// deviation from a naive "defaults to CONTINUE" reading).
573        fallback: RetryFallback,
574    },
575}
576
577/// The `THEN CONTINUE|BREAK|FAIL` fallback mode of `ON ERROR RETRY`.
578#[derive(Debug, Clone, PartialEq)]
579pub enum RetryFallback {
580    Fail,
581    Continue,
582    Break,
583}
584
585/// The `(...)` variable scope clause on a `CALL` subquery (CIP-141).
586#[derive(Debug, Clone, PartialEq)]
587pub enum CallScope {
588    /// Naked `CALL { ... }` -- no scope clause at all.
589    None,
590    /// `CALL (*) { ... }` -- import every variable currently in scope.
591    Wildcard,
592    /// `CALL (a, b) { ... }` / `CALL () { ... }` -- import exactly these
593    /// variables (the list may be empty).
594    Vars(Vec<SmallName>),
595}
596
597/// `USE <graph-expr>` clause.
598#[derive(Debug, Clone, PartialEq)]
599pub struct UseClause {
600    pub graph_expr: Expr,
601}
602
603/// CALL db.procedure() YIELD ... clause.
604#[derive(Debug, Clone, PartialEq)]
605pub struct CallProcedureClause {
606    pub procedure: SmallName,
607    pub args: Vec<Expr>,
608    /// Whether the procedure name was followed by an explicit argument list,
609    /// including an empty `()`. Relate needs this to distinguish `CALL p`
610    /// (implicit arguments) from `CALL p()` (no arguments).
611    pub explicit_args: bool,
612    pub yields: YieldList,
613    /// CIP-159: `OPTIONAL CALL proc(...)` -- when the procedure call yields
614    /// zero rows (after any `WHERE` in `YIELD`) for a given outer row, that
615    /// outer row is null-padded instead of being dropped. Void-procedure
616    /// and zero-outer-row semantics are handled by the engine.
617    pub optional: bool,
618    /// CIP-159: `WHERE` inside the `YIELD` clause -- part of the
619    /// `<procedure call>` production, filtering the procedure's own result
620    /// rows (may reference the outer row's variables) before they're
621    /// merged into the pipeline.
622    pub where_expr: Option<Expr>,
623}
624
625// -- Pattern nodes --