graphdblite 0.1.2

Embedded graph database with Cypher support. SQLite-grade simplicity, graph-native performance.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
use std::collections::HashMap;

use crate::types::Span;

/// Top-level Cypher statement.
#[derive(Debug, Clone, PartialEq)]
pub enum Statement {
    Match(MatchStatement),
    Create(CreateStatement),
    MatchCreate(MatchCreateStatement),
    MatchMerge(MatchMergeStatement),
    Delete(DeleteStatement),
    Set(SetStatement),
    Remove(RemoveStatement),
    Merge(MergeStatement),
    Unwind(UnwindStatement),
    /// Standalone RETURN (no preceding MATCH / CREATE).
    Return(ReturnStatement),
    /// Multi-clause statement: arbitrary sequences of MATCH/CREATE/MERGE/WITH/UNWIND/SET/REMOVE/DELETE.
    MultiClause(MultiClauseStatement),
    Explain(Box<Statement>),
    /// UNION [ALL] of multiple statements.
    Union {
        statements: Vec<Statement>,
        /// true = UNION ALL (keep duplicates), false = UNION (deduplicate).
        all: bool,
    },
    /// CREATE INDEX ON :Label(prop1, prop2, ...)
    CreateIndex {
        label: String,
        properties: Vec<String>,
    },
    /// DROP INDEX ON :Label(prop1, prop2, ...)
    DropIndex {
        label: String,
        properties: Vec<String>,
    },
    /// CALL procedure statement.
    Call {
        procedure_name: String,
        /// Explicit arguments: `CALL proc(expr1, expr2)`. Empty if no parens (implicit args).
        args: Vec<Expr>,
        /// True when called without parentheses: `CALL proc` (implicit argument passing).
        implicit_args: bool,
        /// YIELD items: `YIELD col1 AS alias1, col2`. None = no YIELD clause.
        /// Each entry is (output_column, optional_alias).
        yield_items: Option<Vec<(String, Option<String>)>>,
        /// True when YIELD * is used instead of named columns.
        yield_star: bool,
        /// Optional RETURN clause for in-query CALL: `CALL proc() YIELD x RETURN x`.
        return_clause: Option<ReturnClause>,
        /// ORDER BY for the RETURN clause.
        order_by: Vec<SortItem>,
        /// SKIP expression.
        skip: Option<Box<Expr>>,
        /// LIMIT expression.
        limit: Option<Box<Expr>>,
    },
}

/// A clause in a multi-clause statement.
//
// Variant sizes vary by ~hundreds of bytes (Match holds Vec<Pattern> +
// Vec<OptionalMatch>; Create holds only Vec<Pattern>). Boxing the heavy
// variants would touch every match arm in the planner for ~zero runtime
// benefit — there's only ever a handful of clauses per parsed query.
#[allow(clippy::large_enum_variant)]
#[derive(Debug, Clone, PartialEq)]
pub enum Clause {
    Match {
        patterns: Vec<Pattern>,
        optional_patterns: Vec<OptionalMatch>,
        where_clause: Option<Expr>,
    },
    Create {
        patterns: Vec<Pattern>,
    },
    Merge {
        pattern: Pattern,
        on_create: Vec<SetItem>,
        on_match: Vec<SetItem>,
    },
    With(WithClause),
    Unwind(UnwindClause),
    Set {
        items: Vec<SetItem>,
    },
    Remove {
        items: Vec<RemoveItem>,
    },
    Call {
        procedure_name: String,
        args: Vec<Expr>,
        implicit_args: bool,
        yield_items: Option<Vec<(String, Option<String>)>>,
        yield_star: bool,
    },
    Delete {
        exprs: Vec<Expr>,
        detach: bool,
    },
}

/// Multi-clause statement: a sequence of arbitrary clauses with optional RETURN.
#[derive(Debug, Clone, PartialEq)]
pub struct MultiClauseStatement {
    pub clauses: Vec<Clause>,
    pub return_clause: Option<ReturnClause>,
    pub order_by: Vec<SortItem>,
    pub skip: Option<Expr>,
    pub limit: Option<Expr>,
}

/// Standalone `RETURN expr [AS alias], ... [ORDER BY ...] [SKIP n] [LIMIT n]`
#[derive(Debug, Clone, PartialEq)]
pub struct ReturnStatement {
    pub return_clause: ReturnClause,
    pub order_by: Vec<SortItem>,
    pub skip: Option<Expr>,
    pub limit: Option<Expr>,
}

/// An OPTIONAL MATCH clause with its patterns and optional WHERE filter.
#[derive(Debug, Clone, PartialEq)]
pub struct OptionalMatch {
    pub patterns: Vec<Pattern>,
    pub where_clause: Option<Expr>,
}

/// MATCH ... WHERE ... WITH ... RETURN ... ORDER BY ... LIMIT
#[derive(Debug, Clone, PartialEq)]
pub struct MatchStatement {
    pub patterns: Vec<Pattern>,
    pub optional_patterns: Vec<OptionalMatch>,
    pub where_clause: Option<Expr>,
    pub intermediate_clauses: Vec<IntermediateClause>,
    pub return_clause: ReturnClause,
    pub order_by: Vec<SortItem>,
    pub skip: Option<Expr>,
    pub limit: Option<Expr>,
}

/// WITH clause: intermediate projection/filter/aggregation.
#[derive(Debug, Clone, PartialEq)]
pub struct WithClause {
    pub items: Vec<ReturnItem>,
    pub distinct: bool,
    pub order_by: Vec<SortItem>,
    pub skip: Option<Expr>,
    pub limit: Option<Expr>,
    pub where_clause: Option<Expr>,
}

/// CREATE (n:Label {props})-[:TYPE]->(m:Label) [RETURN ...]
#[derive(Debug, Clone, PartialEq)]
pub struct CreateStatement {
    pub patterns: Vec<Pattern>,
    pub return_clause: Option<ReturnClause>,
    pub order_by: Vec<SortItem>,
    pub skip: Option<Expr>,
    pub limit: Option<Expr>,
}

/// MATCH ... CREATE (a)-[:TYPE]->(b) [RETURN ...]
#[derive(Debug, Clone, PartialEq)]
pub struct MatchCreateStatement {
    pub patterns: Vec<Pattern>,
    pub where_clause: Option<Expr>,
    pub create_patterns: Vec<Pattern>,
    pub return_clause: Option<ReturnClause>,
    pub order_by: Vec<SortItem>,
    pub skip: Option<Expr>,
    pub limit: Option<Expr>,
}

/// MATCH ... [DETACH] DELETE n, m [RETURN ...]
#[derive(Debug, Clone, PartialEq)]
pub struct DeleteStatement {
    pub patterns: Vec<Pattern>,
    pub optional_patterns: Vec<OptionalMatch>,
    pub where_clause: Option<Expr>,
    pub detach: bool,
    pub exprs: Vec<Expr>,
    pub return_clause: Option<ReturnClause>,
    pub order_by: Vec<SortItem>,
    pub skip: Option<Expr>,
    pub limit: Option<Expr>,
}

/// MATCH ... SET n.prop = value | n:Label | n = {map} | n += {map} [WITH ...] [RETURN ...]
#[derive(Debug, Clone, PartialEq)]
pub struct SetStatement {
    pub patterns: Vec<Pattern>,
    pub optional_patterns: Vec<OptionalMatch>,
    pub where_clause: Option<Expr>,
    pub items: Vec<SetItem>,
    pub intermediate_clauses: Vec<IntermediateClause>,
    pub return_clause: Option<ReturnClause>,
    pub order_by: Vec<SortItem>,
    pub skip: Option<Expr>,
    pub limit: Option<Expr>,
}

/// A single SET clause item.
#[derive(Debug, Clone, PartialEq)]
pub enum SetItem {
    Property(Assignment),
    Label {
        variable: String,
        labels: Vec<String>,
    },
    MapOverwrite {
        variable: String,
        value: Expr,
    },
    MapMerge {
        variable: String,
        value: Expr,
    },
}

/// MATCH ... REMOVE n.prop, n:Label [RETURN ...]
#[derive(Debug, Clone, PartialEq)]
pub struct RemoveStatement {
    pub patterns: Vec<Pattern>,
    pub optional_patterns: Vec<OptionalMatch>,
    pub where_clause: Option<Expr>,
    pub items: Vec<RemoveItem>,
    pub return_clause: Option<ReturnClause>,
    pub order_by: Vec<SortItem>,
    pub skip: Option<Expr>,
    pub limit: Option<Expr>,
}

/// An item to remove: property or label(s).
#[derive(Debug, Clone, PartialEq)]
pub enum RemoveItem {
    Property {
        variable: String,
        property: String,
    },
    Label {
        variable: String,
        labels: Vec<String>,
    },
}

/// MATCH ... MERGE pattern ON CREATE SET ... ON MATCH SET ... [RETURN ...]
#[derive(Debug, Clone, PartialEq)]
pub struct MatchMergeStatement {
    pub patterns: Vec<Pattern>,
    pub where_clause: Option<Expr>,
    pub merge_pattern: Pattern,
    pub on_create: Vec<SetItem>,
    pub on_match: Vec<SetItem>,
    pub return_clause: Option<ReturnClause>,
    pub order_by: Vec<SortItem>,
    pub skip: Option<Expr>,
    pub limit: Option<Expr>,
}

/// MERGE (n:Label {props}) ON CREATE SET ... ON MATCH SET ... [RETURN ...]
#[derive(Debug, Clone, PartialEq)]
pub struct MergeStatement {
    pub pattern: Pattern,
    pub on_create: Vec<SetItem>,
    pub on_match: Vec<SetItem>,
    pub return_clause: Option<ReturnClause>,
    pub order_by: Vec<SortItem>,
    pub skip: Option<Expr>,
    pub limit: Option<Expr>,
}

/// UNWIND expr AS alias [WHERE ...] RETURN ... / CREATE ...
#[derive(Debug, Clone, PartialEq)]
pub struct UnwindStatement {
    pub expr: Expr,
    pub alias: String,
    pub body: UnwindBody,
}

/// What follows the UNWIND clause.
#[derive(Debug, Clone, PartialEq)]
pub enum UnwindBody {
    Return {
        where_clause: Option<Expr>,
        intermediate_clauses: Vec<IntermediateClause>,
        return_clause: ReturnClause,
        order_by: Vec<SortItem>,
        skip: Option<Expr>,
        limit: Option<Expr>,
    },
    Create {
        patterns: Vec<Pattern>,
        intermediate_clauses: Vec<IntermediateClause>,
        return_clause: Option<ReturnClause>,
        order_by: Vec<SortItem>,
        skip: Option<Expr>,
        limit: Option<Expr>,
    },
}

/// Intermediate clause (WITH, UNWIND, or MATCH) within a MATCH statement.
//
// WithClause is much larger than UnwindClause; same rationale as `Clause` —
// not worth boxing for an AST that lives briefly per query.
#[allow(clippy::large_enum_variant)]
#[derive(Debug, Clone, PartialEq)]
pub enum IntermediateClause {
    With(WithClause),
    Unwind(UnwindClause),
    Match(IntermediateMatch),
}

/// MATCH/OPTIONAL MATCH clause appearing after a WITH.
#[derive(Debug, Clone, PartialEq)]
pub struct IntermediateMatch {
    pub patterns: Vec<Pattern>,
    pub optional_patterns: Vec<OptionalMatch>,
    pub where_clause: Option<Expr>,
}

/// UNWIND clause within a MATCH statement.
#[derive(Debug, Clone, PartialEq)]
pub struct UnwindClause {
    pub expr: Expr,
    pub alias: String,
}

/// Whether a pattern is wrapped in shortestPath / allShortestPaths.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ShortestPathMode {
    None,
    Single,
    All,
}

/// A graph pattern: sequence of node and relationship elements,
/// with optional path variable binding and shortest path mode.
#[derive(Debug, Clone, PartialEq)]
pub struct Pattern {
    pub elements: Vec<PatternElement>,
    pub path_variable: Option<String>,
    pub shortest_path_mode: ShortestPathMode,
}

#[derive(Debug, Clone, PartialEq)]
pub enum PatternElement {
    Node(NodePattern),
    Relationship(RelPattern),
}

#[derive(Debug, Clone, PartialEq)]
pub struct NodePattern {
    pub variable: Option<String>,
    pub labels: Vec<String>,
    pub properties: HashMap<String, Expr>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct RelPattern {
    pub variable: Option<String>,
    pub rel_types: Vec<String>,
    pub properties: HashMap<String, Expr>,
    pub direction: RelDirection,
    pub var_length: Option<(u32, u32)>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RelDirection {
    Outgoing,   // -[]->)
    Incoming,   // <-[]-
    Undirected, // -[]-
}

/// RETURN clause with optional ORDER BY and LIMIT.
#[derive(Debug, Clone, PartialEq)]
pub struct ReturnClause {
    pub items: Vec<ReturnItem>,
    pub distinct: bool,
}

#[derive(Debug, Clone, PartialEq)]
pub struct ReturnItem {
    pub expr: Expr,
    pub alias: Option<String>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct SortItem {
    pub expr: Expr,
    pub descending: bool,
}

/// Property assignment: n.prop = value
#[derive(Debug, Clone, PartialEq)]
pub struct Assignment {
    pub variable: String,
    pub property: String,
    pub value: Expr,
}

/// Expression AST node — wraps a kind with its source span.
///
/// The span identifies where this expression came from in the original query
/// text. Synthesized expressions (e.g. planner rewrites) use `Span::synthetic()`.
///
/// Equality compares only `kind` — span is metadata and must not affect
/// AST equality (the planner relies on structural equality to dedupe
/// expressions across rewrites with different spans).
#[derive(Debug, Clone)]
pub struct Expr {
    pub kind: ExprKind,
    pub span: Span,
}

impl PartialEq for Expr {
    fn eq(&self, other: &Self) -> bool {
        self.kind == other.kind
    }
}

impl Expr {
    /// Construct an expression with an explicit source span.
    pub fn new(kind: ExprKind, span: Span) -> Self {
        Self { kind, span }
    }

    /// Construct an expression with no source location (planner-synthesized).
    pub fn synthetic(kind: ExprKind) -> Self {
        Self {
            kind,
            span: Span::synthetic(),
        }
    }
}

/// Discriminant for expression AST nodes — see `Expr` for the spanned wrapper.
#[derive(Debug, Clone, PartialEq)]
pub enum ExprKind {
    /// Literal value (string, int, float, bool, null).
    Literal(LiteralValue),
    /// Property access: variable.property
    Property(String, String),
    /// Variable reference.
    Variable(String),
    /// Parameter reference: $name
    Parameter(String),
    /// Binary operation: left op right
    BinaryOp {
        left: Box<Expr>,
        op: BinOp,
        right: Box<Expr>,
    },
    /// Unary NOT.
    Not(Box<Expr>),
    /// IS NULL check.
    IsNull(Box<Expr>),
    /// IS NOT NULL check.
    IsNotNull(Box<Expr>),
    /// Function call: name(args)
    FunctionCall {
        name: String,
        args: Vec<Expr>,
        distinct: bool,
        /// Original source text for column naming (preserves whitespace/case).
        original_text: Option<String>,
    },
    /// CASE [operand] WHEN cond THEN result ... ELSE default END
    Case {
        operand: Option<Box<Expr>>,
        alternatives: Vec<(Box<Expr>, Box<Expr>)>,
        default: Option<Box<Expr>>,
    },
    /// List literal: [expr, expr, ...]
    List(Vec<Expr>),
    /// List comprehension: [x IN list WHERE pred | expr]
    ListComprehension {
        variable: String,
        list_expr: Box<Expr>,
        filter: Option<Box<Expr>>,
        map_expr: Option<Box<Expr>>,
    },
    /// Pattern comprehension: [(p = )? pattern (WHERE pred)? | expr]
    PatternComprehension {
        path_variable: Option<String>,
        pattern: Pattern,
        where_clause: Option<Box<Expr>>,
        map_expr: Box<Expr>,
    },
    /// EXISTS { pattern [WHERE expr] } subquery predicate.
    Exists {
        patterns: Vec<Pattern>,
        where_clause: Option<Box<Expr>>,
    },
    /// EXISTS { MATCH ... [WITH ...] RETURN ... } full existential subquery.
    ExistsSubquery(Box<Statement>),
    /// Map literal: {key: expr, key2: expr2, ...}. Keys are preserved in
    /// source order for error messages; evaluation sorts them into a
    /// BTreeMap.
    MapLiteral(Vec<(String, Expr)>),
    /// List index: expr[index]
    Index { expr: Box<Expr>, index: Box<Expr> },
    /// Chained property access: expr.key (for m.a.b patterns)
    DotAccess { expr: Box<Expr>, key: String },
    /// List slice: expr[start..end] (either bound may be None)
    Slice {
        expr: Box<Expr>,
        start: Option<Box<Expr>>,
        end: Option<Box<Expr>>,
    },
    /// Quantifier predicate: none/single/any/all(x IN list WHERE pred)
    Quantifier {
        kind: QuantifierKind,
        variable: String,
        list_expr: Box<Expr>,
        predicate: Box<Expr>,
    },
    /// Label predicate: n:Label (true if node has all specified labels).
    HasLabel(String, Vec<String>),
    /// Pattern predicate: (n)-[:REL]->(m) — true if the pattern matches.
    /// Used in WHERE clauses for existential checks.
    PatternPredicate(Pattern),
    /// Wildcard * (used in count(*) and RETURN *)
    Star,
}

/// Quantifier predicate kind.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum QuantifierKind {
    None,
    Single,
    Any,
    All,
}

#[derive(Debug, Clone, PartialEq)]
pub enum LiteralValue {
    Null,
    Bool(bool),
    I64(i64),
    F64(f64),
    String(String),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BinOp {
    Eq,
    Neq,
    Lt,
    Gt,
    Lte,
    Gte,
    And,
    Or,
    Xor,
    StartsWith,
    EndsWith,
    Contains,
    RegexMatch,
    In,
    Add,
    Sub,
    Mul,
    Div,
    Mod,
    Pow,
}