Skip to main content

relate_parser/ast/
clause.rs

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