Skip to main content

core_query/cypher/
ast.rs

1//! Cypher subset AST. Types match the Plan 3 Task 6 interface block.
2
3use crate::filter::CmpOp;
4use core_storage::Value;
5
6/// A LIMIT or SKIP value: either an exact count or a named query parameter.
7///
8/// `$name` parameters are resolved at execution time from the params map and
9/// validated to be a non-negative integer.
10#[derive(Debug, Clone, PartialEq)]
11pub enum LimitSkip {
12    Exact(u64),
13    Param(String),
14}
15
16/// One `OPTIONAL MATCH pattern [WHERE expr]` clause.
17///
18/// If the pattern produces no rows for a given input row, the input row
19/// survives with the optional variables set to `null` (left-outer-join
20/// semantics, openCypher §10.1.3).
21///
22/// `where_expr`, when present, is applied INSIDE the optional scope:
23/// it filters candidate rows before the left-outer fallback fires.  This
24/// differs from a post-filter that would eliminate the null row entirely.
25#[derive(Debug, Clone, PartialEq)]
26pub struct OptionalClause {
27    pub patterns: Vec<Pattern>,
28    /// WHERE clause scoped to this optional match (applied before nullification).
29    pub where_expr: Option<Expr>,
30}
31
32#[derive(Debug, Clone, PartialEq)]
33pub struct Query {
34    pub matches: Vec<Pattern>,
35    /// `OPTIONAL MATCH` clauses that follow the required matches.
36    pub optional_clauses: Vec<OptionalClause>,
37    /// Top-level WHERE filter, evaluated before UNWIND expansion.
38    pub where_expr: Option<Expr>,
39    /// Top-level UNWIND clauses (after WHERE, before post_unwind_where/WITH/RETURN).
40    pub unwinds: Vec<UnwindClause>,
41    /// Optional WHERE evaluated after UNWIND expansion (references UNWIND aliases).
42    pub post_unwind_where: Option<Expr>,
43    /// WITH pipeline stages. Each stage carries a WITH clause and optional
44    /// MATCH / UNWIND / WHERE that follow it.
45    pub stages: Vec<WithStage>,
46    pub returns: Vec<RetItem>,
47    /// `RETURN DISTINCT …` — executor hashes projected rows after `Project`.
48    pub distinct: bool,
49    pub order_by: Vec<OrderItem>,
50    pub skip: Option<LimitSkip>,
51    pub limit: Option<LimitSkip>,
52}
53
54/// One `UNWIND <expr> AS <alias>` clause.
55#[derive(Debug, Clone, PartialEq)]
56pub struct UnwindClause {
57    pub list: UnwindExpr,
58    pub alias: String,
59}
60
61/// The expression whose value is iterated in UNWIND.
62#[derive(Debug, Clone, PartialEq)]
63pub enum UnwindExpr {
64    /// Inline list literal: `[1, 2, 3]`.
65    Lit(Vec<Value>),
66    /// Property on a bound node: `n.tags`.
67    Prop { var: String, field: String },
68    /// A previously bound alias (from a prior WITH): `alias`.
69    Var(String),
70}
71
72/// One WITH stage in a pipeline:
73/// ```text
74/// WITH <items> [WHERE <expr>] [ORDER BY …] [SKIP n] [LIMIT n]
75/// [MATCH …]* [OPTIONAL MATCH …]* [UNWIND …]* [WHERE <expr>]
76/// ```
77#[derive(Debug, Clone, PartialEq)]
78pub struct WithStage {
79    /// The projected items in the WITH clause.
80    pub items: Vec<RetItem>,
81    /// Optional WHERE / HAVING filter immediately after the WITH keyword.
82    pub where_expr: Option<Expr>,
83    pub order_by: Vec<OrderItem>,
84    pub skip: Option<LimitSkip>,
85    pub limit: Option<LimitSkip>,
86    /// MATCH clauses that follow this WITH.
87    pub matches: Vec<Pattern>,
88    /// OPTIONAL MATCH clauses that follow the required MATCHes in this stage.
89    pub optional_clauses: Vec<OptionalClause>,
90    /// UNWIND clauses that follow this WITH.
91    pub unwinds: Vec<UnwindClause>,
92    /// WHERE clause that follows those MATCHes (pre-next-WITH/RETURN filter).
93    pub post_where: Option<Expr>,
94}
95
96/// Aggregate function in a RETURN clause.
97#[derive(Debug, Clone, PartialEq)]
98pub enum AggFunc {
99    Count,
100    Sum,
101    Avg,
102    Min,
103    Max,
104}
105
106/// Argument to an aggregate function.
107#[derive(Debug, Clone, PartialEq)]
108pub enum AggArg {
109    /// `COUNT(*)` — every matched row counts regardless of binding.
110    Star,
111    /// `COUNT(var)` — counts rows where `var` is bound (non-null).
112    Var(String),
113    /// `SUM(var.field)`, `AVG(var.field)`, etc.
114    Prop { var: String, field: String },
115}
116
117/// Hop-count range for variable-length relationship patterns (`*min..max`).
118/// Both bounds are inclusive.  `min = max` is a fixed-hop pattern.
119#[derive(Debug, Clone, Copy, PartialEq, Eq)]
120pub struct HopRange {
121    pub min: u8,
122    pub max: u8,
123}
124
125#[derive(Debug, Clone, PartialEq)]
126pub struct Pattern {
127    pub start: NodePat,
128    pub chain: Vec<(RelPat, NodePat)>,
129    /// True when parsed as `MATCH shortestPath(...)`.
130    pub shortest: bool,
131}
132
133#[derive(Debug, Clone, PartialEq)]
134pub struct NodePat {
135    pub var: Option<String>,
136    pub label: Option<String>,
137    pub props: Vec<(String, Operand)>,
138}
139
140#[derive(Debug, Clone, Copy, PartialEq, Eq)]
141pub enum RelDir {
142    Right,
143    Left,
144    Undirected,
145}
146
147#[derive(Debug, Clone, PartialEq)]
148pub struct RelPat {
149    pub var: Option<String>,
150    pub etype: Option<String>,
151    pub dir: RelDir,
152    /// `None` = single-hop (normal `Expand`).  `Some(r)` = variable-length
153    /// (`VarExpand`) with the given min/max hop bounds.
154    pub hops: Option<HopRange>,
155}
156
157#[derive(Debug, Clone, PartialEq)]
158pub enum Expr {
159    And(Box<Expr>, Box<Expr>),
160    Or(Box<Expr>, Box<Expr>),
161    Not(Box<Expr>),
162    Cmp {
163        lhs: Operand,
164        op: CmpOp,
165        rhs: Operand,
166    },
167    /// Standalone operand used as a boolean predicate.
168    ///
169    /// Enables `WHERE textMatches(n.bio, 'query')` without requiring an
170    /// explicit comparison.  Truthiness: `Bool(true)` → true, `Bool(false)`
171    /// → false, null → false, any other non-null non-false value → true.
172    Truthy(Operand),
173    /// `operand IS NULL` — true iff the operand evaluates to null.
174    IsNull(Operand),
175    /// `operand IS NOT NULL` — true iff the operand is non-null.
176    IsNotNull(Operand),
177    /// `expr IN [a, b, $p]` or `expr IN $list` (`$list` is `Value::List`).
178    In {
179        expr: Operand,
180        list: Vec<Operand>,
181    },
182}
183
184#[derive(Debug, Clone, PartialEq)]
185pub enum Operand {
186    Prop {
187        var: String,
188        field: String,
189    },
190    Lit(Value),
191    Param(String),
192    /// Bare variable reference (used in `WITH … WHERE alias > 2`).
193    Var(String),
194    /// Scalar function call: `toLower(n.name)`, `size(n.tags)`, `type(r)`, etc.
195    ///
196    /// Supported functions (case-insensitive): `toLower`, `toUpper`, `size`,
197    /// `coalesce`, `type`, `abs`, `round`.  Unknown names → named error at
198    /// execution time listing the supported set.
199    FuncCall {
200        name: String,
201        args: Vec<Operand>,
202    },
203    /// Arithmetic expression inside a function argument: `abs(n.age - 27)`,
204    /// `round(n.score * 1.5)`.  Supports `+`, `-`, `*`, `/`.
205    BinArith {
206        op: ArithOp,
207        left: Box<Operand>,
208        right: Box<Operand>,
209    },
210}
211
212/// Arithmetic operators for `Operand::BinArith`.
213#[derive(Debug, Clone, PartialEq)]
214pub enum ArithOp {
215    Add,
216    Sub,
217    Mul,
218    Div,
219}
220
221/// RETURN item value: bare variable, `var.field`, an aggregate call, a
222/// scalar function call, or an arbitrary scalar expression (arithmetic etc.).
223#[derive(Debug, Clone, PartialEq)]
224pub enum RetVal {
225    Var(String),
226    Prop {
227        var: String,
228        field: String,
229    },
230    /// Single aggregate function call.  When combined with non-aggregate items
231    /// in the same RETURN clause, the planner routes to `GroupAggregate`.
232    /// Multiple aggregate items are also supported via `GroupAggregate`.
233    Agg {
234        func: AggFunc,
235        arg: AggArg,
236    },
237    /// Scalar function call in a RETURN position, e.g. `toLower(n.name)`.
238    /// The same function set as `Operand::FuncCall`.
239    FuncCall {
240        name: String,
241        args: Vec<Operand>,
242    },
243    /// Arbitrary scalar expression in a RETURN/WITH position, e.g. `n.age + 1`.
244    /// Evaluated via `resolve_operand` at execution time; null propagates.
245    ScalarExpr(Operand),
246}
247
248#[derive(Debug, Clone, PartialEq)]
249pub struct RetItem {
250    pub value: RetVal,
251    pub alias: Option<String>,
252}
253
254/// ORDER BY target. Bare identifiers that match a RETURN alias become `Alias`;
255/// otherwise they stay `Var`. `var.field` is always `Prop`.
256#[derive(Debug, Clone, PartialEq)]
257pub enum OrderTarget {
258    Alias(String),
259    Var(String),
260    Prop { var: String, field: String },
261}
262
263#[derive(Debug, Clone, PartialEq)]
264pub struct OrderItem {
265    pub target: OrderTarget,
266    pub descending: bool,
267}
268
269// ─── Write statement AST ──────────────────────────────────────────────────────
270
271/// Top-level write statement (CREATE / MATCH…SET / MATCH…DELETE / MATCH…DETACH DELETE / MERGE).
272/// Produced by `parse_write`; executed by `GraphDb::query_write`.
273#[derive(Debug, Clone, PartialEq)]
274pub enum WriteStatement {
275    Create(CreateStmt),
276    MatchSet(MatchSetStmt),
277    MatchDelete(MatchDeleteStmt),
278    MatchDeleteNode(MatchDeleteNodeStmt),
279    Merge(MergeStmt),
280}
281
282/// `CREATE (a:L {id: 'x', ...})[-[:T]->(b:L2 {id: 'y', ...})] [RETURN …]`
283///
284/// `nodes` is in encounter order. `edges` reference node vars that appear in
285/// `nodes`. Each node must have a string-valued `id` property (used as key).
286///
287/// `returns`, when `Some`, projects the created bindings as a read result.
288/// The write and the projection are committed as a single WAL batch frame.
289#[derive(Debug, Clone, PartialEq)]
290pub struct CreateStmt {
291    pub nodes: Vec<CreateNode>,
292    pub edges: Vec<CreateEdge>,
293    /// Optional RETURN clause: project created bindings after commit.
294    pub returns: Option<Vec<RetItem>>,
295}
296
297/// One node in a CREATE pattern.
298#[derive(Debug, Clone, PartialEq)]
299pub struct CreateNode {
300    /// Optional binding variable (`a` in `(a:Label {…})`).
301    pub var: Option<String>,
302    pub label: String,
303    /// Literal property pairs.  Must include a string-valued `id` field.
304    pub props: Vec<(String, core_storage::Value)>,
305}
306
307/// One edge in a CREATE pattern, referencing vars from `CreateStmt.nodes`.
308#[derive(Debug, Clone, PartialEq)]
309pub struct CreateEdge {
310    pub src_var: String,
311    pub etype: String,
312    pub dst_var: String,
313}
314
315/// `MATCH patterns [WHERE expr] SET var.field = literal [, …] [RETURN …]`
316#[derive(Debug, Clone, PartialEq)]
317pub struct MatchSetStmt {
318    pub matches: Vec<Pattern>,
319    pub where_expr: Option<Expr>,
320    pub sets: Vec<SetClause>,
321    /// Optional RETURN clause: project matched bindings from post-write state.
322    pub returns: Option<Vec<RetItem>>,
323}
324
325/// One `var.field = literal_or_param` assignment in a SET clause.
326///
327/// `value` is an `Operand` rather than a bare `Value` so that `$param`
328/// references are legal on the RHS (resolved at execution time from the
329/// query's parameter map).  Only `Operand::Lit` and `Operand::Param` are
330/// accepted by the parser; other variants produce a named parse error.
331#[derive(Debug, Clone, PartialEq)]
332pub struct SetClause {
333    pub var: String,
334    pub field: String,
335    pub value: Operand,
336}
337
338/// `MATCH patterns [WHERE expr] DELETE rel_var [, …]`
339///
340/// Each `EdgeDelete` carries the etype, src node var, and dst node var resolved
341/// from the MATCH patterns at parse time so the executor can emit a read query
342/// returning node keys without extra pattern-scanning.
343#[derive(Debug, Clone, PartialEq)]
344pub struct MatchDeleteStmt {
345    pub matches: Vec<Pattern>,
346    pub where_expr: Option<Expr>,
347    pub deletes: Vec<EdgeDelete>,
348}
349
350/// One edge variable to delete, with resolved topology.
351#[derive(Debug, Clone, PartialEq)]
352pub struct EdgeDelete {
353    pub rel_var: String,
354    pub etype: String,
355    pub src_var: String,
356    pub dst_var: String,
357}
358
359/// `MATCH patterns [WHERE expr] [DETACH] DELETE node_var [, …]`
360///
361/// When `detach` is `true` (DETACH DELETE), all incident edges are removed
362/// before the node is tombstoned (openCypher semantics).  When `false`
363/// (bare DELETE), the node must have no incident edges; the executor returns
364/// an error if any remain.
365#[derive(Debug, Clone, PartialEq)]
366pub struct MatchDeleteNodeStmt {
367    pub matches: Vec<Pattern>,
368    pub where_expr: Option<Expr>,
369    /// Node variable names whose nodes are to be deleted (resolved from MATCH patterns).
370    pub node_vars: Vec<String>,
371    /// `true` → DETACH DELETE (allowed regardless of edges).
372    /// `false` → bare DELETE (error if any edges touch the node).
373    pub detach: bool,
374}
375
376/// `MERGE (n:Label {id: 'x'}) [ON CREATE SET …] [ON MATCH SET …] [RETURN …]`
377///
378/// Exactly one property is allowed (the key). More properties → named error.
379/// `ON CREATE SET` / `ON MATCH SET` apply inside the same write batch as the
380/// insert-or-skip. `returns`, when `Some`, projects the node after commit.
381#[derive(Debug, Clone, PartialEq)]
382pub struct MergeStmt {
383    pub label: String,
384    /// The single property that identifies the node. Value must be a string.
385    pub key_field: String,
386    pub key_value: core_storage::Value,
387    /// Optional bound variable for the MERGE node (for RETURN projection).
388    pub var: Option<String>,
389    /// `ON CREATE SET` assignments, applied only when the node is inserted.
390    pub on_create: Vec<SetClause>,
391    /// `ON MATCH SET` assignments, applied only when the node already exists.
392    pub on_match: Vec<SetClause>,
393    /// Optional RETURN clause: project the node after commit.
394    pub returns: Option<Vec<RetItem>>,
395}