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