relate_parser/ast.rs
1use relate_names::SmallName;
2
3/// AST node types for the Cypher parser.
4///
5/// The AST uses enums for Clause, Expr, and PatternElement to avoid trait objects.
6/// Literal values use native Rust types (not CypherValue) since the AST is a compile-time concept.
7///
8/// Top-level AST node for a Cypher statement.
9#[derive(Debug, Clone, Default)]
10pub struct Statement {
11 pub clauses: Vec<Clause>,
12 pub union: Option<Box<UnionPart>>,
13 pub explain: bool,
14 pub profile: bool,
15 /// CIP-213 `<statement block> ::= <statement> [<next statement>...]`,
16 /// `<next statement> ::= NEXT <statement>`. `next` chains this
17 /// statement (which may itself carry its own `.union` chain, or be a
18 /// sole `Clause::Conditional`) to the following NEXT stage's own
19 /// statement (which may in turn have a `.next` of its own). `None`
20 /// means this is either not part of a NEXT chain, or is its final
21 /// stage. Deliberately a *sibling* field to `union`/`Conditional`
22 /// rather than nested inside them: per the CIP grammar, NEXT operates
23 /// on a whole `<statement>` (union-chain-or-conditional), one level
24 /// above where UNION/WHEN operate, so it's threaded through the
25 /// outermost `Statement` of each stage only -- a stage's own `.union`
26 /// arms never carry their own independent `.next` chain.
27 pub next: Option<Box<Statement>>,
28 /// CIP-150: the effective Cypher language version explicitly requested
29 /// by a `CYPHER <version>` statement preamble (`5` or `25`), or `None`
30 /// if the query had no version-bearing preamble clause at all (a
31 /// version-less `CYPHER <options>` clause with no `<cypher version>`
32 /// token also leaves this `None`). Only ever set on the outermost
33 /// `Statement` a top-level `parse()` call returns -- the preamble is
34 /// parsed once, before any clause, so nested statements (UNION arms,
35 /// `CALL`/`EXISTS`/`COUNT` subquery bodies, NEXT stages) never carry
36 /// their own value here and consumers must read it off the top-level
37 /// statement. `None` means "use the session/database default
38 /// language", which Relate always resolves to 25 (its only
39 /// implemented dialect) since it has no CIP-170 default-language
40 /// configuration surface.
41 pub cypher_version: Option<u32>,
42 /// CIP-146/CIP-242: true when this `SingleQuery` was written as
43 /// `[ USE <graph-expr> ] '{' <RegularQuery> '}'` -- top-level braces --
44 /// rather than the plain unbraced form. The brace form's *content* is
45 /// otherwise indistinguishable from an unbraced statement (same clause
46 /// list, same `.union` chain) once parsed, but CIP-242's SHOW/TERMINATE
47 /// composability rule ("Composing a SHOW command without YIELD fails")
48 /// treats an explicitly brace-wrapped bare `SHOW` (e.g. `{ SHOW INDEXES
49 /// }`) as *composed*, requiring `YIELD`, even though the identical
50 /// clause list unbraced (`SHOW INDEXES` alone) is the lenient
51 /// "canonical standalone" form that doesn't need one -- so this needs
52 /// its own marker distinct from clause shape. Set only by
53 /// `parse_braced_single_query`; every other `Statement` constructor
54 /// leaves it `false` (via `#[derive(Default)]` field-by-field
55 /// construction elsewhere).
56 pub brace_wrapped: bool,
57 /// CIP-231: the `DEFINE <procedure definition> | <function
58 /// definition>` block parsed at the head of this statement block (only
59 /// the top-level statement and braced nested bodies carry definitions;
60 /// every statement-block parse site funnels through
61 /// `parse_statement_block`, where they are parsed). Rewritten away --
62 /// definitions and their call sites eliminated -- by the front-end
63 /// resolver (`relate-front`'s `local_callables`) before lowering;
64 /// the planner/executor never see local callables. `Default`-empty so
65 /// the derived and hand-written constructors of un-gated statements
66 /// are unchanged.
67 pub definitions: Vec<LocalDefinition>,
68}
69
70/// Manual `PartialEq`: deliberately ignores `brace_wrapped`. CIP-146's own
71/// "Semantics Step 3, Unwrap Case 1" -- and the parser tests pinning it
72/// (`test_brace_enclosed_top_level_query_is_transparent` and friends) --
73/// treat a brace-wrapped `SingleQuery` as producing an AST indistinguishable
74/// from its unbraced spelling; `brace_wrapped` is out-of-band provenance a
75/// couple of CIP-242 composability checks read directly off the field
76/// (`validate_show_composability`), not part of that observable-content
77/// equivalence.
78impl PartialEq for Statement {
79 fn eq(&self, other: &Self) -> bool {
80 self.clauses == other.clauses
81 && self.union == other.union
82 && self.explain == other.explain
83 && self.profile == other.profile
84 && self.next == other.next
85 && self.cypher_version == other.cypher_version
86 && self.definitions == other.definitions
87 }
88}
89
90/// CIP-231 `DEFINE` block entry: one local callable definition, parsed at
91/// the head of a `<statement block>` (top level or a braced nested body)
92/// and rewritten away by the front-end resolver
93/// (`relate-front`'s `local_callables`) before lowering -- the
94/// planner/executor never see local callables.
95#[derive(Debug, Clone, PartialEq)]
96pub struct LocalDefinition {
97 /// `PROCEDURE` or `FUNCTION`.
98 pub kind: LocalCallableKind,
99 /// The fully-qualified callable name as written (`foo.bar`), namespace
100 /// segments joined on `.`. Matched against call-site names verbatim.
101 pub name: SmallName,
102 /// The `<callable input signature>`: parameters in declaration order.
103 pub params: Vec<LocalParam>,
104 /// The declared `<procedure output type>` (`(field :: T, ...)`) or
105 /// `<function output type>` (`:: T`), when written.
106 pub output: Option<LocalOutput>,
107 /// `= <value expression>` (simple function body) or a braced
108 /// `<procedure specification>` (procedure body or subquery function
109 /// body).
110 pub body: LocalDefinitionBody,
111}
112
113/// `DEFINE PROCEDURE` vs `DEFINE FUNCTION` (CIP-231). The two namespaces
114/// are independent (CIP-230: a procedure and a function may share a name).
115#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
116pub enum LocalCallableKind {
117 Procedure,
118 Function,
119}
120
121/// One `<input field signature>` of a local callable (CIP-231): a field
122/// name, an optional `[<typed>] <value type>`, and an optional
123/// `= <value expression>` default (which makes the parameter optional).
124#[derive(Debug, Clone, PartialEq)]
125pub struct LocalParam {
126 pub name: SmallName,
127 /// The written value type, `None` when omitted (implicitly ANY).
128 /// Parsed and syntactically validated, deliberately not enforced at
129 /// runtime (ADR-0382, NOTES.md).
130 pub type_expr: Option<TypeExpr>,
131 /// `= <value expression>`; `None` for a mandatory parameter. Defaults
132 /// may not reference variables (checked at parse time).
133 pub default: Option<Expr>,
134}
135
136/// A declared output type of a local callable (CIP-231): the procedure
137/// form `:: (a :: INT, ...)` or the function form `:: STRING`.
138#[derive(Debug, Clone, PartialEq)]
139pub enum LocalOutput {
140 /// `:: (<mandatory field signature>, ...)` on a procedure.
141 Fields(Vec<LocalOutputField>),
142 /// `:: <value type>` on a function.
143 Type(TypeExpr),
144}
145
146/// One field of a procedure's `:: (a :: INT, ...)` output signature.
147#[derive(Debug, Clone, PartialEq)]
148pub struct LocalOutputField {
149 pub name: SmallName,
150 pub type_expr: Option<TypeExpr>,
151}
152
153/// The body of a local callable definition (CIP-231).
154#[derive(Debug, Clone, PartialEq)]
155pub enum LocalDefinitionBody {
156 /// `FUNCTION f(...) = <value expression>` (simple function body).
157 Expression(Expr),
158 /// A braced `<procedure specification>`: a procedure body, or a
159 /// subquery function body.
160 Query(Statement),
161}
162
163/// Represents a UNION or UNION ALL between statements.
164#[derive(Debug, Clone, PartialEq)]
165pub struct UnionPart {
166 pub all: bool,
167 pub statement: Statement,
168}
169
170/// All clause types in the Cypher language.
171#[derive(Debug, Clone, PartialEq)]
172pub enum Clause {
173 Match(MatchClause),
174 Create(CreateClause),
175 Merge(MergeClause),
176 Delete(DeleteClause),
177 Set(SetClause),
178 Remove(RemoveClause),
179 Return(ReturnClause),
180 With(WithClause),
181 Unwind(UnwindClause),
182 CreateIndex(CreateIndexClause),
183 DropIndex(DropIndexClause),
184 CreateConstraint(CreateConstraintClause),
185 DropConstraint(DropConstraintClause),
186 Foreach(ForeachClause),
187 LoadCSV(LoadCSVClause),
188 CallSubquery(CallSubqueryClause),
189 CallProcedure(CallProcedureClause),
190 ShowFunctions(ShowFunctionsClause),
191 ShowConstraints(ShowConstraintsClause),
192 ShowIndexes(ShowIndexesClause),
193 /// `SHOW DATABASE[S] [<name>] [YIELD ...] [WHERE ...]` / `SHOW DEFAULT
194 /// DATABASE` / `SHOW HOME DATABASE` (CIP-68's singular/plural KIND
195 /// acceptance; CIP-42's four non-default columns). A minimal virtual
196 /// catalog -- Relate is a single-database engine, so this reports a
197 /// small set of deterministic built-in databases rather than modeling
198 /// real multi-database administration.
199 ShowDatabases(ShowDatabasesClause),
200 /// `SHOW [ALL|POPULATED] ROLE[S] [WITH USER[S]] [YIELD ...] [WHERE ...]`
201 /// (CIP-68). A minimal virtual catalog of built-in roles.
202 ShowRoles(ShowRolesClause),
203 /// `SHOW SERVER[S] [YIELD ...] [WHERE ...]` (CIP-68). Reports a single
204 /// row, matching a single-process embedded engine.
205 ShowServers(ShowServersClause),
206 /// `SHOW USER[S] [YIELD ...] [WHERE ...]` / `SHOW CURRENT USER`
207 /// (CIP-68). A minimal virtual catalog of a single built-in user.
208 ShowUsers(ShowUsersClause),
209 /// `SHOW PROCEDURE[S] [YIELD ...] [WHERE ...]` (CIP-68 grammar
210 /// foundation). Lists the built-in procedure names the engine's `CALL`
211 /// handler recognizes.
212 ShowProcedures(ShowProceduresClause),
213 /// `SHOW SETTING[S] [<names>] [YIELD ...] [WHERE ...]` (CIP-68 grammar
214 /// foundation). Relate has no configurable settings surface, so
215 /// this always reports an empty catalog.
216 ShowSettings(ShowSettingsClause),
217 /// `SHOW TRANSACTION[S] [<ids>] [YIELD ...] [WHERE ...]` (CIP-68
218 /// grammar foundation). Relate executes each statement to
219 /// completion without exposing concurrent transaction identifiers, so
220 /// this always reports an empty catalog.
221 ShowTransactions(ShowTransactionsClause),
222 /// `TERMINATE TRANSACTION[S] <ids> [YIELD ...]` (CIP-68 grammar
223 /// foundation). Since `ShowTransactions` never reports a live
224 /// transaction, every requested id is reported as not found.
225 TerminateTransactions(TerminateTransactionsClause),
226 /// `USE <graph-expr>` (CIP-141 feature-interaction scenarios) -- a
227 /// graph-selector clause. Relate is a single-database engine, so
228 /// this is parsed and scope-checked (its expression's variables must
229 /// be in scope, same as any other clause) but has no runtime effect
230 /// beyond that: there is no composite/multi-graph database to switch
231 /// to.
232 Use(UseClause),
233 /// `FINISH` (CIP-140) -- a terminal clause producing a truly empty
234 /// result (0 rows, 0 columns) instead of RETURN's projected rows,
235 /// while still running any earlier updating clauses. Only the minimal
236 /// semantics needed by CIP-218's `CALL (a) { FINISH }` scenario are
237 /// implemented: cardinality is preserved (one output row per input
238 /// row) but that row carries no columns, so it contributes nothing
239 /// when merged back into an enclosing CALL's outer row.
240 Finish,
241 /// CIP-168: a standalone `<order by and page statement>` -- e.g.
242 /// `ORDER BY n.name SKIP 1 LIMIT 3` appearing as its own clause, not
243 /// attached to WITH/RETURN/YIELD. Acts as an implicit `WITH *`
244 /// horizon clause: changes row order/count but never the column set,
245 /// and may sit between any two other clauses (including two write
246 /// clauses). See `StandaloneOrderByClause` for why this is a sequence
247 /// of stages rather than three fixed fields.
248 StandaloneOrderBy(StandaloneOrderByClause),
249 /// CIP-135: a standalone conditional clause chain --
250 /// `<when query> ::= <when>, {<when>}, [<else>]`. This is a *sibling*
251 /// alternative to `<union query>`/`<single query>` at the `<regular
252 /// query>` grammar level (see `parse_regular_query`), not an ordinary
253 /// mid-statement clause -- so this variant only ever appears as the
254 /// sole element of a `Statement.clauses` vec, never alongside other
255 /// clauses in the same statement.
256 Conditional(ConditionalClause),
257 /// `ALTER CURRENT GRAPH TYPE SET/ADD/ALTER/DROP { <graph type
258 /// specification body> }` (CIP-176/182/183's mechanism; CIP-187's
259 /// constraint derivation builds on it). `body` is the full CIP-178
260 /// `<graph type specification body>` grammar (node/edge type specs,
261 /// property types, and constraint specs) -- see `GraphTypeBody`.
262 AlterCurrentGraphType(AlterCurrentGraphTypeClause),
263 /// `CREATE GRAPH TYPE <name> [AS] { <graph type specification body> }`
264 /// (CIP-178 grammar; the `AS` keyword is CIP-180's spelling of the same
265 /// body-introducing form). Registers a *named* graph type, independent
266 /// of the database's single unnamed "current" graph type that `ALTER
267 /// CURRENT GRAPH TYPE` manages.
268 CreateGraphType(CreateGraphTypeClause),
269 /// `SHOW GRAPH TYPE <name> [YIELD ...]` (CIP-180's SHOW surface): a
270 /// single-row catalog whose `name`/`body` columns report the named
271 /// graph type's own name and its CIP-180 canonical specification
272 /// string.
273 ShowGraphType(ShowGraphTypeClause),
274 /// `SHOW CURRENT GRAPH TYPE [YIELD ...]` (CIP-176 overview / CIP-184):
275 /// the database's persistent current graph type, reported as a single
276 /// `specification` column (the CIP-180 canonical body string wrapped in
277 /// `{ }`, or the literal `{}` when empty).
278 ShowCurrentGraphType(ShowCurrentGraphTypeClause),
279 /// `ALTER DATABASE <name> [IF EXISTS] SET DEFAULT LANGUAGE CYPHER
280 /// <n>` (CIP-170). Under ADR-0116 §2's fixed namespaces this is the
281 /// only supported `ALTER DATABASE` form; every other form is
282 /// recognized and rejected at parse time with CE's
283 /// `UnsupportedAdministrationCommand`.
284 AlterDatabase(AlterDatabaseClause),
285}
286
287impl Clause {
288 /// The Cypher clause keyword(s) for this clause — e.g. `"MATCH"`,
289 /// `"SHOW INDEXES"`, `"LOAD CSV"`. Exhaustive over the enum, so a new
290 /// clause cannot ship without a renderable name; the planner's
291 /// `clause_keyword` delegates here rather than keeping a second table.
292 pub fn keyword(&self) -> &'static str {
293 match self {
294 Clause::Match(_) => "MATCH",
295 Clause::Create(_) => "CREATE",
296 Clause::Merge(_) => "MERGE",
297 Clause::Delete(_) => "DELETE",
298 Clause::Set(_) => "SET",
299 Clause::Remove(_) => "REMOVE",
300 Clause::Return(_) => "RETURN",
301 Clause::With(_) => "WITH",
302 Clause::Unwind(_) => "UNWIND",
303 Clause::CreateIndex(_) => "CREATE INDEX",
304 Clause::DropIndex(_) => "DROP INDEX",
305 Clause::CreateConstraint(_) => "CREATE CONSTRAINT",
306 Clause::DropConstraint(_) => "DROP CONSTRAINT",
307 Clause::Foreach(_) => "FOREACH",
308 Clause::LoadCSV(_) => "LOAD CSV",
309 Clause::CallSubquery(_) | Clause::CallProcedure(_) => "CALL",
310 Clause::ShowFunctions(_) => "SHOW FUNCTIONS",
311 Clause::ShowConstraints(_) => "SHOW CONSTRAINTS",
312 Clause::ShowIndexes(_) => "SHOW INDEXES",
313 Clause::ShowDatabases(_) => "SHOW DATABASES",
314 Clause::ShowRoles(_) => "SHOW ROLES",
315 Clause::ShowServers(_) => "SHOW SERVERS",
316 Clause::ShowUsers(_) => "SHOW USERS",
317 Clause::ShowProcedures(_) => "SHOW PROCEDURES",
318 Clause::ShowSettings(_) => "SHOW SETTINGS",
319 Clause::ShowTransactions(_) => "SHOW TRANSACTIONS",
320 Clause::TerminateTransactions(_) => "TERMINATE TRANSACTIONS",
321 Clause::Use(_) => "USE",
322 Clause::Finish => "FINISH",
323 Clause::StandaloneOrderBy(_) => "ORDER BY",
324 Clause::Conditional(_) => "WHEN",
325 Clause::AlterCurrentGraphType(_) => "ALTER CURRENT GRAPH TYPE",
326 Clause::CreateGraphType(_) => "CREATE GRAPH TYPE",
327 Clause::ShowGraphType(_) => "SHOW GRAPH TYPE",
328 Clause::ShowCurrentGraphType(_) => "SHOW CURRENT GRAPH TYPE",
329 Clause::AlterDatabase(_) => "ALTER DATABASE",
330 }
331 }
332}
333
334/// See `Clause::AlterDatabase`.
335#[derive(Debug, Clone, PartialEq)]
336pub struct AlterDatabaseClause {
337 pub name: SchemaName,
338 pub if_exists: bool,
339 /// The `SET DEFAULT LANGUAGE CYPHER <n>` digits (e.g. `5`, `25`, or an
340 /// unsupported value like `6`), unvalidated at parse time -- CIP-170
341 /// NOTES.md Deviations #2: an out-of-range version here is a *runtime*
342 /// data exception (`22N04`), unlike the CIP-150 statement-preamble
343 /// `CYPHER <version>` prefix, which rejects at compile time.
344 pub default_language: u32,
345}
346
347/// See `Clause::AlterCurrentGraphType`.
348#[derive(Debug, Clone, PartialEq)]
349pub struct AlterCurrentGraphTypeClause {
350 pub verb: AlterGraphTypeVerb,
351 pub target: AlterCurrentGraphTypeTarget,
352}
353
354/// What an `ALTER CURRENT GRAPH TYPE` verb applies: an inline `{ <body> }`,
355/// or — ADR-0211's `ALTER CURRENT GRAPH TYPE SET GRAPH TYPE <name>` — a
356/// reference to a `CREATE GRAPH TYPE`-declared named type, promoted to
357/// current. The invalid combinations (a verb body *and* a named reference)
358/// are unrepresentable; no parser placeholder and no consumer-side doc
359/// invariant.
360#[derive(Debug, Clone, PartialEq)]
361pub enum AlterCurrentGraphTypeTarget {
362 Body(GraphTypeBody),
363 Named(SmallName),
364}
365
366/// One `YIELD <name> [AS <alias>]` item of a procedure call or catalog
367/// command. `alias` is `None` when no `AS` was written, so "no alias" is
368/// represented by the optional itself rather than an empty-string sentinel
369/// in a parallel array.
370#[derive(Debug, Clone, PartialEq, Eq)]
371pub struct YieldItem {
372 pub name: SmallName,
373 pub alias: Option<SmallName>,
374}
375
376impl YieldItem {
377 /// The name this item binds in the enclosing scope: the alias when one
378 /// was written, else the yielded column name. A `SmallName` copy (the
379 /// inline arm is a `u64` move, the spilled arm a refcount bump,
380 /// ADR-0509 §1) — consumers bridging into a `String`-keyed scope map
381 /// pay the text conversion at that one feed site.
382 pub fn effective_name(&self) -> SmallName {
383 self.alias.clone().unwrap_or_else(|| self.name.clone())
384 }
385}
386
387/// A clause's `YIELD` tail, modeled once: the explicit items in source
388/// order plus whether `YIELD *` was written. Empty `items` with `all ==
389/// false` means no `YIELD` at all (the grammar never reads an empty
390/// explicit list).
391#[derive(Debug, Clone, PartialEq, Eq, Default)]
392pub struct YieldList {
393 pub items: Vec<YieldItem>,
394 pub all: bool,
395}
396
397/// A clause's yield mode, derived once from its [`YieldList`]: `YIELD *`
398/// projects every column, a bare clause its default table, and an explicit
399/// list its named (post-alias) columns. Consumers select their behavior
400/// from this instead of each re-testing `(all, is_empty)`.
401#[derive(Debug, Clone, Copy, PartialEq, Eq)]
402pub enum YieldMode {
403 /// `YIELD *`: every column of the command.
404 Star,
405 /// No `YIELD` at all: the command's default table.
406 Default,
407 /// An explicit `YIELD` list: the named, post-alias columns.
408 Named,
409}
410
411impl YieldList {
412 /// The clause's yield mode — the one derivation.
413 pub fn mode(&self) -> YieldMode {
414 if self.all {
415 YieldMode::Star
416 } else if self.items.is_empty() {
417 YieldMode::Default
418 } else {
419 YieldMode::Named
420 }
421 }
422
423 /// Whether any `YIELD` tail was written (an explicit list or `*`).
424 pub fn present(&self) -> bool {
425 !matches!(self.mode(), YieldMode::Default)
426 }
427
428 /// Each item's raw yielded name, in source order.
429 pub fn names(&self) -> impl Iterator<Item = &SmallName> {
430 self.items.iter().map(|item| &item.name)
431 }
432
433 /// Each item's raw name, optional alias, and effective (post-alias)
434 /// name, in source order. Consumers that need both sides of the alias
435 /// rule read them from this one iterator instead of re-deriving the
436 /// precedence.
437 pub fn pairs(&self) -> impl Iterator<Item = (&SmallName, Option<&SmallName>, SmallName)> {
438 self.items
439 .iter()
440 .map(|item| (&item.name, item.alias.as_ref(), item.effective_name()))
441 }
442
443 /// Each item's effective (post-alias) name, in source order.
444 pub fn effective_names(&self) -> impl Iterator<Item = SmallName> + '_ {
445 self.items.iter().map(YieldItem::effective_name)
446 }
447}
448
449/// See `Clause::ShowCurrentGraphType`.
450#[derive(Debug, Clone, PartialEq, Default)]
451pub struct ShowCurrentGraphTypeClause {
452 pub yields: YieldList,
453 /// Paging stages following YIELD, preserved in source order.
454 pub stages: Vec<PageStage>,
455 /// CIP-184: an optional trailing `WHERE <expr>`, permitted with or
456 /// without an explicit `YIELD` (mirrors `ShowDatabasesClause`).
457 pub where_expr: Option<Expr>,
458 /// CIP-257: `AS GRAPH [SINGLE | SEPARATE]` -- renders the current graph
459 /// type as `nodes`/`relationships` columns instead of the plain
460 /// `specification` string column. `None` when `AS GRAPH` wasn't
461 /// written at all.
462 pub as_graph: Option<AnyNodeMode>,
463}
464
465/// CIP-257's "Future improvements" any-node keyword, controlling how many
466/// synthetic `(:AnyLabel {})` nodes an unconstrained relationship endpoint
467/// gets: `Separate` (the default, whether or not the keyword is written) --
468/// one any-node per relationship that needs one; `Single` -- every
469/// unconstrained endpoint across the whole graph type shares one any-node.
470#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
471pub enum AnyNodeMode {
472 #[default]
473 Separate,
474 Single,
475}
476
477/// The four `ALTER CURRENT GRAPH TYPE` verbs (CIP-176/CIP-182 overview
478/// scope): `SET` replaces the whole current graph type (and, as observed
479/// live, every constraint in the database -- CIP-187 NOTES.md); `ADD`
480/// extends it; `ALTER` replaces an existing element type (matched by
481/// identifying label) with a new declaration; `DROP` removes the element
482/// types named in its body.
483#[derive(Debug, Clone, Copy, PartialEq, Eq)]
484pub enum AlterGraphTypeVerb {
485 Set,
486 Add,
487 Alter,
488 Drop,
489}
490
491/// See `Clause::CreateGraphType`.
492#[derive(Debug, Clone, PartialEq)]
493pub struct CreateGraphTypeClause {
494 pub name: SmallName,
495 pub body: GraphTypeBody,
496 /// Whether the `AS` spelling was used (CIP-180's own scaffolding form,
497 /// `CREATE GRAPH TYPE <name> AS { <body> }`, vs. CIP-178's plain
498 /// `CREATE GRAPH TYPE <name> { <body> }`). CIP-180's own worked
499 /// example (`()-[:REL =>]->()`, no properties, both endpoints the any
500 /// type) violates CIP-178 Rule 9 (an ineffectual single-label edge
501 /// type) -- the `AS` form exists to exercise the CIP-180 canonicalizer,
502 /// so the engine's `CreateGraphType` handler exempts it from Rule 9 and
503 /// the one-index-backing-per-subject clash (both shapes CIP-180's own
504 /// scenarios use), and validates every other body rule normally.
505 pub via_as: bool,
506}
507
508/// See `Clause::ShowGraphType`.
509#[derive(Debug, Clone, PartialEq)]
510pub struct ShowGraphTypeClause {
511 pub name: SmallName,
512 pub yields: YieldList,
513}
514
515/// A fully parsed `<graph type specification body>` (CIP-178): the `{
516/// ... }` contents shared by `CreateGraphTypeClause` and
517/// `AlterCurrentGraphTypeClause`. Parsing is grammar-only (always succeeds
518/// once the tokens match); the CIP-178 "shall" rules (alias/label
519/// uniqueness, reference resolution, ...) are enforced separately by
520/// `relate-executor`'s graph-type validator (`validate_graph_type_body`),
521/// which only `CREATE GRAPH
522/// TYPE` invokes -- `ALTER CURRENT GRAPH TYPE` bodies legitimately reference
523/// element types declared by an *earlier* statement (e.g. `ADD`), which a
524/// single-body validation pass cannot see.
525#[derive(Debug, Clone, PartialEq, Default)]
526pub struct GraphTypeBody {
527 pub node_types: Vec<GraphTypeNodeTypeSpec>,
528 pub edge_types: Vec<GraphTypeEdgeTypeSpec>,
529 pub constraints: Vec<GraphTypeConstraintSpec>,
530 /// CIP-182 `<constraint drop specification>` = `CONSTRAINT <name>` (bare,
531 /// no `FOR ...`) -- only allowed in an `ALTER CURRENT GRAPH TYPE DROP {
532 /// ... }` body. The parser reads it in any body, and every other verb
533 /// rejects a non-empty list as a parse error
534 /// (`Parser::reject_bare_constraint_drops`), so this is always empty for
535 /// `CREATE GRAPH TYPE`/`SET`/`ADD`/`ALTER` bodies.
536 pub drop_constraint_names: Vec<SmallName>,
537}
538
539/// `'(' [alias] (':'|IS) <identifying label> ('=>'|IMPLIES) [(':'|IS)
540/// <implied label> ('&' <implied label>)*] ['{' <property types> '}'] ')'`
541/// (CIP-178 `<node type specification>`).
542#[derive(Debug, Clone, PartialEq)]
543pub struct GraphTypeNodeTypeSpec {
544 pub alias: Option<SmallName>,
545 pub identifying_label: SmallName,
546 pub implied_labels: Vec<SmallName>,
547 pub properties: Vec<GraphTypePropertyType>,
548}
549
550/// `<source endpoint> '-' '[' [alias] (':'|IS) <identifying label>
551/// ('=>'|IMPLIES) ['{' <property types> '}'] ']' '->' <destination
552/// endpoint>` (CIP-178 `<edge type specification>`).
553#[derive(Debug, Clone, PartialEq)]
554pub struct GraphTypeEdgeTypeSpec {
555 pub alias: Option<SmallName>,
556 pub identifying_label: SmallName,
557 pub properties: Vec<GraphTypePropertyType>,
558 pub source: GraphTypeElementRef,
559 pub target: GraphTypeElementRef,
560}
561
562/// One `<property type>`: a name, its declared value type, an optional
563/// `DEFAULT ON COMMIT <value expression>` (CIP-262), and an optional
564/// inline `IS [NODE|REL|RELATIONSHIP] (KEY|UNIQUE)` constraint (CIP-178
565/// Rules 10-12 rewrite these into standalone `GraphTypeConstraintSpec`s
566/// during registration).
567///
568/// The default value is parsed as a full expression here (grammar-only,
569/// like the rest of the body): the CIP-262 shape restriction -- a literal
570/// or an allowed type constructor, never `null` -- is enforced by the
571/// graph-type semantic layer, and the construct itself sits behind the
572/// ADR-0371 `graph-type-default-values` preview gate at statement
573/// admission (the trio's decision: ADR-0388). `None` is the no-default
574/// case.
575#[derive(Debug, Clone, PartialEq)]
576pub struct GraphTypePropertyType {
577 pub name: SmallName,
578 pub value_type: TypeExpr,
579 pub default_value: Option<Expr>,
580 pub inline_constraint: Option<GraphTypeInlineConstraint>,
581}
582
583/// An inline property-type constraint (`{prop :: TYPE IS [qualifier]
584/// KEY|UNIQUE}`). `qualifier` records which (if any) `NODE`/`REL`/
585/// `RELATIONSHIP` keyword was written, so the graph-type validator can
586/// enforce CIP-178 Rule 2 (a node type must not contain `REL`/
587/// `RELATIONSHIP`; an edge type must not contain `NODE`).
588#[derive(Debug, Clone, Copy, PartialEq, Eq)]
589pub struct GraphTypeInlineConstraint {
590 pub verb: GraphTypeInlineVerb,
591 pub qualifier: Option<GraphTypeEntityQualifier>,
592}
593
594#[derive(Debug, Clone, Copy, PartialEq, Eq)]
595pub enum GraphTypeInlineVerb {
596 Key,
597 Unique,
598}
599
600#[derive(Debug, Clone, Copy, PartialEq, Eq)]
601pub enum GraphTypeEntityQualifier {
602 Node,
603 Rel,
604}
605
606/// A `<node type reference>` / `<edge type reference>` (CIP-178): how a
607/// node/edge type spec's endpoint, or a constraint specification's `FOR`
608/// target, names the element type it applies to.
609#[derive(Debug, Clone, PartialEq)]
610pub enum GraphTypeElementRef {
611 /// `()` -- the any node/edge type.
612 Any,
613 /// `(alias)` / `()-[alias]->()` -- resolves to a previously declared
614 /// node/edge type alias (Rule 1.1.3: must already be declared).
615 AliasRef(SmallName),
616 /// `[alias] (':'|IS) <label> ['=>'|IMPLIES]` -- an in-situ reference.
617 /// `implies` (`=>`/`IMPLIES` present) requires `label` to name an
618 /// already-declared identifying label (Rule 1.2.3); without it, the
619 /// label need not be declared. `alias` is only legal in constraint
620 /// `FOR`-clause context (Rules 3/4 forbid it on an edge type's own
621 /// endpoint references).
622 InSitu {
623 alias: Option<SmallName>,
624 label: SmallName,
625 implies: bool,
626 },
627}
628
629/// `[CONSTRAINT [<name>]] FOR <node/edge type reference> REQUIRE
630/// <property name spec> <constraint verb> [OPTIONS <map>]` (CIP-178
631/// `<constraint specification>`) -- also the target of a node/edge type
632/// spec's trailing inline `REQUIRE ...` list and a property's own inline
633/// `IS KEY`/`IS UNIQUE` (both rewritten to this same shape at parse time,
634/// per Rules 10-12).
635#[derive(Debug, Clone, PartialEq)]
636pub struct GraphTypeConstraintSpec {
637 pub name: Option<SmallName>,
638 pub target: GraphTypeElementRef,
639 /// True when `target` is an edge type reference (`FOR ()-[...]->()`);
640 /// false for a node type reference (`FOR (...)`).
641 pub is_edge: bool,
642 pub properties: Vec<SmallName>,
643 pub kind: GraphTypeConstraintVerb,
644 /// The parsed `<value type>` for a `PropertyType`-kind constraint,
645 /// `None` for every other kind.
646 pub property_type: Option<TypeExpr>,
647 /// The `OPTIONS` tail: absent, a literal map, or a whole-map parameter
648 /// (CIP-116 CR[4]) resolved before the body is captured/persisted.
649 pub options: OptionsForm,
650}
651
652#[derive(Debug, Clone, PartialEq, Eq)]
653pub enum GraphTypeConstraintVerb {
654 Key,
655 Unique,
656 Exists,
657 PropertyType,
658}
659
660/// CIP-135 conditional clause: `WHEN <pred> THEN { <body> } [WHEN <pred>
661/// THEN { <body> }]* [ELSE { <body> }]`. Each branch's `body`/`else_body`
662/// is itself a `<single-query>` (own `Statement`, possibly carrying its own
663/// `.union` chain).
664#[derive(Debug, Clone, PartialEq)]
665pub struct ConditionalClause {
666 pub branches: Vec<WhenBranch>,
667 pub else_body: Option<Statement>,
668}
669
670/// One `WHEN <predicate> THEN <single-query>` branch of a `ConditionalClause`.
671#[derive(Debug, Clone, PartialEq)]
672pub struct WhenBranch {
673 pub predicate: Expr,
674 pub body: Statement,
675}
676
677/// MATCH clause.
678#[derive(Debug, Clone, PartialEq)]
679pub struct MatchClause {
680 pub optional: bool,
681 /// CIP-51/CIP-60 match mode: whether relationship uniqueness (the
682 /// default `DIFFERENT RELATIONSHIPS`) is enforced across the whole
683 /// comma-separated graph pattern, or relaxed (`REPEATABLE ELEMENTS`).
684 pub match_mode: MatchMode,
685 pub pattern: Vec<PatternPath>,
686 /// CIP-79 variables named by a `USING SCAN <var>:<Label>` hint.
687 /// Relate's planner is not cost-based, but a scan hint is not a
688 /// mere plan preference here: an indexed equality seek and a label
689 /// scan genuinely answer differently for a zoned-datetime DST overlap
690 /// (the index keys on instant plus zone, `=` on the wall clock), so
691 /// the hint must reach the executor — the one hint family that does;
692 /// `USING INDEX` stops at the front-end fulfillability check and
693 /// `USING JOIN ON` at the plan-time notification, per the two
694 /// fields below.
695 pub using_scan: Vec<ScanHint>,
696 /// CIP-79 `USING INDEX [SEEK] <var>:<Label>(<prop>[, …])` hints. The
697 /// planner is not cost-based so they steer nothing, but the front end
698 /// still validates that each hint is *fulfillable* — Neo4j rejects an
699 /// undefined hint variable and an unfulfillable hint at compile time
700 /// (SemanticErrorPart2 "An index hint … is rejected"), which needs the
701 /// hint preserved here.
702 pub using_index: Vec<IndexHint>,
703 /// CIP-79 `USING JOIN ON <var>[, <var>…]` hints. The planner is not
704 /// cost-based so a join hint steers nothing — every one is
705 /// unfulfillable, which the `01N30` plan-time notification reports
706 /// (ADR-0363); retaining the hint here is what lets the IR carry it
707 /// to that detector.
708 pub using_join: Vec<JoinHint>,
709 pub where_expr: Option<Expr>,
710 /// CIP-224 `<search clause>`: `SEARCH <binding var ref> IN (VECTOR
711 /// INDEX <index name> FOR <expr> LIMIT <expr>) [SCORE AS <var>]`, a
712 /// subclause of `<match statement>`. The grammar allows the `<graph
713 /// pattern where clause>` to appear either before or after the search
714 /// clause with no semantic difference (CIP-224 "Canonical syntax"), so
715 /// the parser folds both orderings into this same `where_expr` field --
716 /// the source order isn't tracked in the AST.
717 pub search: Option<SearchClause>,
718}
719
720/// One `USING SCAN <variable>:<Label>` hint. The label is retained at the
721/// same fidelity as [`IndexHint`]'s properties, so the hint family keeps
722/// one shape; the planner's scan fork keys on the variable.
723#[derive(Debug, Clone, PartialEq, Eq)]
724pub struct ScanHint {
725 pub variable: SmallName,
726 pub label: SmallName,
727}
728
729/// One `USING INDEX [SEEK] <variable>:<Label>(<property>[, …])` hint.
730#[derive(Debug, Clone, PartialEq, Eq)]
731pub struct IndexHint {
732 pub variable: SmallName,
733 pub label: SmallName,
734 pub properties: Vec<SmallName>,
735}
736
737impl IndexHint {
738 /// The hinted property list as one text — `name`, `name, surname` —
739 /// the one spelling both the front end's unfulfillable-hint error
740 /// (42N76) and the plan-time `01N31` description render.
741 pub fn properties_text(&self) -> String {
742 self.properties
743 .iter()
744 .map(|property| property.to_string())
745 .collect::<Vec<_>>()
746 .join(", ")
747 }
748}
749
750/// One `USING JOIN ON <variable>[, <variable>…]` hint: the join key
751/// identifiers, in written order.
752#[derive(Debug, Clone, PartialEq, Eq)]
753pub struct JoinHint {
754 pub variables: Vec<SmallName>,
755}
756
757/// CIP-224 `<search clause>`: the `SEARCH ... IN (<source specification
758/// clause>) [SCORE AS ...]` subclause of `MatchClause`.
759///
760/// `binding_var`/`score_var` (and each nested `index_name`) are plain
761/// identifiers (never a general expression, a parameter, or a property
762/// access -- Rules 1, 4, 5) rather than `Expr`, matching the grammar's own
763/// `<binding variable reference>` / `<index name specification>` /
764/// `<binding variable>` productions.
765#[derive(Debug, Clone, PartialEq)]
766pub struct SearchClause {
767 /// `<binding variable reference>`: must name a variable declared by the
768 /// same `<match statement>`'s own pattern (Rule 4).
769 pub binding_var: SmallName,
770 /// CIP-278 `<source specification clause>`: one index search, or a
771 /// `COMBINE` of two or more weighted sources fused with WRRF.
772 pub spec: SearchSpec,
773 /// `[SCORE AS <binding variable>]` -- `None` when the score column is
774 /// omitted (results are still ordered by descending score either way).
775 pub score_var: Option<SmallName>,
776}
777
778/// CIP-278 `<source specification clause>`:
779/// `<index specification clause> | <combined specification clause>`.
780#[derive(Debug, Clone, PartialEq)]
781pub enum SearchSpec {
782 Index(SearchIndexSpec),
783 Combine(SearchCombineSpec),
784}
785
786/// CIP-225 `<index specification clause>`: `{ VECTOR | FULLTEXT } INDEX
787/// <index name> <index for and control clause>`.
788#[derive(Debug, Clone, PartialEq)]
789pub struct SearchIndexSpec {
790 /// CIP-225: which index kind the specification names.
791 pub kind: SearchKind,
792 /// `<index name specification>`: the literal name of an existing index.
793 pub index_name: SmallName,
794 /// `<for clause>`'s `<value expression>` -- the search query.
795 pub for_expr: Expr,
796 /// CIP-225 `WITH ANALYZER <expr>` (fulltext only).
797 pub analyzer: Option<Expr>,
798 /// CIP-240 "Vector Search with Single-stage Filtering": the optional
799 /// inner `WHERE <search condition>` between `FOR <expr>` and `LIMIT
800 /// <expr>`. Its `<search condition>` must decompose into one or more
801 /// `<binding variable reference> <static property reference> <simple
802 /// comp op> <arithmetic value expression>` predicates joined by `AND`
803 /// (or a form rewritable into that, e.g. `NOT x.prop` or flipped
804 /// operands) -- enforced by `relate_front::search_filter`, not here;
805 /// the parser accepts any general `<expression>` here, exactly like
806 /// `MatchClause.where_expr`.
807 pub inner_where: Option<Expr>,
808 /// CIP-225 `<offset clause>` (`SKIP`/`OFFSET`).
809 pub offset_expr: Option<Expr>,
810 /// `<limit clause>`'s `<value expression>` (mandatory for an index
811 /// source, in and out of a COMBINE).
812 pub limit_expr: Expr,
813}
814
815/// CIP-225 `<index specification clause>`: `{ VECTOR | FULLTEXT } INDEX`.
816#[derive(Debug, Clone, Copy, PartialEq, Eq)]
817pub enum SearchKind {
818 Vector,
819 Fulltext,
820}
821
822/// CIP-278 `<combined specification clause>`: `COMBINE ( <weighted source
823/// clause>, ... ) USING WRRF [ WITH CONSTANT <expr> ] [ LIMIT <expr> ]`.
824///
825/// Rule 5: `sources` holds two or more weighted source clauses (fewer is a
826/// parse error, raised where the list is parsed). A source may itself be a
827/// nested `<combined specification clause>` (Example P3).
828#[derive(Debug, Clone, PartialEq)]
829pub struct SearchCombineSpec {
830 pub sources: Vec<SearchWeightedSource>,
831 /// `<constant specification clause>`'s `<value expression>` -- the WRRF
832 /// dampening constant; `None` means the default 60 (Rule 4).
833 pub constant_expr: Option<Expr>,
834 /// The optional `<limit clause>` of the combined specification -- the n
835 /// highest-scoring results kept; `None` keeps all (Rule 7).
836 pub limit_expr: Option<Expr>,
837}
838
839/// CIP-278 `<weighted source clause>`:
840/// `<source specification clause> [ WEIGHT <value expression> ]`.
841#[derive(Debug, Clone, PartialEq)]
842pub struct SearchWeightedSource {
843 pub spec: SearchSpec,
844 /// Rule 2: `None` means the default weight 1.
845 pub weight_expr: Option<Expr>,
846}
847
848/// CIP-51/CIP-60 match mode: governs the default relationship-uniqueness
849/// pool that spans one MATCH clause's entire comma-separated graph pattern.
850#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
851pub enum MatchMode {
852 /// `MATCH DIFFERENT RELATIONSHIPS ...` (also the implicit default): no
853 /// two relationship slots anywhere in the graph pattern may bind to the
854 /// same physical relationship.
855 #[default]
856 DifferentRelationships,
857 /// `MATCH REPEATABLE ELEMENTS ...`: relaxes the relationship-uniqueness
858 /// pool entirely -- nodes and relationships may repeat freely, subject
859 /// only to each path's own path mode (which must resolve to `WALK`
860 /// under this match mode, CIP-51 Section 3.1.3 rule 4).
861 RepeatableElements,
862}
863
864/// CIP-51 path mode: an explicit restrictor on one path pattern's candidate
865/// bindings. `PatternPath::mode` is `None` when no explicit keyword was
866/// written -- Rule 1: the resolved default is `Walk`.
867#[derive(Debug, Clone, Copy, PartialEq, Eq)]
868pub enum PathMode {
869 /// Nodes and relationships may repeat freely (subject to the enclosing
870 /// match mode's own relationship-uniqueness pool, which under the
871 /// default `DIFFERENT RELATIONSHIPS` match mode still applies).
872 Walk,
873 /// No two relationship bindings in this one path may bind the same
874 /// relationship (already the effective default under `DIFFERENT
875 /// RELATIONSHIPS`, since that pool subsumes a single path's own).
876 Trail,
877 /// No two node bindings in this one path may bind the same node, except
878 /// where two connectors are juxtaposed at a shared boundary node.
879 Acyclic,
880 /// Like `Acyclic`, but the very first and very last node of the path may
881 /// coincide (an equijoin on the endpoints).
882 Simple,
883}
884
885/// The `<number of paths>`/`<number of groups>` non-terminal (CIP-73 Rule 0,
886/// extended by CIP-191 to accept a `$parameter`). A literal is validated
887/// (`> 0`) at parse time; a parameter is validated at runtime once its value
888/// is known (CIP-191 "Non-negative integer" rule).
889#[derive(Debug, Clone, PartialEq)]
890pub enum PathCount {
891 Literal(u32),
892 Parameter(String),
893}
894
895/// CIP-73 path selector prefix (`<path search prefix>`). `PatternPath` has
896/// no selector when this is `None` -- Rule 3: the path pattern is then
897/// non-selective, equivalent to an implicit `ALL`.
898#[derive(Debug, Clone, PartialEq)]
899pub enum PathSelector {
900 /// `ALL [path mode] [PATH|PATHS]` -- also the implicit default.
901 All,
902 /// `ANY [<number of paths>] [path mode] [PATH|PATHS]`; `None` count
903 /// defaults to 1 (Rule 0).
904 Any(Option<PathCount>),
905 /// `ANY SHORTEST [path mode] [PATH|PATHS]` -- normalizes to `SHORTEST 1
906 /// [path mode] PATH` (Rule 2).
907 AnyShortest,
908 /// `ALL SHORTEST [path mode] [PATH|PATHS]` -- normalizes to `SHORTEST 1
909 /// [path mode] GROUP` (Rule 2).
910 AllShortest,
911 /// `SHORTEST <number of paths> [path mode] [PATH|PATHS]` (`group` false)
912 /// or `SHORTEST [<number of groups>] [path mode] [PATH|PATHS]
913 /// (GROUP|GROUPS)` (`group` true); `count` is `None` only in the GROUP
914 /// form (defaults to 1, Rule 0).
915 Shortest {
916 count: Option<PathCount>,
917 group: bool,
918 },
919}
920
921/// CREATE clause.
922#[derive(Debug, Clone, PartialEq)]
923pub struct CreateClause {
924 pub pattern: Vec<PatternPath>,
925 /// True when this clause was written as `INSERT` (CIP-114) rather than
926 /// `CREATE` -- executed identically in every other respect, but the
927 /// `+labels` side-effect stat is *not* subject to CREATE's row-scoped
928 /// same-label-name dedup (empirically, INSERT counts every label
929 /// application on every node it creates, unlike CREATE/MERGE).
930 pub is_insert: bool,
931}
932
933/// MERGE clause.
934#[derive(Debug, Clone, PartialEq)]
935pub struct MergeClause {
936 pub pattern: PatternPath,
937 pub on_create: Vec<SetItem>,
938 pub on_match: Vec<SetItem>,
939}
940
941/// DELETE clause.
942#[derive(Debug, Clone, PartialEq)]
943pub struct DeleteClause {
944 pub detach: bool,
945 pub expressions: Vec<Expr>,
946}
947
948/// SET clause.
949#[derive(Debug, Clone, PartialEq)]
950pub struct SetClause {
951 pub items: Vec<SetItem>,
952}
953
954/// A single item in a SET clause.
955#[derive(Debug, Clone, PartialEq)]
956pub struct SetItem {
957 pub property: Option<PropertyAccess>,
958 pub variable: Option<SmallName>,
959 /// Each element is a `LabelExpr::Label` (static, `SET n:A`) or
960 /// `LabelExpr::Dynamic` (CIP-162, `SET n:$(<expr>)`/`SET n IS $(<expr>)`)
961 /// atom -- the parser never produces any other `LabelExpr` variant here
962 /// (no `&`/`|`/`!`/`%`/grouping). See `RemoveItem::labels`.
963 pub labels: Vec<LabelExpr>,
964 pub value: Option<Expr>,
965 pub merge: bool,
966 /// True if this label item used the CIP-126 `IS` keyword (`SET n IS A`)
967 /// rather than `:` (`SET n:A`). Only meaningful when `labels` is
968 /// non-empty. Used for the CIP-40/CIP-126 statement-level rule that
969 /// forbids mixing `IS` with a colon-conjunction (`:A:B`) anywhere in the
970 /// same statement.
971 pub is_keyword: bool,
972 /// CIP-162 "Alternatives" section: `SET labels(<expr>) = / += / -=
973 /// <expr>`. Per the CIP's own text this was never shipped in Neo4j
974 /// ("we have decided to implement the rest first, and leave this as a
975 /// potential future extension") -- Relate implements it anyway as
976 /// the CIP's stated target semantics. `Some((target_expr, op))` when
977 /// this item is that form, with `target_expr` the node expression
978 /// inside `labels(...)` and `value` (above) holding the RHS list
979 /// expression.
980 pub labels_function: Option<(Expr, LabelsFunctionOp)>,
981}
982
983/// The operator of a CIP-162 `SET labels(<expr>) <op> <expr>` item.
984#[derive(Debug, Clone, Copy, PartialEq, Eq)]
985pub enum LabelsFunctionOp {
986 /// `=` -- replace the full label set.
987 Overwrite,
988 /// `+=` -- add every listed label, keep existing ones.
989 Extend,
990 /// `-=` -- remove every listed label that is present.
991 Remove,
992}
993
994/// REMOVE clause.
995#[derive(Debug, Clone, PartialEq)]
996pub struct RemoveClause {
997 pub items: Vec<RemoveItem>,
998}
999
1000/// A single item in a REMOVE clause.
1001#[derive(Debug, Clone, PartialEq)]
1002pub struct RemoveItem {
1003 pub property: Option<PropertyAccess>,
1004 pub variable: Option<SmallName>,
1005 /// See `SetItem::labels` (CIP-162 dynamic-label atoms allowed here too).
1006 pub labels: Vec<LabelExpr>,
1007 /// See `SetItem::is_keyword`.
1008 pub is_keyword: bool,
1009}
1010
1011/// RETURN clause.
1012#[derive(Debug, Clone, PartialEq)]
1013pub struct ReturnClause {
1014 pub group_by: Option<GroupBySpec>,
1015 pub distinct: bool,
1016 pub items: Vec<ReturnItem>,
1017 pub order_by: Vec<OrderByItem>,
1018 pub skip: Option<Expr>,
1019 pub limit: Option<Expr>,
1020}
1021
1022/// A single item in a RETURN clause.
1023#[derive(Debug, Clone, PartialEq)]
1024pub struct ReturnItem {
1025 pub expr: Expr,
1026 pub alias: Option<SmallName>,
1027 pub all: bool,
1028 pub source_text: Option<String>,
1029}
1030
1031/// An item in ORDER BY.
1032#[derive(Debug, Clone, PartialEq)]
1033pub struct OrderByItem {
1034 pub expr: Expr,
1035 pub descending: bool,
1036}
1037
1038/// Which surface syntax produced a `WithClause`. Plain `WITH`, CIP-206's
1039/// `LET`, and CIP-203's `FILTER` all desugar into the same `WithClause` so
1040/// they share WITH's projection/aggregation/ORDER BY/SKIP/LIMIT/WHERE
1041/// execution machinery and its generic variable-scope tracking -- but LET
1042/// and FILTER each carry restrictions ordinary WITH does not (LET: no
1043/// shadowing of an in-scope variable, no sibling/forward/self reference
1044/// within one LET's item list, no aggregation function in a value
1045/// expression; FILTER: its search condition's declared type must be
1046/// Boolean). The origin is recorded so the validation passes enforcing
1047/// those extra rules only fire for the syntax that actually carries them.
1048#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1049pub enum WithOrigin {
1050 #[default]
1051 Explicit,
1052 Let,
1053 Filter,
1054}
1055
1056/// CIP-236 `<group by clause>` on RETURN/WITH.
1057#[derive(Debug, Clone, PartialEq)]
1058pub enum GroupBySpec {
1059 /// `GROUP BY <expr> [, <expr>...]`
1060 Keys(Vec<Expr>),
1061 /// `GROUP BY ()` -- the empty grouping set: one global group.
1062 Empty,
1063 /// `GROUP BY ALL` -- every non-aggregating return item is a key.
1064 All,
1065}
1066
1067/// WITH clause.
1068#[derive(Debug, Clone, PartialEq)]
1069pub struct WithClause {
1070 pub group_by: Option<GroupBySpec>,
1071 pub distinct: bool,
1072 pub items: Vec<ReturnItem>,
1073 pub order_by: Vec<OrderByItem>,
1074 pub skip: Option<Expr>,
1075 pub limit: Option<Expr>,
1076 pub where_expr: Option<Expr>,
1077 pub origin: WithOrigin,
1078}
1079
1080/// One stage of a CIP-168 standalone `<order by and page statement>`.
1081/// Neo4j 2026.05 accepts `ORDER BY`/`OFFSET`/`SKIP`/`LIMIT` in any order
1082/// at the start of the clause and applies them sequentially in the order
1083/// written -- not the fixed ORDER-BY-then-OFFSET-then-LIMIT semantic
1084/// order the CIP text describes (see CIP-168 NOTES.md "Deviations" #1,
1085/// e.g. `LIMIT 3 OFFSET 1` keeps 3 rows then drops the first 1 of those,
1086/// rather than offsetting first). A `Vec<PageStage>` records exactly the
1087/// written sequence so execution can replay it faithfully.
1088#[derive(Debug, Clone, PartialEq)]
1089pub enum PageStage {
1090 OrderBy(Vec<OrderByItem>),
1091 Skip(Expr),
1092 Limit(Expr),
1093}
1094
1095/// CIP-168: a standalone `<order by and page statement>`. See
1096/// `Clause::StandaloneOrderBy`.
1097#[derive(Debug, Clone, PartialEq)]
1098pub struct StandaloneOrderByClause {
1099 pub stages: Vec<PageStage>,
1100}
1101
1102/// UNWIND clause. CIP-250 (GQ10): a `FOR <variable> IN <expression>`
1103/// clause normalizes here at parse time -- the same expr/alias pair with
1104/// [`UnwindClause::for_syntax`] recording the source spelling -- so every
1105/// downstream consumer (validation, lowering, planning, execution) treats
1106/// the two spellings identically, exactly as the CIP requires (no new
1107/// operators). The flag is the parse-spelling record the FOREACH-body
1108/// renderer reads (`FOR`, not `UNWIND`, in the 42I01 text) — the one
1109/// consumer that must distinguish the spellings.
1110#[derive(Debug, Clone, PartialEq)]
1111pub struct UnwindClause {
1112 pub expr: Expr,
1113 pub alias: SmallName,
1114 /// True when the clause was written `FOR <variable> IN <expression>`
1115 /// (CIP-250) rather than `UNWIND <expression> AS <variable>`.
1116 pub for_syntax: bool,
1117}
1118
1119/// The DDL index kind (CIP-11 RANGE/POINT/TEXT, CIP-38 FULLTEXT, the
1120/// pre-existing VECTOR, and the label/type-token LOOKUP index).
1121#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1122pub enum IndexKind {
1123 Range,
1124 Point,
1125 Text,
1126 Fulltext,
1127 Lookup,
1128 Vector,
1129}
1130
1131impl IndexKind {
1132 /// The canonical lowercase tag persisted in
1133 /// `relate_storage::Index::index_type` -- also the tag the engine
1134 /// switches on to decide which (if any) in-memory acceleration
1135 /// structure to build for a given index (`Engine::rebuild_indexes`).
1136 /// Unchanged for `Point`/`Vector` from before CIP-11 so existing
1137 /// vector/point index acceleration keeps working untouched; `Range`
1138 /// replaces the old ad hoc `"secondary"` tag (still accepted as a
1139 /// legacy alias when reading it back).
1140 pub fn storage_tag(&self) -> &'static str {
1141 match self {
1142 IndexKind::Range => "range",
1143 IndexKind::Point => "point",
1144 IndexKind::Text => "text",
1145 IndexKind::Fulltext => "fulltext",
1146 IndexKind::Lookup => "lookup",
1147 IndexKind::Vector => "vector",
1148 }
1149 }
1150
1151 /// The upper-case display name Neo4j's `SHOW INDEXES` `type` column
1152 /// uses.
1153 pub fn display_name(&self) -> &'static str {
1154 match self {
1155 IndexKind::Range => "RANGE",
1156 IndexKind::Point => "POINT",
1157 IndexKind::Text => "TEXT",
1158 IndexKind::Fulltext => "FULLTEXT",
1159 IndexKind::Lookup => "LOOKUP",
1160 IndexKind::Vector => "VECTOR",
1161 }
1162 }
1163}
1164
1165/// Which kind of graph element a CREATE INDEX / CREATE CONSTRAINT `FOR`
1166/// pattern targets (CIP-11's relationship-pattern generalization: `FOR
1167/// (n:Label)` vs. `FOR ()-[r:TYPE]-()` in all four direction spellings).
1168#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1169pub enum SchemaEntityType {
1170 Node,
1171 Relationship,
1172}
1173
1174impl SchemaEntityType {
1175 /// The upper-case display value Neo4j's `SHOW INDEXES`/`SHOW
1176 /// CONSTRAINTS` `entityType` column uses.
1177 pub fn as_str(&self) -> &'static str {
1178 match self {
1179 SchemaEntityType::Node => "NODE",
1180 SchemaEntityType::Relationship => "RELATIONSHIP",
1181 }
1182 }
1183}
1184
1185/// The name of an index or constraint in CREATE INDEX / CREATE CONSTRAINT /
1186/// DROP INDEX / DROP CONSTRAINT: either a literal identifier or a `$param`
1187/// reference resolved against the query's parameter map at execution time
1188/// (CIP-134).
1189#[derive(Debug, Clone, PartialEq)]
1190pub enum SchemaName {
1191 Literal(String),
1192 Parameter(String),
1193}
1194
1195/// The optional `OPTIONS` tail of a schema DDL command (CIP-116 CR[4],
1196/// ADR-0489): the three states the old `options` + `options_param` pair
1197/// encoded in a comment only.
1198#[derive(Debug, Clone, PartialEq)]
1199pub enum OptionsForm {
1200 /// No `OPTIONS` clause at all.
1201 Absent,
1202 /// `OPTIONS { key: <value expression>, ... }`: lowered and evaluated at
1203 /// execution time.
1204 Literal(Vec<(String, Expr)>),
1205 /// `OPTIONS $param`: the parameter must evaluate to a MAP at execution
1206 /// time, whose entries become the command's literal options.
1207 Parameter(String),
1208}
1209
1210impl OptionsForm {
1211 /// The literal map's entries — `None` for the two forms that carry no
1212 /// literal map, so no caller can mistake an absent clause or an
1213 /// unresolved `$param` for an empty map.
1214 pub fn literal(&self) -> Option<&[(String, Expr)]> {
1215 match self {
1216 Self::Literal(entries) => Some(entries),
1217 Self::Absent | Self::Parameter(_) => None,
1218 }
1219 }
1220
1221 /// The unresolved parameter's name, if this is that form.
1222 pub fn parameter(&self) -> Option<&str> {
1223 match self {
1224 Self::Parameter(name) => Some(name),
1225 Self::Absent | Self::Literal(_) => None,
1226 }
1227 }
1228
1229 /// The literal map's entries for in-place rewriting — `None` for the two
1230 /// forms that carry no literal map, the mutable twin of [`Self::literal`].
1231 pub fn literal_mut(&mut self) -> Option<&mut [(String, Expr)]> {
1232 match self {
1233 Self::Literal(entries) => Some(entries),
1234 Self::Absent | Self::Parameter(_) => None,
1235 }
1236 }
1237}
1238
1239/// CREATE INDEX clause.
1240#[derive(Debug, Clone, PartialEq)]
1241pub struct CreateIndexClause {
1242 pub name: Option<SchemaName>,
1243 pub entity_type: SchemaEntityType,
1244 /// Node labels, or (for a relationship index) relationship types, the
1245 /// index applies to. More than one entry only for the `A|B` disjunctive
1246 /// form (CIP-38/CIP-235); empty for a label-less/type-less LOOKUP index
1247 /// (`FOR (n)` / `FOR ()-[r]-()`).
1248 pub labels: Vec<SmallName>,
1249 pub properties: Vec<SmallName>,
1250 pub if_not_exists: bool,
1251 pub kind: IndexKind,
1252 /// True when the property list was written as `ON EACH [...]` (CIP-38
1253 /// FULLTEXT) rather than a plain `ON (...)` / paren-less `ON ...` list.
1254 pub on_each: bool,
1255 /// `WITH [var.prop1, var.prop2, ...]` (CIP-235): additional properties
1256 /// available for single-stage filtering on a VECTOR index, following
1257 /// the `ON` vector property. Always empty for every other index kind
1258 /// and for a vector index that doesn't use the clause.
1259 pub with_properties: Vec<SmallName>,
1260 /// The `OPTIONS` tail: absent, a literal map, or a whole-map parameter
1261 /// (CIP-116 CR[4]) resolved at execution time.
1262 pub options: OptionsForm,
1263}
1264
1265/// DROP INDEX clause.
1266#[derive(Debug, Clone, PartialEq)]
1267pub struct DropIndexClause {
1268 pub name: SchemaName,
1269 pub if_exists: bool,
1270 /// Legacy `DROP INDEX ON :Label(property)` target.
1271 pub legacy_target: Option<(SmallName, SmallName)>,
1272}
1273
1274/// `SHOW [ALL|RANGE|POINT|TEXT|FULLTEXT|VECTOR|LOOKUP] INDEXES [YIELD ...]
1275/// [WHERE ...]` (CIP-11). Mirrors `ShowConstraintsClause`; `kind_filter`
1276/// is `None` for bare `SHOW INDEXES`/`SHOW ALL INDEXES` (every index kind).
1277#[derive(Debug, Clone, PartialEq)]
1278pub struct ShowIndexesClause {
1279 pub kind_filter: Option<IndexKind>,
1280 pub yields: YieldList,
1281 pub where_expr: Option<Expr>,
1282 /// `ORDER BY`/`SKIP`/`LIMIT` written directly on the `YIELD` (before
1283 /// any trailing `WHERE`), same paging sub-grammar and rationale as
1284 /// `ShowConstraintsClause::stages`.
1285 pub stages: Vec<PageStage>,
1286}
1287
1288/// CREATE CONSTRAINT clause.
1289#[derive(Debug, Clone, PartialEq)]
1290pub struct CreateConstraintClause {
1291 pub name: Option<SchemaName>,
1292 pub entity_type: SchemaEntityType,
1293 pub label: SmallName,
1294 pub variable: SmallName,
1295 pub properties: Vec<SmallName>,
1296 pub constraint_type: String, // "unique", "exists", "key", "propertyType"
1297 pub if_not_exists: bool,
1298 /// The parsed `<value type>` for a `REQUIRE (n.prop) IS :: <type>` /
1299 /// `IS TYPED <type>` property type constraint (CIP-85), `None` for
1300 /// every other `constraint_type`.
1301 pub property_type: Option<TypeExpr>,
1302 /// The `OPTIONS` tail: absent, a literal map, or a whole-map parameter
1303 /// (CIP-116 CR[4]) resolved at execution time.
1304 pub options: OptionsForm,
1305 /// The target label for a CIP-177 `REQUIRE <alias>:<Label>` label
1306 /// existence constraint (`constraint_type` one of `"labelExistence"`/
1307 /// `"sourceLabelExistence"`/`"targetLabelExistence"`), `None` for
1308 /// every other `constraint_type`.
1309 pub enforced_label: Option<SmallName>,
1310}
1311
1312/// DROP CONSTRAINT clause.
1313#[derive(Debug, Clone, PartialEq)]
1314pub struct DropConstraintClause {
1315 pub name: SchemaName,
1316 pub if_exists: bool,
1317}
1318
1319/// FOREACH clause.
1320#[derive(Debug, Clone, PartialEq)]
1321pub struct ForeachClause {
1322 pub variable: SmallName,
1323 pub list_expr: Expr,
1324 pub clauses: Vec<Clause>,
1325}
1326
1327/// LOAD CSV clause.
1328#[derive(Debug, Clone, PartialEq)]
1329pub struct LoadCSVClause {
1330 pub with_headers: bool,
1331 pub source: Expr,
1332 pub alias: SmallName,
1333 pub field_terminator: Option<String>,
1334}
1335
1336/// CALL { ... } subquery clause.
1337#[derive(Debug, Clone, PartialEq)]
1338pub struct CallSubqueryClause {
1339 pub statement: Statement,
1340 /// CIP-141 variable scope clause: `None` for a naked `CALL { ... }`
1341 /// (the deprecated legacy form, where an `IMPORTING WITH` as the
1342 /// subquery's own first clause is the only way to correlate outer
1343 /// variables in); `Some(CallScope::...)` for `CALL (...) { ... }`.
1344 pub scope: CallScope,
1345 /// CIP-159: `OPTIONAL CALL { ... }` -- when the inline subquery yields
1346 /// zero rows for a given outer row, that outer row is null-padded
1347 /// (every column the subquery would export set to `NULL`) instead of
1348 /// being dropped.
1349 pub optional: bool,
1350 /// CIP-32/CIP-34/CIP-198/CIP-30 trailing `IN [<concExpr>] CONCURRENT?
1351 /// TRANSACTIONS [OF <n> ROW(S)] [ON ERROR ...] [REPORT STATUS AS
1352 /// <var>]` production. `None` for a plain `CALL { ... }` subquery.
1353 pub in_transactions: Option<InTransactionsClause>,
1354}
1355
1356/// The full `IN [<concExpr>] CONCURRENT? TRANSACTIONS [OF <n> ROW|ROWS] [ON
1357/// ERROR ...] [REPORT STATUS AS <var>]` production trailing a CALL
1358/// subquery. Parsed in its entirety (CIP-32 base batching, CIP-34
1359/// concurrency, CIP-198 retry, CIP-30 status/error) so later CIPs only need
1360/// to add validation/execution on top of this AST -- CIP-32 itself only
1361/// implements sequential batching plus the nesting/preceding-write
1362/// restrictions; concurrency and retry are parsed but currently execute as
1363/// plain sequential batching (see `Engine`'s `Clause::CallSubquery` arm).
1364#[derive(Debug, Clone, PartialEq)]
1365pub struct InTransactionsClause {
1366 /// `IN TRANSACTIONS` (no `CONCURRENT`) vs `IN [<expr>] CONCURRENT
1367 /// TRANSACTIONS` (CIP-34).
1368 pub concurrency: Concurrency,
1369 /// `OF <n> ROW|ROWS`. `None` means the batch size is
1370 /// implementation-chosen (batching[6]).
1371 pub batch_size: Option<Expr>,
1372 /// `ON ERROR CONTINUE|BREAK|FAIL|RETRY ...`. Defaults to `Fail` when
1373 /// `ON ERROR` is omitted.
1374 pub on_error: OnErrorMode,
1375 /// `REPORT STATUS AS <var>` (CIP-30).
1376 pub report_status: Option<SmallName>,
1377 /// CIP-260 `DISJOINT BY <exprs> | AUTO | NONE`. A concurrency hint that
1378 /// partitions the input rows by the listed key expressions (or lets the
1379 /// implementation choose / disables disjointness); it never changes the
1380 /// statement's result. Only legal on the `CONCURRENT` form.
1381 pub disjoint: Option<DisjointBy>,
1382}
1383
1384/// CIP-260 `DISJOINT BY` operand.
1385#[derive(Debug, Clone, PartialEq)]
1386pub enum DisjointBy {
1387 /// `DISJOINT BY (<expr>, ...)`: partition rows by these deterministic
1388 /// key expressions.
1389 Expressions(Vec<Expr>),
1390 /// `DISJOINT BY AUTO`: the implementation picks the partitioning.
1391 Auto,
1392 /// `DISJOINT BY NONE`: no disjointness requirement.
1393 None,
1394}
1395
1396impl InTransactionsClause {
1397 /// Every value expression of the `IN TRANSACTIONS` tail, in visit
1398 /// order: the CIP-34 concurrency value, the CIP-32 batch size, the
1399 /// CIP-198 retry duration and the CIP-260 `DISJOINT BY` key
1400 /// expressions. The exhaustive matches on the three operand enums are
1401 /// the slot list: a new operand variant is a compile error here until
1402 /// its expression is enumerated, so a consumer cannot drift from the
1403 /// parser shape.
1404 pub fn exprs(&self) -> Vec<&Expr> {
1405 let mut out = Vec::new();
1406 match &self.concurrency {
1407 Concurrency::Value(expr) => out.push(expr),
1408 Concurrency::Sequential | Concurrency::DefaultUnspecified => {}
1409 }
1410 out.extend(self.batch_size.as_ref());
1411 match &self.on_error {
1412 OnErrorMode::Retry { duration, .. } => out.extend(duration.as_ref()),
1413 OnErrorMode::Fail | OnErrorMode::Continue | OnErrorMode::Break => {}
1414 }
1415 match &self.disjoint {
1416 Some(DisjointBy::Expressions(keys)) => out.extend(keys),
1417 Some(DisjointBy::Auto | DisjointBy::None) | None => {}
1418 }
1419 out
1420 }
1421}
1422
1423/// CIP-34 `IN [<concExpr>] CONCURRENT? TRANSACTIONS` concurrency modifier.
1424#[derive(Debug, Clone, PartialEq)]
1425pub enum Concurrency {
1426 /// No `CONCURRENT` keyword -- sequential (base CIP-32 form).
1427 Sequential,
1428 /// `CONCURRENT` with no explicit value -- implementation-chosen
1429 /// concurrency.
1430 DefaultUnspecified,
1431 /// `<expr> CONCURRENT` -- an explicit concurrency value.
1432 Value(Expr),
1433}
1434
1435/// CIP-30/CIP-198 `ON ERROR ...` mode.
1436#[derive(Debug, Clone, PartialEq)]
1437pub enum OnErrorMode {
1438 /// The default when `ON ERROR` is omitted entirely.
1439 Fail,
1440 Continue,
1441 Break,
1442 /// CIP-198 `RETRY [FOR]? [<dur> SEC|SECOND|SECONDS]? [THEN
1443 /// CONTINUE|BREAK|FAIL]?`.
1444 Retry {
1445 /// `FOR <dur> SEC[OND[S]]`; `None` means the retry duration is
1446 /// implementation-chosen.
1447 duration: Option<Expr>,
1448 /// The mode to fall back to once retries are exhausted. Defaults to
1449 /// `Fail` when no `THEN` clause is given (CIP-198's documented
1450 /// deviation from a naive "defaults to CONTINUE" reading).
1451 fallback: RetryFallback,
1452 },
1453}
1454
1455/// The `THEN CONTINUE|BREAK|FAIL` fallback mode of `ON ERROR RETRY`.
1456#[derive(Debug, Clone, PartialEq)]
1457pub enum RetryFallback {
1458 Fail,
1459 Continue,
1460 Break,
1461}
1462
1463/// The `(...)` variable scope clause on a `CALL` subquery (CIP-141).
1464#[derive(Debug, Clone, PartialEq)]
1465pub enum CallScope {
1466 /// Naked `CALL { ... }` -- no scope clause at all.
1467 None,
1468 /// `CALL (*) { ... }` -- import every variable currently in scope.
1469 Wildcard,
1470 /// `CALL (a, b) { ... }` / `CALL () { ... }` -- import exactly these
1471 /// variables (the list may be empty).
1472 Vars(Vec<SmallName>),
1473}
1474
1475/// `USE <graph-expr>` clause.
1476#[derive(Debug, Clone, PartialEq)]
1477pub struct UseClause {
1478 pub graph_expr: Expr,
1479}
1480
1481/// `SHOW FUNCTIONS [YIELD ...] [WHERE ...]` — the built-in function catalog
1482/// (CIP-245/CIP-247/CIP-263 discoverability scenarios). A minimal, dedicated
1483/// clause rather than a generic SHOW-command framework: only the function
1484/// catalog is modeled, not indexes/constraints/databases (out of this
1485/// batch's scope). `where_expr` is embedded here (rather than requiring a
1486/// standalone `WHERE` clause, which this AST has no variant for — WHERE is
1487/// always embedded in the clause that produces its rows, matching
1488/// `MatchClause`) so `SHOW FUNCTIONS YIELD name WHERE name = 'x' RETURN
1489/// name` parses as a single clause producing already-filtered rows.
1490#[derive(Debug, Clone, PartialEq)]
1491pub struct ShowFunctionsClause {
1492 pub yields: YieldList,
1493 pub where_expr: Option<Expr>,
1494 /// The YIELD's own paging sub-grammar, written between the YIELD list
1495 /// and the trailing `WHERE` (CIP-74 filtering[8]/[9]; live Neo4j
1496 /// accepts that order for every SHOW command).
1497 pub stages: Vec<PageStage>,
1498 /// `[ALL | BUILT IN | USER DEFINED]` scope filter (CIP-84/CIP-157
1499 /// `SHOW BUILT IN FUNCTIONS` / `SHOW USER DEFINED FUNCTIONS`
1500 /// scenarios). `All` (the default) and `BuiltIn` are equivalent for
1501 /// Relate, which ships only built-in functions; `UserDefined`
1502 /// always yields an empty catalog (no way to register a UDF).
1503 pub scope: FunctionScope,
1504 /// `EXECUTABLE [BY <user>]`, when written.
1505 pub executable: Option<ExecutableBy>,
1506}
1507
1508/// The `EXECUTABLE BY <user>` selector of `SHOW FUNCTIONS`/`SHOW
1509/// PROCEDURES`: the commands a user may execute. The bare `EXECUTABLE` form
1510/// applies no privilege filter, so it is the same state as writing no
1511/// selector at all (`None` on the clause) and has no variant of its own.
1512#[derive(Debug, Clone, PartialEq)]
1513pub enum ExecutableBy {
1514 /// `EXECUTABLE BY <user>` -- the named user.
1515 User(String),
1516 /// `EXECUTABLE BY CURRENT USER` -- the session's own user.
1517 Current,
1518}
1519
1520/// Scope filter for `SHOW [ALL | BUILT IN | USER DEFINED] FUNCTIONS`
1521/// (CIP-84/CIP-157). See `ShowFunctionsClause::scope`.
1522#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1523pub enum FunctionScope {
1524 #[default]
1525 All,
1526 BuiltIn,
1527 UserDefined,
1528}
1529
1530/// `SHOW [<type filter>] CONSTRAINTS [YIELD ...] [WHERE ...]` (CIP-85's
1531/// observation surface, needed by CIP-100 to expose a property type
1532/// constraint's normalized `propertyType`; the `<type filter>` grammar is
1533/// CIP-62/CIP-64/CIP-74's `[ALL] [NODE|REL[ATIONSHIP]] [PROPERTY]?
1534/// (UNIQUE[NESS]|KEY|EXIST[ENCE]|TYPE)` surface). Mirrors
1535/// `ShowFunctionsClause` otherwise.
1536#[derive(Debug, Clone, PartialEq)]
1537pub struct ShowConstraintsClause {
1538 pub yields: YieldList,
1539 pub where_expr: Option<Expr>,
1540 pub type_filter: ConstraintTypeFilter,
1541 /// `ORDER BY`/`SKIP`/`LIMIT` written directly on the `YIELD` (before
1542 /// any trailing `WHERE`) as part of the `YIELD`'s own paging
1543 /// sub-grammar (CIP-74 filtering[8]/[9]), e.g. `YIELD name ORDER BY
1544 /// name WHERE ... RETURN ...` -- distinct from a `SHOW ... YIELD ...`
1545 /// followed by a separate top-level `ORDER BY`/`RETURN ... ORDER BY`
1546 /// clause, which parses as its own `StandaloneOrderBy`/`Return` clause
1547 /// instead and never populates this field.
1548 pub stages: Vec<PageStage>,
1549}
1550
1551/// The entity half of a `SHOW <type filter> CONSTRAINTS` filter -- `Any`
1552/// for bare `SHOW CONSTRAINTS`/`SHOW ALL CONSTRAINTS` or a kind-only
1553/// filter with no `NODE`/`REL[ATIONSHIP]` prefix.
1554#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1555pub enum ConstraintEntityFilter {
1556 Any,
1557 Node,
1558 Relationship,
1559}
1560
1561/// The constraint-kind half of a `SHOW <type filter> CONSTRAINTS` filter.
1562/// `None` (on `ConstraintTypeFilter::kind`) means every kind (bare `SHOW
1563/// CONSTRAINTS`/`SHOW ALL CONSTRAINTS`/`SHOW NODE CONSTRAINTS`).
1564#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1565pub enum ConstraintKindFilter {
1566 /// `UNIQUE`/`UNIQUENESS`, optionally `PROPERTY`-prefixed (CIP-74) --
1567 /// matches `constraint_type == "unique"`.
1568 Unique,
1569 /// `KEY` -- matches `constraint_type == "key"`. Never combines with
1570 /// `PROPERTY` (CIP-74 SD[12]/SD[13]).
1571 Key,
1572 /// `TYPE`, optionally `PROPERTY`-prefixed -- matches `constraint_type
1573 /// == "propertyType"` (CIP-85/CIP-100).
1574 PropertyType,
1575 /// `EXIST`/`EXISTENCE` -- property existence plus the four
1576 /// label/endpoint-label kinds (CIP-187's filtering table: a bare
1577 /// `EXIST[ENCE]`/`NODE EXIST[ENCE]` matches `NODE_LABEL_EXISTENCE`
1578 /// too).
1579 Existence,
1580 /// `PROPERTY EXIST[ENCE]` (CIP-187) -- property existence only
1581 /// (`constraint_type == "exists"`), never the label/endpoint-label
1582 /// kinds the bare [`Self::Existence`] also admits. Its own variant —
1583 /// the grammar distinguishes the two spellings at parse time, so the
1584 /// AST carries the distinction typed, never as a side-channel bool
1585 /// beside the kind.
1586 PropertyExistence,
1587}
1588
1589/// `SHOW <type filter> CONSTRAINTS` -- `entity` narrows by `entityType`,
1590/// `kind` narrows by constraint kind. `ConstraintTypeFilter::all()` (empty
1591/// entity, no kind) is the default for bare `SHOW CONSTRAINTS`/`SHOW ALL
1592/// CONSTRAINTS`, matching every constraint.
1593#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1594pub struct ConstraintTypeFilter {
1595 pub entity: ConstraintEntityFilter,
1596 pub kind: Option<ConstraintKindFilter>,
1597}
1598
1599impl ConstraintTypeFilter {
1600 pub fn all() -> Self {
1601 ConstraintTypeFilter {
1602 entity: ConstraintEntityFilter::Any,
1603 kind: None,
1604 }
1605 }
1606}
1607
1608/// `SHOW DATABASE[S] [<filter>] [YIELD ...] [WHERE ...]` (CIP-42/CIP-68).
1609#[derive(Debug, Clone, PartialEq)]
1610pub struct ShowDatabasesClause {
1611 pub filter: DatabaseFilter,
1612 pub yields: YieldList,
1613 pub where_expr: Option<Expr>,
1614 pub stages: Vec<PageStage>,
1615}
1616
1617/// Which database(s) a `SHOW DATABASE[S]` clause reports (CIP-68's
1618/// `DEFAULT`/`HOME` singular-only forms).
1619#[derive(Debug, Clone, PartialEq)]
1620pub enum DatabaseFilter {
1621 /// Bare `SHOW DATABASE[S]` -- every database.
1622 All,
1623 /// `SHOW DEFAULT DATABASE` -- singular only, CIP-68 rejects the plural
1624 /// `SHOW DEFAULT DATABASES`.
1625 Default,
1626 /// `SHOW HOME DATABASE` -- singular only, same restriction as `Default`.
1627 Home,
1628 /// `SHOW DATABASE[S] <name>` -- one named database.
1629 Named(SchemaName),
1630}
1631
1632/// `SHOW [ALL|POPULATED] ROLE[S] [WITH USER[S]] [YIELD ...] [WHERE ...]`
1633/// (CIP-68).
1634#[derive(Debug, Clone, PartialEq)]
1635pub struct ShowRolesClause {
1636 pub modifier: RoleModifier,
1637 /// `WITH USER[S]` -- when true, the catalog carries one row per
1638 /// (role, member) pair (adding the `member` column) instead of one row
1639 /// per role.
1640 pub with_users: bool,
1641 pub yields: YieldList,
1642 pub where_expr: Option<Expr>,
1643 pub stages: Vec<PageStage>,
1644}
1645
1646/// The `[ALL|POPULATED]` modifier of `SHOW ROLE[S]` -- `Any` (bare `SHOW
1647/// ROLE[S]`) and `All` (`SHOW ALL ROLE[S]`) report the identical row set
1648/// (every role); `Populated` narrows to roles with at least one member.
1649#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1650pub enum RoleModifier {
1651 Any,
1652 All,
1653 Populated,
1654}
1655
1656/// `SHOW SERVER[S] [YIELD ...] [WHERE ...]` (CIP-68).
1657#[derive(Debug, Clone, PartialEq)]
1658pub struct ShowServersClause {
1659 pub yields: YieldList,
1660 pub where_expr: Option<Expr>,
1661 pub stages: Vec<PageStage>,
1662}
1663
1664/// `SHOW USER[S] [YIELD ...] [WHERE ...]` / `SHOW CURRENT USER` (CIP-68).
1665#[derive(Debug, Clone, PartialEq)]
1666pub struct ShowUsersClause {
1667 /// `SHOW CURRENT USER` -- singular only, CIP-68 rejects the plural
1668 /// `SHOW CURRENT USERS`.
1669 pub current_only: bool,
1670 pub yields: YieldList,
1671 pub where_expr: Option<Expr>,
1672 pub stages: Vec<PageStage>,
1673}
1674
1675/// `SHOW PROCEDURE[S] [YIELD ...] [WHERE ...]` (CIP-68 grammar
1676/// foundation).
1677#[derive(Debug, Clone, PartialEq)]
1678pub struct ShowProceduresClause {
1679 pub yields: YieldList,
1680 pub where_expr: Option<Expr>,
1681 pub stages: Vec<PageStage>,
1682 /// `EXECUTABLE [BY <user>]`, when written.
1683 pub executable: Option<ExecutableBy>,
1684}
1685
1686/// `SHOW SETTING[S] [<names>] [YIELD ...] [WHERE ...]` (CIP-68 grammar
1687/// foundation). `names` is the optional expression naming the setting(s) to
1688/// filter to: a STRING or a LIST<STRING> (or a `null`/parameter resolving to
1689/// either). The executor selects from its own fixed settings catalog -- a
1690/// null selects nothing, an empty list means "no filter" (CIP-253), and any
1691/// other shape is a `TypeError`.
1692#[derive(Debug, Clone, PartialEq)]
1693pub struct ShowSettingsClause {
1694 pub names: Option<Expr>,
1695 pub yields: YieldList,
1696 pub where_expr: Option<Expr>,
1697 pub stages: Vec<PageStage>,
1698}
1699
1700/// `SHOW TRANSACTION[S] [<id-list>] [YIELD ...] [WHERE ...]` (CIP-68
1701/// grammar foundation). `ids` is the optional comma-separated list of
1702/// transaction-id expressions to filter to (empty = no filter) --
1703/// Relate has no live-transaction catalog, so it's parsed but never
1704/// changes the (always empty) result.
1705#[derive(Debug, Clone, PartialEq)]
1706pub struct ShowTransactionsClause {
1707 pub ids: Vec<Expr>,
1708 pub yields: YieldList,
1709 pub where_expr: Option<Expr>,
1710 pub stages: Vec<PageStage>,
1711}
1712
1713/// `TERMINATE TRANSACTION[S] <id-list> [YIELD ...]` (CIP-68 grammar
1714/// foundation). Since `ShowTransactions` never reports a live transaction,
1715/// every requested id is reported as not found.
1716#[derive(Debug, Clone, PartialEq)]
1717pub struct TerminateTransactionsClause {
1718 pub ids: Vec<Expr>,
1719 pub yields: YieldList,
1720}
1721
1722/// CALL db.procedure() YIELD ... clause.
1723#[derive(Debug, Clone, PartialEq)]
1724pub struct CallProcedureClause {
1725 pub procedure: SmallName,
1726 pub args: Vec<Expr>,
1727 /// Whether the procedure name was followed by an explicit argument list,
1728 /// including an empty `()`. Relate needs this to distinguish `CALL p`
1729 /// (implicit arguments) from `CALL p()` (no arguments).
1730 pub explicit_args: bool,
1731 pub yields: YieldList,
1732 /// CIP-159: `OPTIONAL CALL proc(...)` -- when the procedure call yields
1733 /// zero rows (after any `WHERE` in `YIELD`) for a given outer row, that
1734 /// outer row is null-padded instead of being dropped. Void-procedure
1735 /// and zero-outer-row semantics are handled by the engine.
1736 pub optional: bool,
1737 /// CIP-159: `WHERE` inside the `YIELD` clause -- part of the
1738 /// `<procedure call>` production, filtering the procedure's own result
1739 /// rows (may reference the outer row's variables) before they're
1740 /// merged into the pipeline.
1741 pub where_expr: Option<Expr>,
1742}
1743
1744// -- Pattern nodes --
1745
1746/// A path pattern like (a)-[r]->(b), optionally named: p = (a)-[r]->(b).
1747#[derive(Debug, Clone, PartialEq)]
1748pub struct PatternPath {
1749 pub variable: Option<SmallName>,
1750 /// CIP-73: the subpath variable of a named parenthesized group that is
1751 /// itself the whole path body (`MATCH p = ANY SHORTEST (q = (:A)-->+(:B))`,
1752 /// `MATCH ANY SHORTEST (q = (:A)-->+(:B))`). [`Self::variable`] carries
1753 /// only the enclosing `p = …` name; both names bind the same path value
1754 /// and [`Self::path_names`] lists them. A lone group name (no enclosing
1755 /// path name) stays here, not in `variable`, so a group reading its own
1756 /// name inside its `WHERE` stays distinguishable from an enclosing path
1757 /// variable read there (42I21).
1758 pub subpath_variable: Option<SmallName>,
1759 pub elements: Vec<PatternElement>,
1760 /// The trailing `WHERE` of a parenthesized path pattern, e.g.
1761 /// `((n)-[r]->(m) WHERE n.p > m.q AND r:S)` (CIP-14 "parenthesized path
1762 /// pattern" location). Evaluated once every element in the path is
1763 /// bound, ANDed with the pattern match itself.
1764 pub where_expr: Option<Expr>,
1765 /// CIP-51 explicit path mode prefix (`WALK`/`TRAIL`/`ACYCLIC`/`SIMPLE`),
1766 /// written directly or nested inside a `selector`'s own `[path mode]`
1767 /// slot. `None` means no explicit keyword (Rule 1: resolves to `Walk`).
1768 pub mode: Option<PathMode>,
1769 /// CIP-73/CIP-191 path selector prefix (`ALL`/`ANY`/`SHORTEST`/...).
1770 /// `None` means no explicit selector (equivalent to an implicit `ALL`).
1771 pub selector: Option<PathSelector>,
1772 /// True if this path pattern is sugar for the pre-GPM
1773 /// `shortestPath(...)`/`allShortestPaths(...)` function (CIP-40/CIP-73
1774 /// Section 3.3), rather than an explicit `SHORTEST`/`ALL SHORTEST`
1775 /// selector keyword -- even though both normalize to the same
1776 /// `selector` value. The two are NOT interchangeable for CIP-40's
1777 /// mixing rules: the legacy function forms are exempt from the
1778 /// explicit-match-mode and multiple-selective-path-pattern
1779 /// restrictions that apply to the keyword selector syntax (see
1780 /// `Parser::parse_match`).
1781 pub is_shortest_path_function: bool,
1782}
1783
1784impl PatternPath {
1785 /// The names this path binds its path value under, in declaration order:
1786 /// the outer path variable, then a named parenthesized subpath. The two
1787 /// name the same path value; the IR twin is `PathPattern::path_names`.
1788 pub fn path_names(&self) -> impl Iterator<Item = &SmallName> {
1789 [self.variable.as_ref(), self.subpath_variable.as_ref()]
1790 .into_iter()
1791 .flatten()
1792 }
1793}
1794
1795/// A pattern element is either a node pattern, a relationship pattern, or a
1796/// quantified path pattern (CIP-28).
1797#[derive(Debug, Clone, PartialEq)]
1798pub enum PatternElement {
1799 Node(NodePattern),
1800 Relationship(RelPattern),
1801 Quantified(QuantifiedPathPattern),
1802}
1803
1804/// The `{min, max}` bounds of a CIP-28 quantifier (`*`, `+`, `{m,n}`, `{m,}`,
1805/// `{,n}`, `{,}`, `{n}`). `max = None` means unbounded. Bounds are already
1806/// normalized and validated by the parser: Rule 1 (`{,}` -> `{0,}`) and
1807/// Rule 2 (upper bound > 0, lower bound <= upper bound) are enforced at
1808/// parse time, so every `PathQuantifier` that reaches the AST is legal.
1809#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1810pub struct PathQuantifier {
1811 pub min: u32,
1812 pub max: Option<u32>,
1813}
1814
1815/// A quantified path pattern (CIP-28 Section 3.1): a parenthesized subpath
1816/// (`elements`), optionally assigned a subpath variable (CIP-28 Section 3.3,
1817/// e.g. `(p2 = (x)-->(y))*`) and/or a trailing `WHERE` evaluated once per
1818/// iteration, followed by a quantifier. Appears as a `PatternElement`
1819/// alongside plain `Node`/`Relationship` elements so it composes freely with
1820/// them by concatenation (CIP-28 Section 3.1.7).
1821///
1822/// A bare quantified relationship (`-[r]->*`, Form 5) does *not* produce this
1823/// variant: it normalizes directly into the ordinary variable-length
1824/// `RelPattern` (`min_hops`/`max_hops`), since it declares no element
1825/// variables of its own to expose as a group and its matching semantics are
1826/// identical to the legacy `-[*min..max]->` matcher (only the quantifier's
1827/// own zero-inclusive defaults differ, e.g. bare `*` means 0 or more here
1828/// versus 1 or more for legacy bare `*`). See `Parser::parse_rel_pattern`.
1829#[derive(Debug, Clone, PartialEq)]
1830pub struct QuantifiedPathPattern {
1831 pub subpath_variable: Option<SmallName>,
1832 pub elements: Vec<PatternElement>,
1833 pub where_expr: Option<Expr>,
1834 pub quantifier: PathQuantifier,
1835}
1836
1837/// A node pattern like (n:Label {prop: value}).
1838#[derive(Debug, Clone, PartialEq)]
1839pub struct NodePattern {
1840 pub variable: Option<SmallName>,
1841 pub label_expr: Option<LabelExpr>,
1842 pub properties: Vec<(SmallName, Expr)>,
1843 pub has_properties: bool,
1844 /// The `$paramName` whole-property-map shorthand (an alternative to
1845 /// `{...}`), e.g. `CREATE (n:Label $props)`. Mutually exclusive with
1846 /// `properties`/`has_properties` -- the parser only ever populates one
1847 /// property-map form per pattern element.
1848 pub properties_param: Option<Expr>,
1849 /// The element-pattern `WHERE` of `(n WHERE <expr>)` (CIP-14 "node
1850 /// element pattern" location), evaluated once `variable` is bound.
1851 pub where_expr: Option<Expr>,
1852}
1853
1854/// A relationship pattern like -[r:TYPE {prop: value}]->.
1855#[derive(Debug, Clone, PartialEq)]
1856pub struct RelPattern {
1857 pub variable: Option<SmallName>,
1858 pub type_expr: Option<LabelExpr>,
1859 pub properties: Vec<(SmallName, Expr)>,
1860 /// Whether a property specification was *written*, in either spelling.
1861 /// The rel twin of [`NodePattern`]'s field: set for `{}` too, so
1862 /// `-[] {}]-` and `(a {})` agree wherever "has predicates" is asked
1863 /// (CIP-225 Rule 7, 42N56) — live-verified against Neo4j.
1864 pub has_properties: bool,
1865 /// The `$paramName` whole-property-map shorthand -- see
1866 /// `NodePattern::properties_param`.
1867 pub properties_param: Option<Expr>,
1868 pub direction: Direction,
1869 pub min_hops: Option<u32>,
1870 pub max_hops: Option<u32>,
1871 /// The element-pattern `WHERE` of `[r WHERE <expr>]`.
1872 pub where_expr: Option<Expr>,
1873 /// True when `min_hops`/`max_hops` came from a CIP-28 postfix quantifier
1874 /// (`-[r]->*`, `-->+`, `-[]->{1,6}`, Form 5) rather than the legacy
1875 /// bracket-internal `[r*min..max]` syntax. Distinguishes the two so the
1876 /// engine can apply `where_expr` per traversed edge for the CIP-28 form
1877 /// without changing the legacy matcher's (TCK-tested) behavior.
1878 pub quantified: bool,
1879}
1880
1881impl RelPattern {
1882 /// Whether the relationship is variable-length: either hop bound was
1883 /// written (`*m..n`, or a CIP-28 quantifier lowered onto the bounds).
1884 /// The one predicate every consumer consults instead of re-spelling
1885 /// the two `is_some` checks.
1886 pub fn is_variable_length(&self) -> bool {
1887 self.min_hops.is_some() || self.max_hops.is_some()
1888 }
1889}
1890
1891/// A GQL label/relationship-type expression (CIP-14): `&` (conjunction),
1892/// `|` (disjunction), `!` (negation), `%` (wildcard -- matches any non-empty
1893/// label set, or any relationship since every relationship has exactly one
1894/// type), parenthesized grouping (folded directly into the tree, so no
1895/// explicit `Group` variant is needed), and CIP-249's dynamic label name
1896/// `$(expr)`. The legacy colon-conjunction shorthand `:A:B:C` lowers to
1897/// `And([Label(A), Label(B), Label(C)])`, and the legacy relationship-type
1898/// disjunction shorthand `:A|B` lowers to `Or([Label(A), Label(B)])`,
1899/// preserving pre-CIP-14 behavior exactly.
1900#[derive(Debug, Clone, PartialEq)]
1901pub enum LabelExpr {
1902 /// A single label/type name.
1903 Label(SmallName),
1904 /// `%`
1905 Wildcard,
1906 /// `$(expr)` / `$all(expr)` / `$any(expr)` -- a label/type name (or, for
1907 /// list-valued `expr`, a set of label/type names) resolved at runtime
1908 /// (CIP-249 / CIP-156 / CIP-221).
1909 Dynamic(DynamicLabelExpr),
1910 /// `!<label-expr>` -- negates only the following primary.
1911 Not(Box<LabelExpr>),
1912 /// `<label-expr> & <label-expr> & ...`
1913 And(Vec<LabelExpr>),
1914 /// `<label-expr> | <label-expr> | ...`
1915 Or(Vec<LabelExpr>),
1916}
1917
1918/// A dynamic label/type expression's quantifier: `$(expr)` (`Default`),
1919/// `$all(expr)` (`All`), or `$any(expr)` (`Any`). `Default` and `All` share
1920/// conjunction semantics for list-valued `expr` (and are otherwise
1921/// interchangeable); `Any` is disjunction. Kept distinct from `All` so
1922/// callers (e.g. `CREATE`/`MERGE` label resolution) can reject the explicit
1923/// `$any(...)` form while still accepting the implicit-all `$(...)` form.
1924#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1925pub enum DynamicLabelQuantifier {
1926 Default,
1927 All,
1928 Any,
1929}
1930
1931/// The payload of `LabelExpr::Dynamic`: the value expression plus its
1932/// quantifier.
1933#[derive(Debug, Clone, PartialEq)]
1934pub struct DynamicLabelExpr {
1935 pub expr: Box<Expr>,
1936 pub quantifier: DynamicLabelQuantifier,
1937}
1938
1939impl LabelExpr {
1940 /// Returns the flat list of label names if this expression is a plain
1941 /// label list: a single label, or an `And` of only plain labels (as
1942 /// produced by legacy colon-conjunction `:A:B:C`, or a comma-separated
1943 /// SET/REMOVE label item). Returns `None` for anything using `|`, `!`,
1944 /// `%`, or a dynamic label -- those aren't valid label lists (CREATE /
1945 /// MERGE / SET / REMOVE label specifications, per CIP-14's "DML
1946 /// statements" exclusion and CIP-126).
1947 pub fn as_label_list(&self) -> Option<Vec<SmallName>> {
1948 match self {
1949 LabelExpr::Label(name) => Some(vec![name.clone()]),
1950 LabelExpr::And(items) => {
1951 let mut out = Vec::with_capacity(items.len());
1952 for item in items {
1953 match item {
1954 LabelExpr::Label(name) => out.push(name.clone()),
1955 _ => return None,
1956 }
1957 }
1958 Some(out)
1959 }
1960 _ => None,
1961 }
1962 }
1963
1964 /// True if this expression contains `!` (negation) or `%` (wildcard)
1965 /// anywhere, recursively. Used to reject a variable-length quantifier
1966 /// combined with negation/wildcard (CIP-14).
1967 pub fn contains_not_or_wildcard(&self) -> bool {
1968 match self {
1969 LabelExpr::Label(_) | LabelExpr::Dynamic(_) => false,
1970 LabelExpr::Wildcard | LabelExpr::Not(_) => true,
1971 LabelExpr::And(items) | LabelExpr::Or(items) => {
1972 items.iter().any(LabelExpr::contains_not_or_wildcard)
1973 }
1974 }
1975 }
1976
1977 /// Returns the flat list of label/type names if this expression is a
1978 /// plain label or `|`-disjunction list: a single label, or an `Or` of
1979 /// only plain labels (as produced by `A|B|C`). Returns `None` for
1980 /// anything using `&`, `!`, `%`, or a dynamic label. Used by the
1981 /// CREATE INDEX / CREATE CONSTRAINT `FOR` target (CIP-11/CIP-38/
1982 /// CIP-235's `FOR (n:A|B)` multi-label DDL surface) -- a narrower
1983 /// grammar than general MATCH label expressions.
1984 pub fn as_ddl_list(&self) -> Option<Vec<SmallName>> {
1985 match self {
1986 LabelExpr::Label(name) => Some(vec![name.clone()]),
1987 LabelExpr::Or(items) => {
1988 let mut out = Vec::with_capacity(items.len());
1989 for item in items {
1990 match item {
1991 LabelExpr::Label(name) => out.push(name.clone()),
1992 _ => return None,
1993 }
1994 }
1995 Some(out)
1996 }
1997 _ => None,
1998 }
1999 }
2000
2001 /// True if this expression contains a `$(...)`/`$all(...)`/`$any(...)`
2002 /// dynamic label/type atom anywhere, recursively (CIP-156). Used by
2003 /// CREATE/MERGE's static "exactly one relationship type" check to defer
2004 /// to runtime resolution when the count can't be known until the
2005 /// dynamic expression is evaluated.
2006 pub fn contains_dynamic(&self) -> bool {
2007 match self {
2008 LabelExpr::Label(_) | LabelExpr::Wildcard => false,
2009 LabelExpr::Dynamic(_) => true,
2010 LabelExpr::Not(inner) => inner.contains_dynamic(),
2011 LabelExpr::And(items) | LabelExpr::Or(items) => {
2012 items.iter().any(LabelExpr::contains_dynamic)
2013 }
2014 }
2015 }
2016}
2017
2018/// Direction of a relationship.
2019#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2020pub enum Direction {
2021 Right, // (a)-[]->(b)
2022 Left, // (a)<-[]-(b)
2023 Both, // (a)-[]-(b)
2024}
2025
2026// -- Expression nodes --
2027
2028mod expr_children;
2029pub use expr_children::{Edge, EdgeMut};
2030
2031/// One segment of a CIP-261 interpolated string literal.
2032#[derive(Debug, Clone, PartialEq)]
2033pub enum InterpPart {
2034 /// Literal text (escaped braces already resolved to plain braces).
2035 Text(String),
2036 /// An `{expression}` embed.
2037 Interp(Box<Expr>),
2038}
2039
2040/// All expression types.
2041#[derive(Debug, Clone, PartialEq)]
2042pub enum Expr {
2043 Literal(LiteralValue),
2044 List(Vec<Expr>),
2045 Map(Vec<MapPair>),
2046 /// CIP-261 interpolated string literal: text segments interleaved with
2047 /// `{expression}` embeds, lowered to the internal `string.interp`
2048 /// function (see `relate/relate-front/src/lower.rs`).
2049 StringInterp(Vec<InterpPart>),
2050 Variable(SmallName),
2051 Parameter(String),
2052 Property(Box<PropertyAccess>),
2053 FunctionCall(FunctionCallExpr),
2054 Binary(Box<BinaryExpr>),
2055 Unary(Box<UnaryExpr>),
2056 Comparison(Box<ComparisonExpr>),
2057 In(Box<InExpr>),
2058 IsNull(Box<IsNullExpr>),
2059 IsType(Box<IsTypeExpr>),
2060 IsNormalized(Box<IsNormalizedExpr>),
2061 ChronologicalCompare(Box<ChronologicalCompareExpr>),
2062 StringMatch(Box<StringMatchExpr>),
2063 CountStar,
2064 Star,
2065 Case(Box<CaseExpr>),
2066 ExistsSubquery(Box<ExistsSubqueryExpr>),
2067 CountSubquery(Box<CountSubqueryExpr>),
2068 CollectSubquery(Box<CollectSubqueryExpr>),
2069 ListComprehension(Box<ListComprehensionExpr>),
2070 MapComprehension(Box<MapComprehensionExpr>),
2071 PatternComprehension(Box<PatternComprehensionExpr>),
2072 Reduce(Box<ReduceExpr>),
2073 AllReduce(Box<AllReduceExpr>),
2074 ShortestPath(Box<ShortestPathExpr>),
2075 Subscript(Box<SubscriptExpr>),
2076 Quantifier(Box<QuantifierExpr>),
2077 HasLabel(Box<HasLabelExpr>),
2078 Paren(Box<Expr>),
2079 PatternPredicate(Box<PatternPredicateExpr>),
2080 MapProjection(Box<MapProjectionExpr>),
2081 /// The canonical `?` marker for an `OPTIONS` value outside the persisted
2082 /// five-literal vocabulary (a list, map, temporal, …), produced only when
2083 /// a whole-map `OPTIONS $param` is resolved into literal entries. The
2084 /// parser never produces it and it references nothing, so no walker can
2085 /// mistake it for a variable.
2086 OptionValuePlaceholder,
2087}
2088
2089/// A literal value in the AST.
2090#[derive(Debug, Clone, PartialEq)]
2091pub enum LiteralValue {
2092 Null,
2093 Bool(bool),
2094 Integer(i64),
2095 Float(f64),
2096 String(String),
2097}
2098
2099/// A key-value pair in a map literal.
2100#[derive(Debug, Clone, PartialEq)]
2101pub struct MapPair {
2102 pub key: SmallName,
2103 pub value: Expr,
2104}
2105
2106/// `<variable> <map projection>` (`n {.foo, bar, baz: qux}`): openCypher's
2107/// map projection, syntactically always rooted at a plain variable
2108/// (`expr` is always an `Expr::Variable`). Needed for CIP-190's
2109/// near-ambiguity coverage: `exists {name: exists.name}` etc. must parse
2110/// as a map projection on a variable named `exists`, not as
2111/// `EXISTS { <subquery> }`, when the filler between the braces looks like
2112/// projection items rather than subquery content (near-ambiguities.feature).
2113#[derive(Debug, Clone, PartialEq)]
2114pub struct MapProjectionExpr {
2115 pub expr: Expr,
2116 pub items: Vec<MapProjectionItem>,
2117}
2118
2119/// One item of a `<map projection>`.
2120#[derive(Debug, Clone, PartialEq)]
2121pub enum MapProjectionItem {
2122 /// `.*` -- every property of the base entity.
2123 AllProperties,
2124 /// `.prop` -- shorthand for `prop: <base>.prop`.
2125 Property(SmallName),
2126 /// A bare `variable` selector -- shorthand for `variable: variable`,
2127 /// pulling a same-named variable from the surrounding scope (*not* a
2128 /// property of the base expression).
2129 Variable(SmallName),
2130 /// `key: <expr>` -- a literal entry.
2131 KeyValue(SmallName, Expr),
2132}
2133
2134/// Property access like n.prop.
2135#[derive(Debug, Clone, PartialEq)]
2136pub struct PropertyAccess {
2137 pub expr: Expr,
2138 pub property: SmallName,
2139 /// CIP-131: when a SET/REMOVE target uses the dynamic-property bracket
2140 /// form (`n[<expr>]`) instead of the static `n.prop` form, the property
2141 /// key is computed at runtime from this expression rather than being the
2142 /// statically-known `property` string (which is left empty). `None` for
2143 /// every static `.prop` access, keeping `property` back-compatible for
2144 /// all existing (non-SET/REMOVE) uses of `PropertyAccess`.
2145 pub key_expr: Option<Expr>,
2146}
2147
2148/// Function call like count(x).
2149#[derive(Debug, Clone, PartialEq)]
2150pub struct FunctionCallExpr {
2151 pub name: SmallName,
2152 pub args: Vec<Expr>,
2153 pub distinct: bool,
2154}
2155
2156/// Binary expression like a + b. `op` is the operator's AST spelling, a
2157/// `&'static str` drawn from the parser's operator-constant table
2158/// (`parser/mod.rs`, ADR-0505 §2) — never a runtime-built `String`.
2159#[derive(Debug, Clone, PartialEq)]
2160pub struct BinaryExpr {
2161 pub left: Expr,
2162 pub op: &'static str,
2163 pub right: Expr,
2164}
2165
2166/// Unary expression like NOT x or -x. `op` is the operator's AST spelling,
2167/// a `&'static str` drawn from the parser's operator-constant table
2168/// (`parser/mod.rs`, ADR-0505 §2) — never a runtime-built `String`.
2169#[derive(Debug, Clone, PartialEq)]
2170pub struct UnaryExpr {
2171 pub op: &'static str,
2172 pub expr: Expr,
2173}
2174
2175/// Comparison expression like a > b. `op` is the operator's AST spelling, a
2176/// `&'static str` from the `comparison_op` token-to-spelling table
2177/// (`parser/mod.rs`, ADR-0505 §2) — never a runtime-built `String`.
2178#[derive(Debug, Clone, PartialEq)]
2179pub struct ComparisonExpr {
2180 pub left: Expr,
2181 pub op: &'static str,
2182 pub right: Expr,
2183}
2184
2185/// x IN list.
2186#[derive(Debug, Clone, PartialEq)]
2187pub struct InExpr {
2188 pub expr: Expr,
2189 pub list: Expr,
2190}
2191
2192/// x IS NULL or x IS NOT NULL.
2193#[derive(Debug, Clone, PartialEq)]
2194pub struct IsNullExpr {
2195 pub expr: Expr,
2196 pub negated: bool,
2197}
2198
2199/// x IS [NOT] :: <value type> (CIP-86/CIP-87 type predicate expression);
2200/// also produced by the `IS [NOT] TYPED <value type>` and bare `x :: <value
2201/// type>` surface forms, which are equivalent.
2202#[derive(Debug, Clone, PartialEq)]
2203pub struct IsTypeExpr {
2204 pub expr: Expr,
2205 pub type_expr: TypeExpr,
2206 pub negated: bool,
2207}
2208
2209/// A parsed `<value type>` per the CIP-86 grammar: the vocabulary used by
2210/// the CIP-87 type predicate expression (`IS [NOT] :: <type>`) and, once
2211/// CIP-90 ships, by `valueType()`.
2212#[derive(Debug, Clone, PartialEq)]
2213pub enum TypeExpr {
2214 /// A predefined leaf type: a scalar, temporal, reference, point, map,
2215 /// nothing/null, or the open `ANY` type. `not_null` reflects an
2216 /// explicit `NOT NULL` suffix directly on this leaf's own grammar
2217 /// production (e.g. `INTEGER NOT NULL`).
2218 Predefined {
2219 kind: PredefinedKind,
2220 not_null: bool,
2221 },
2222 /// `LIST<T>` / `T LIST` / `ARRAY<T>` / `T ARRAY`, with an optional
2223 /// `NOT NULL` on the list value itself (not on its elements -- element
2224 /// nullability lives in `element`).
2225 List {
2226 element: Box<TypeExpr>,
2227 not_null: bool,
2228 },
2229 /// `[ANY] PROPERTY VALUE [NOT NULL]`: the dynamic union of every
2230 /// property-storable scalar type and lists thereof.
2231 PropertyValue { not_null: bool },
2232 /// A closed dynamic union -- `ANY [VALUE] <A | B | ...>` or the bare
2233 /// `A | B | ...` form (equivalent). The grammar gives closed unions no
2234 /// `[NOT NULL]` production of their own, so the parser never attaches
2235 /// one here; a trailing `NOT NULL` after a union is a syntax error.
2236 Union(Vec<TypeExpr>),
2237 /// `VECTOR<TYPE [NOT NULL]>(DIM)` (Cypher style) or `VECTOR(DIM, TYPE
2238 /// [NOT NULL])` (GQL style) (CIP-216). Either the coordinate type or
2239 /// the dimension may be grammatically omitted (`VECTOR(3)`,
2240 /// `VECTOR<INTEGER32>`) -- both parse fine but are rejected at
2241 /// constraint-creation time, since a property type constraint requires
2242 /// both. The coordinate type's own `NOT NULL` is mandatory/implicit
2243 /// (always rendered NOT NULL in canonical form) and so isn't tracked
2244 /// separately here; `not_null` is the *outer* NOT NULL on the whole
2245 /// vector type (valid grammatically, but rejected for independent
2246 /// property type constraints -- CIP-216 doc, "for dependent property
2247 /// type constraints only").
2248 Vector {
2249 coord: Option<VectorCoordKind>,
2250 dimension: Option<i64>,
2251 not_null: bool,
2252 },
2253}
2254
2255impl TypeExpr {
2256 /// The `NOT NULL` flag attached directly to this node's own grammar
2257 /// production. Used only to check that a closed union's components all
2258 /// agree on nullability (CIP-86 "Not Null Uses"); closed unions have no
2259 /// such production of their own, so they report `false`.
2260 pub fn direct_not_null(&self) -> bool {
2261 match self {
2262 TypeExpr::Predefined { not_null, .. } => *not_null,
2263 TypeExpr::List { not_null, .. } => *not_null,
2264 TypeExpr::PropertyValue { not_null } => *not_null,
2265 TypeExpr::Vector { not_null, .. } => *not_null,
2266 TypeExpr::Union(_) => false,
2267 }
2268 }
2269}
2270
2271/// A vector coordinate type (CIP-216): the six numeric types valid inside
2272/// `VECTOR<...>`/`VECTOR(...)`. `Int64`/`Float64` double as ordinary plain
2273/// property types (aliases for `INTEGER`/`FLOAT`, see `PredefinedKind`)
2274/// outside a vector type; the other four (`Float32`, `Int8`/`Int16`/
2275/// `Int32`) are valid only as a vector coordinate type.
2276///
2277/// Defined in `relate-model` (so the runtime `CypherValue::Vector`
2278/// variant can carry it without a circular crate dependency) and
2279/// re-exported here under its original name/location.
2280pub use relate_model::VectorCoordKind;
2281
2282/// The predefined leaf type names from CIP-86's `<value type>` grammar.
2283#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2284pub enum PredefinedKind {
2285 Nothing,
2286 Null,
2287 Any,
2288 Boolean,
2289 String,
2290 Integer,
2291 Float,
2292 Date,
2293 Duration,
2294 Point,
2295 LocalTime,
2296 ZonedTime,
2297 LocalDateTime,
2298 ZonedDateTime,
2299 Node,
2300 Relationship,
2301 Path,
2302 Map,
2303 /// CIP-246 `UUID [NOT NULL]`.
2304 Uuid,
2305}
2306
2307/// x IS [NOT] [<normal form>] NORMALIZED (CIP-133). `form` is one of
2308/// "NFC"/"NFD"/"NFKC"/"NFKD", or None when the form is omitted (defaults to
2309/// NFC at evaluation time).
2310#[derive(Debug, Clone, PartialEq)]
2311pub struct IsNormalizedExpr {
2312 pub expr: Expr,
2313 pub form: Option<String>,
2314 pub negated: bool,
2315}
2316
2317/// The four chronological comparison operators (Cypher 25):
2318/// `a IS [NOT] BEFORE | AFTER | SAME INSTANT | SAME REPRESENTATION b`.
2319/// The four words stay non-reserved identifiers everywhere else
2320/// (TemporalChronologicalCompare's non-reserved-identifier scenario), so
2321/// the parser recognizes them contextually after an `IS` introducer, the
2322/// same policy as `TYPED`/`NORMALIZED`/`LABELED`.
2323#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2324pub enum ChronologicalOp {
2325 Before,
2326 After,
2327 SameInstant,
2328 SameRepresentation,
2329}
2330
2331/// `a IS [NOT] <chronological operator> b` (Cypher 25). `SameInstant`
2332/// compares UTC instants, `SameRepresentation` the local clock plus zone
2333/// identity (the `=` relation), and `Before`/`After` the instant ordering;
2334/// the executor owns the null/mixed-kind policy.
2335#[derive(Debug, Clone, PartialEq)]
2336pub struct ChronologicalCompareExpr {
2337 pub left: Expr,
2338 pub op: ChronologicalOp,
2339 pub right: Expr,
2340 pub negated: bool,
2341}
2342
2343/// STARTS WITH, ENDS WITH, CONTAINS. `op` is the operator's AST spelling, a
2344/// `&'static str` drawn from the parser's operator-constant table
2345/// (`parser/mod.rs`, ADR-0505 §2) — never a runtime-built `String`.
2346#[derive(Debug, Clone, PartialEq)]
2347pub struct StringMatchExpr {
2348 pub left: Expr,
2349 pub op: &'static str,
2350 pub right: Expr,
2351}
2352
2353/// CASE expression. The simple form's test operand is lowered at parse time
2354/// into each `WHEN`'s equality comparison (`parser/case.rs`), so the stored
2355/// model is the searched form only: every condition is a predicate.
2356#[derive(Debug, Clone, PartialEq)]
2357pub struct CaseExpr {
2358 pub whens: Vec<WhenClause>,
2359 pub else_expr: Option<Expr>,
2360}
2361
2362/// WHEN ... THEN ... part of a CASE: the condition is always a predicate
2363/// (the simple form's `operand = value` lowering included).
2364#[derive(Debug, Clone, PartialEq)]
2365pub struct WhenClause {
2366 pub condition: Expr,
2367 pub result: Expr,
2368}
2369
2370/// EXISTS { ... } subquery expression.
2371#[derive(Debug, Clone, PartialEq)]
2372pub struct ExistsSubqueryExpr {
2373 pub statement: Statement,
2374}
2375
2376/// COUNT { ... } subquery expression: evaluates to the number of rows the
2377/// subquery produces against the current row, run independently per row
2378/// (like `EXISTS { ... }`, just returning a count instead of a boolean).
2379#[derive(Debug, Clone, PartialEq)]
2380pub struct CountSubqueryExpr {
2381 pub statement: Statement,
2382}
2383
2384/// `COLLECT { <RegularQuery> }` subquery expression (CIP-71): evaluates the
2385/// inner `<RegularQuery>` once per outer row and collects the single
2386/// projected column's value from every inner row into a list. Unlike
2387/// `EXISTS`/`COUNT`, `COLLECT` has no bare-pattern shorthand -- the inner
2388/// query is always a full `<RegularQuery>` (any read clause, including
2389/// UNION) and must end in a `RETURN` with exactly one non-`*` return item.
2390#[derive(Debug, Clone, PartialEq)]
2391pub struct CollectSubqueryExpr {
2392 pub statement: Statement,
2393}
2394
2395/// CIP-272 map comprehension: `{k : v IN map [WHERE p] | keyExpr : valueExpr}`
2396/// (map source) or `{item IN list [WHERE p] | keyExpr : valueExpr}` (list
2397/// source).
2398#[derive(Debug, Clone, PartialEq)]
2399pub struct MapComprehensionExpr {
2400 /// The key binding variable of a map source (`None` for a list source).
2401 pub key_var: Option<SmallName>,
2402 /// The value binding variable (map source) or the item variable (list
2403 /// source).
2404 pub value_var: SmallName,
2405 pub source_expr: Expr,
2406 pub where_expr: Option<Expr>,
2407 pub key_expr: Expr,
2408 pub value_expr: Expr,
2409}
2410
2411/// [x IN list WHERE pred | expr]
2412#[derive(Debug, Clone, PartialEq)]
2413pub struct ListComprehensionExpr {
2414 pub variable: SmallName,
2415 pub list_expr: Expr,
2416 pub where_expr: Option<Expr>,
2417 pub map_expr: Option<Expr>,
2418}
2419
2420/// [p = (n)-->() | expr] or [(n)-->() | expr]
2421#[derive(Debug, Clone, PartialEq)]
2422pub struct PatternComprehensionExpr {
2423 pub path_variable: Option<SmallName>,
2424 pub pattern: PatternPath,
2425 pub where_expr: Option<Expr>,
2426 pub map_expr: Expr,
2427}
2428
2429/// reduce(accumulator = init, x IN list | expression)
2430#[derive(Debug, Clone, PartialEq)]
2431pub struct ReduceExpr {
2432 pub accumulator: SmallName,
2433 pub init_expr: Expr,
2434 pub variable: SmallName,
2435 pub list_expr: Expr,
2436 pub expression: Expr,
2437}
2438
2439/// allReduce(accumulator = init, x IN list | expression, predicate)
2440#[derive(Debug, Clone, PartialEq)]
2441pub struct AllReduceExpr {
2442 pub accumulator: SmallName,
2443 pub init_expr: Expr,
2444 pub variable: SmallName,
2445 pub list_expr: Expr,
2446 pub expression: Expr,
2447 pub predicate: Expr,
2448}
2449
2450/// shortestPath() / allShortestPaths()
2451#[derive(Debug, Clone, PartialEq)]
2452pub struct ShortestPathExpr {
2453 pub pattern: PatternPath,
2454 pub all: bool,
2455}
2456
2457/// expr[index] or expr[from..to]
2458#[derive(Debug, Clone, PartialEq)]
2459pub struct SubscriptExpr {
2460 pub expr: Expr,
2461 pub index: Option<Expr>,
2462 pub from: Option<Expr>,
2463 pub to: Option<Expr>,
2464 pub slice: bool,
2465}
2466
2467/// all/any/none/single(x IN list WHERE pred)
2468#[derive(Debug, Clone, PartialEq)]
2469pub struct QuantifierExpr {
2470 pub quantifier: String,
2471 pub variable: SmallName,
2472 pub list: Expr,
2473 pub predicate: Option<Expr>,
2474}
2475
2476/// A label/type predicate: `n:Label`, `n IS Label` (CIP-14), or
2477/// `n IS [NOT] LABELED <label-expr>` / the `n IS NOT <label-expr>` shorthand
2478/// (CIP-249).
2479#[derive(Debug, Clone, PartialEq)]
2480pub struct HasLabelExpr {
2481 pub expr: Expr,
2482 pub label_expr: LabelExpr,
2483 /// True for `IS NOT LABELED <LE>` and its `IS NOT <LE>` shorthand, which
2484 /// negate the *whole* expression (unlike an inline `!` inside `label_expr`,
2485 /// which negates only the following primary).
2486 pub negated: bool,
2487 /// True for the CIP-249 `IS [NOT] LABELED <LE>` forms (and the `IS NOT
2488 /// <LE>` shorthand), which raise a runtime type error for a non-node/
2489 /// relationship LHS. False for the pre-existing `:`/bare `IS <LE>`
2490 /// forms (CIP-14), which fall back to `false` for a non-entity LHS,
2491 /// preserving their original behavior.
2492 pub strict: bool,
2493}
2494
2495/// Pattern used as boolean predicate in WHERE, e.g. (n)-[:REL]->(m)
2496#[derive(Debug, Clone, PartialEq)]
2497pub struct PatternPredicateExpr {
2498 pub pattern: PatternPath,
2499}