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