akar-parser 0.1.21

Cypher parser for the Akar embedded graph database
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
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
//! Abstract Syntax Tree (AST) types for Cypher queries.

/// EXPLAIN type — what kind of plan to show.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ExplainType {
    /// `EXPLAIN` — show the physical plan (default).
    PhysicalPlan,
    /// `EXPLAIN LOGICAL` — show the logical plan.
    LogicalPlan,
    /// `EXPLAIN PROFILE` — execute and show profile.
    Profile,
}

/// EXPORT DATABASE statement.
#[derive(Debug, Clone, PartialEq)]
pub struct ExportDatabase {
    /// Path to the export directory.
    pub file_path: String,
    /// Export options (format, schema_only, etc.).
    pub options: std::collections::HashMap<String, String>,
}

/// IMPORT DATABASE statement.
#[derive(Debug, Clone, PartialEq)]
pub struct ImportDatabase {
    /// Path to the import directory (previously exported).
    pub file_path: String,
    /// Import options (format, etc.) — accepted for Kuzu syntax parity.
    pub options: std::collections::HashMap<String, String>,
}

/// ANALYZE statement — collect table statistics.
#[derive(Debug, Clone, PartialEq)]
pub struct AnalyzeStatement {
    /// Table name to analyze, or None for all tables (ANALYZE *).
    pub table_name: Option<String>,
}

/// Transaction action type.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum TransactionAction {
    Begin,
    Commit,
    Rollback,
    Checkpoint,
}

/// TRANSACTION statement (BEGIN, COMMIT, ROLLBACK, CHECKPOINT).
#[derive(Debug, Clone, PartialEq)]
pub struct TransactionStatement {
    pub action: TransactionAction,
}

/// Extension management action.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ExtensionAction {
    Install,
    Load,
    Uninstall,
}

/// EXTENSION management statement (INSTALL/LOAD/UNINSTALL EXTENSION name).
#[derive(Debug, Clone, PartialEq)]
pub struct ExtensionStatement {
    pub action: ExtensionAction,
    pub name: String,
}

/// ATTACH DATABASE statement.
#[derive(Debug, Clone, PartialEq)]
pub struct AttachDatabase {
    pub path: String,
    pub alias: String,
    pub options: std::collections::HashMap<String, String>,
}

/// DETACH DATABASE statement.
#[derive(Debug, Clone, PartialEq)]
pub struct DetachDatabase {
    pub alias: String,
}

/// USE DATABASE statement.
#[derive(Debug, Clone, PartialEq)]
pub struct UseDatabase {
    pub alias: String,
}

/// LOAD FROM statement — scan external file without importing.
#[derive(Debug, Clone, PartialEq)]
pub struct LoadFrom {
    pub path: String,
    pub options: std::collections::HashMap<String, String>,
}

/// EXPLAIN statement wrapper.
#[derive(Debug, Clone, PartialEq)]
pub struct ExplainStatement {
    /// The statement being explained.
    pub statement: Box<Statement>,
    /// The type of explain output.
    pub explain_type: ExplainType,
}

/// A Cypher statement (top-level AST node).
#[derive(Debug, Clone, PartialEq)]
pub enum Statement {
    Query(Query),
    CreateNodeTable(CreateNodeTable),
    CreateRelTable(CreateRelTable),
    DropTable(DropTable),
    CopyFrom(CopyFrom),
    CopyTo(CopyTo),
    AlterTable(AlterTable),
    CreateVectorIndex(CreateVectorIndex),
    CreateIndex(CreateIndex),
    DropIndex(DropIndex),
    Union(UnionStatement),
    Merge(MergeStatement),
    StandaloneCall(StandaloneCall),
    CreateDml(CreateClause),
    Explain(ExplainStatement),
    CreateSequence(CreateSequence),
    DropSequence(DropSequence),
    CreateMacro(CreateMacro),
    ExportDatabase(ExportDatabase),
    ImportDatabase(ImportDatabase),
    Analyze(AnalyzeStatement),
    CreateFtsIndex(CreateFtsIndex),
    Transaction(TransactionStatement),
    Extension(ExtensionStatement),
    AttachDatabase(AttachDatabase),
    DetachDatabase(DetachDatabase),
    UseDatabase(UseDatabase),
    LoadFrom(LoadFrom),
    CreateType(CreateType),
    CommentOnTable(CommentOnTable),
    CreateGraph(CreateGraph),
    UseGraph(UseGraph),
    DropGraph(DropGraph),
}

/// A Cypher query (e.g., MATCH ... RETURN ...).
#[derive(Debug, Clone, PartialEq)]
pub struct Query {
    pub clauses: Vec<Clause>,
}

/// A clause in a query.
#[derive(Debug, Clone, PartialEq)]
pub enum Clause {
    Match(MatchClause),
    Return(ReturnClause),
    Where(WhereClause),
    Create(CreateClause),
    Delete(DeleteClause),
    Set(SetClause),
    OptionalMatch(OptionalMatchClause),
    With(ReturnClause),
    Unwind(UnwindClause),
    Foreach(ForeachClause),
    Merge(MergeStatement),
}

#[derive(Debug, Clone, PartialEq)]
pub struct ForeachClause {
    pub variable: String,
    pub expression: Expression,
    /// Sub-statements inside FOREACH (CREATE, SET, DELETE clauses).
    pub clauses: Vec<Clause>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct UnwindClause {
    pub expression: Expression,
    pub variable: String,
}

#[derive(Debug, Clone, PartialEq)]
pub struct SetClause {
    pub items: Vec<SetItem>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct SetItem {
    pub property: Expression,
    pub value: Expression,
}

#[derive(Debug, Clone, PartialEq)]
pub struct DeleteClause {
    pub detach: bool,
    pub expressions: Vec<Expression>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct MatchClause {
    pub patterns: Vec<Pattern>,
    /// Optional FTS query attached to this MATCH via `USING FTS INDEX name('query')`.
    pub fts_query: Option<FtsQuery>,
}

/// A `USING FTS INDEX index_name('search string')` clause attached to a MATCH.
#[derive(Debug, Clone, PartialEq)]
pub struct FtsQuery {
    pub index_name: String,
    pub query_string: String,
}

/// CREATE FTS INDEX statement.
#[derive(Debug, Clone, PartialEq)]
pub struct CreateFtsIndex {
    pub index_name: String,
    pub table_name: String,
    pub column_name: String,
    pub if_not_exists: bool,
}

#[derive(Debug, Clone, PartialEq)]
pub struct OptionalMatchClause {
    pub patterns: Vec<Pattern>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct ReturnClause {
    pub expressions: Vec<ReturnItem>,
    pub distinct: bool,
    /// Optional ORDER BY clause: list of sort items.
    pub order_by: Option<Vec<OrderByItem>>,
    /// Optional LIMIT — maximum number of rows to return.
    pub limit: Option<u64>,
    /// Optional SKIP — number of rows to skip before returning.
    pub skip: Option<u64>,
    /// Parameter name (e.g. `$limit`) referenced by LIMIT, resolved to a value
    /// at prepare/execution time. Mutually exclusive with `limit`.
    pub limit_param: Option<String>,
    /// Parameter name (e.g. `$skip`) referenced by SKIP, resolved to a value
    /// at prepare/execution time. Mutually exclusive with `skip`.
    pub skip_param: Option<String>,
}

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

/// A single sort item in an ORDER BY clause.
#[derive(Debug, Clone, PartialEq)]
pub struct OrderByItem {
    /// The expression to sort by.
    pub expression: Expression,
    /// Sort direction: `true` for ascending (default), `false` for descending.
    pub ascending: bool,
}

#[derive(Debug, Clone, PartialEq)]
pub struct WhereClause {
    pub expression: Expression,
}

#[derive(Debug, Clone, PartialEq)]
pub struct CreateClause {
    pub patterns: Vec<Pattern>,
}

/// A graph pattern (node or relationship).
#[derive(Debug, Clone, PartialEq)]
pub struct Pattern {
    pub node: Option<NodePattern>,
    pub edge: Option<EdgePattern>,
}

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

#[derive(Debug, Clone, PartialEq)]
pub struct EdgePattern {
    pub variable: Option<String>,
    pub labels: Vec<String>,
    pub direction: EdgeDirection,
    pub properties: Vec<(String, Expression)>,
    pub lower_bound: Option<u64>,
    pub upper_bound: Option<u64>,
}

#[derive(Debug, Clone, PartialEq)]
pub enum EdgeDirection {
    LeftToRight,
    RightToLeft,
    Both,
}

impl ExplainStatement {
    /// Create a new EXPLAIN statement wrapping the given inner statement.
    pub fn new(statement: Statement, explain_type: ExplainType) -> Self {
        Self {
            statement: Box::new(statement),
            explain_type,
        }
    }
}

/// An expression in a Cypher query.
#[derive(Debug, Clone, PartialEq)]
pub enum Expression {
    Constant(Constant),
    Variable(String),
    /// A query parameter reference like `$name` or `$age`.
    Parameter(String),
    PropertyAccess(Box<Expression>, String),
    FunctionCall(String, Vec<Expression>),
    BinaryOp(BinaryOp, Box<Expression>, Box<Expression>),
    UnaryOp(UnaryOp, Box<Expression>),
    List(Vec<Expression>),
    Map(Vec<(String, Expression)>),
    /// EXISTS { MATCH ... WHERE ... } — returns true if the pattern matches.
    ExistsSubquery(Box<Query>),
    /// CASE [subject] WHEN ... THEN ... [ELSE ...] END
    Case(CaseExpr),
    /// STAR expression — represents `*` in `RETURN *`.
    /// The binder expands this to all variables in scope.
    Star,
    /// ANY/ALL/NONE/SINGLE list predicates.
    /// Example: ANY(x IN [1,2,3] WHERE x > 5)
    ListPredicate {
        quantifier: Quantifier,
        list: Box<Expression>,
        var_name: String,
        predicate: Box<Expression>,
    },
    /// Lambda expression for list_transform, list_filter, list_reduce.
    /// Example: x -> x + 1  or  (x, y) -> x + y
    Lambda {
        var_name: String,
        body: Box<Expression>,
    },
}

/// Quantifier for list predicates.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Quantifier {
    Any,
    All,
    None,
    Single,
}

/// A single WHEN ... THEN ... branch inside a CASE expression.
#[derive(Debug, Clone, PartialEq)]
pub struct CaseAlternative {
    /// The WHEN expression (a value for simple CASE, or a condition for searched CASE).
    pub when: Expression,
    /// The THEN expression returned when WHEN matches.
    pub then: Expression,
}

/// A CASE expression (simple or searched).
#[derive(Debug, Clone, PartialEq)]
pub struct CaseExpr {
    /// Optional subject expression for simple CASE: `CASE x WHEN v THEN ...`
    pub subject: Option<Box<Expression>>,
    /// The WHEN/THEN branches.
    pub alternatives: Vec<CaseAlternative>,
    /// Optional ELSE expression returned when no branch matches.
    pub else_expr: Option<Box<Expression>>,
}

#[derive(Debug, Clone, PartialEq)]
pub enum Constant {
    Null,
    Bool(bool),
    Integer(i64),
    Float(f64),
    String(String),
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum BinaryOp {
    Add,
    Subtract,
    Multiply,
    Divide,
    Modulo,
    Equal,
    NotEqual,
    LessThan,
    LessThanOrEqual,
    GreaterThan,
    GreaterThanOrEqual,
    And,
    Or,
    Xor,
    Concat,
    /// x IN [list] — true if x equals any element of the list
    In,
    /// x NOT IN [list] — true if x equals no element of the list
    NotIn,
    /// x STARTS WITH prefix — true if string x starts with prefix
    StartsWith,
    /// x ENDS WITH suffix — true if string x ends with suffix
    EndsWith,
    /// x CONTAINS substr — true if string x contains substr
    Contains,
    /// x LIKE pattern — true if string x matches the SQL LIKE pattern
    Like,
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum UnaryOp {
    Not,
    Negate,
    /// x IS NULL — true if x evaluates to null
    IsNull,
    /// x IS NOT NULL — true if x does not evaluate to null
    IsNotNull,
}

// DDL statements
#[derive(Debug, Clone, PartialEq)]
pub struct CreateNodeTable {
    pub name: String,
    pub columns: Vec<ColumnDef>,
    pub primary_key: String,
    pub if_not_exists: bool,
}

#[derive(Debug, Clone, PartialEq)]
pub struct CreateRelTable {
    pub name: String,
    pub from: String,
    pub to: String,
    pub columns: Vec<ColumnDef>,
    pub if_not_exists: bool,
}

#[derive(Debug, Clone, PartialEq)]
pub struct DropTable {
    pub name: String,
}

/// A `CREATE [ART|HASH] INDEX` statement.
#[derive(Debug, Clone, PartialEq)]
pub struct CreateIndex {
    pub index_type: String,
    pub index_name: String,
    pub table_name: String,
    pub variable: String,
    pub property: String,
    pub conflict_action: Option<String>,
}

/// A `DROP INDEX` statement.
#[derive(Debug, Clone, PartialEq)]
pub struct DropIndex {
    pub index_name: String,
    pub table_name: String,
}

/// ALTER TABLE statement.
#[derive(Debug, Clone, PartialEq)]
pub struct AlterTable {
    pub table_name: String,
    pub action: AlterAction,
}

#[derive(Debug, Clone, PartialEq)]
pub enum AlterAction {
    AddColumn { name: String, type_name: String },
    DropColumn { name: String },
    RenameColumn { old_name: String, new_name: String },
    RenameTable { new_name: String },
}

/// UNION statement — combines results from two queries.
#[derive(Debug, Clone, PartialEq)]
pub struct UnionStatement {
    pub left: Query,
    pub right: Query,
    pub all: bool,
}

/// COPY FROM statement — load data from a file into a table.
#[derive(Debug, Clone, PartialEq)]
pub struct CopyFrom {
    pub table_name: String,
    pub file_path: String,
    pub options: std::collections::HashMap<String, String>,
}

/// COPY TO statement — export query results to a file.
///
/// Syntax: `COPY (query) TO 'path' (FORMAT 'CSV'|'PARQUET', HEADER true|false)`
#[derive(Debug, Clone, PartialEq)]
pub struct CopyTo {
    pub query: Query,
    pub file_path: String,
    pub format: CopyToFormat,
    pub header: bool,
}

#[derive(Debug, Clone, PartialEq)]
pub enum CopyToFormat {
    Csv,
    Parquet,
}

/// MERGE statement — match or create a pattern with optional ON CREATE / ON MATCH actions.
#[derive(Debug, Clone, PartialEq)]
pub struct MergeStatement {
    pub patterns: Vec<Pattern>,
    pub on_create: Vec<SetItem>,
    pub on_match: Vec<SetItem>,
}

/// CALL statement — invoke a table function or procedure as a standalone statement.
#[derive(Debug, Clone, PartialEq)]
pub struct StandaloneCall {
    pub function_name: String,
    pub args: Vec<Expression>,
}

/// CREATE SEQUENCE statement — creates a sequence for auto-incrementing counters.
///
/// Syntax:
/// ```sql
/// CREATE [OR REPLACE] SEQUENCE [IF NOT EXISTS] name
///   [START WITH value]
///   [INCREMENT [BY] value]
///   [MINVALUE value | NO MINVALUE]
///   [MAXVALUE value | NO MAXVALUE]
///   [CYCLE | NO CYCLE]
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct CreateSequence {
    pub name: String,
    pub if_not_exists: bool,
    pub or_replace: bool,
    /// START WITH value. Default: 1 for increment > 0, max_value for increment < 0.
    pub start_with: Option<i64>,
    /// INCREMENT BY value. Default: 1.
    pub increment: Option<i64>,
    /// MINVALUE. Auto-computed from defaults if None.
    pub min_value: Option<i64>,
    /// MAXVALUE. Auto-computed from defaults if None.
    pub max_value: Option<i64>,
    /// CYCLE behavior. Default: false (NO CYCLE).
    pub cycle: Option<bool>,
}

/// DROP SEQUENCE statement.
#[derive(Debug, Clone, PartialEq)]
pub struct DropSequence {
    pub name: String,
    pub if_exists: bool,
}

/// CREATE MACRO statement — defines a Cypher scalar macro.
///
/// Syntax: `CREATE MACRO macroName(param1, param2, ...) AS expression`
///
/// Macros are expanded at binding time: macro invocations are replaced
/// with the macro body expression (with parameters substituted).
///
/// Ported from C++ `parser/create_macro.h`.
#[derive(Debug, Clone, PartialEq)]
pub struct CreateMacro {
    /// The macro name.
    pub name: String,
    /// Positional parameter names (no default value).
    pub positional_args: Vec<String>,
    /// Parameters with default values (name, default expression).
    pub default_args: Vec<(String, Expression)>,
    /// The macro body expression.
    pub expression: Box<Expression>,
}

/// CREATE VECTOR INDEX statement — creates an HNSW index on a vector column.
#[derive(Debug, Clone, PartialEq)]
pub struct CreateVectorIndex {
    pub index_name: String,
    pub table_name: String,
    pub column_name: String,
    pub metric: String,
    pub dimensions: u64,
}

#[derive(Debug, Clone, PartialEq)]
pub struct ColumnDef {
    pub name: String,
    pub type_name: String,
    pub compression: Option<String>,
}

/// CREATE TYPE name AS type — user-defined type alias.
#[derive(Debug, Clone, PartialEq)]
pub struct CreateType {
    pub name: String,
    pub type_name: String,
}

/// COMMENT ON TABLE name IS 'string' — add a comment to a table.
#[derive(Debug, Clone, PartialEq)]
pub struct CommentOnTable {
    pub table_name: String,
    pub comment: String,
}

/// CREATE [PROJECTION] GRAPH name [ANY] — create a projected graph.
#[derive(Debug, Clone, PartialEq)]
pub struct CreateGraph {
    pub name: String,
    pub is_any: bool,
}

/// USE GRAPH name — set the current graph context.
#[derive(Debug, Clone, PartialEq)]
pub struct UseGraph {
    pub name: String,
}

/// DROP GRAPH name — remove a projected graph.
#[derive(Debug, Clone, PartialEq)]
pub struct DropGraph {
    pub name: String,
}