graph_d 1.3.2

A native graph database implementation in Rust with built-in JSON support and SQLite-like simplicity
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
//! Abstract Syntax Tree (AST) structures for GQL.

use serde_json::Value;
use std::collections::HashMap;

/// Root GQL statement.
#[derive(Debug, Clone)]
pub enum GqlStatement {
    /// A linear query that operates on the default graph
    LinearQuery(LinearQuery),
    /// A query that operates on a named graph
    GraphQuery {
        /// Name of the graph to query
        graph_name: String,
        /// The query to execute on the graph
        query: LinearQuery,
    },
}

/// A linear query statement that can be chained with NEXT.
#[derive(Debug, Clone)]
pub struct LinearQuery {
    /// The sequence of clauses that make up this query
    pub clauses: Vec<QueryClause>,
}

/// Individual clauses in a linear query.
#[derive(Debug, Clone)]
pub enum QueryClause {
    /// MATCH clause for pattern matching
    Match(MatchClause),
    /// FILTER clause for filtering results  
    Filter(FilterClause),
    /// RETURN clause for specifying output
    Return(ReturnClause),
    /// WITH clause for passing data between query parts
    With(WithClause),
    /// ORDER BY clause for sorting results
    OrderBy(OrderByClause),
    /// LIMIT clause for limiting result count
    Limit(LimitClause),
    /// OFFSET clause for skipping results
    Offset(OffsetClause),
    /// INSERT clause for creating new graph elements
    Insert(InsertClause),
    /// UPDATE clause for modifying existing elements
    Update(UpdateClause),
    /// DELETE clause for removing graph elements
    Delete(DeleteClause),
    /// SET clause for setting property values
    Set(SetClause),
    /// REMOVE clause for removing properties or labels
    Remove(RemoveClause),
}

/// MATCH clause for pattern matching.
#[derive(Debug, Clone)]
pub struct MatchClause {
    /// Whether this is an OPTIONAL MATCH
    pub optional: bool,
    /// The graph patterns to match
    pub patterns: Vec<GraphPattern>,
}

/// Graph pattern in MATCH clauses.
#[derive(Debug, Clone)]
pub enum GraphPattern {
    /// A node pattern (n:Label {prop: value})
    Node(NodePattern),
    /// A path pattern (sequence of nodes and relationships)
    Path(PathPattern),
    /// A relationship pattern -\[:TYPE\]->
    Relationship(RelationshipPattern),
}

/// Node pattern: (variable:Label1|Label2 {prop: value})
#[derive(Debug, Clone)]
pub struct NodePattern {
    /// Optional variable name for binding
    pub variable: Option<String>,
    /// Node labels to match
    pub labels: Vec<String>,
    /// Property patterns to match
    pub properties: Option<PropertyPattern>,
    /// Optional WHERE clause for additional filtering
    pub where_clause: Option<Box<Expression>>,
}

/// Relationship pattern: [variable:TYPE {prop: value}]
#[derive(Debug, Clone)]
pub struct RelationshipPattern {
    /// Optional variable name for binding
    pub variable: Option<String>,
    /// Relationship type to match
    pub rel_type: Option<String>,
    /// Property patterns to match
    pub properties: Option<PropertyPattern>,
    /// Direction of the relationship
    pub direction: RelationshipDirection,
    /// Optional path length specification
    pub length: Option<PathLength>,
}

/// Path pattern: (start)-\[rel\]->(end)
#[derive(Debug, Clone)]
pub struct PathPattern {
    /// Starting node pattern
    pub start: Box<NodePattern>,
    /// Sequence of relationship and node patterns
    pub relationships: Vec<(RelationshipPattern, Box<NodePattern>)>,
}

/// Property pattern: {key: value, key2: $param}
#[derive(Debug, Clone)]
pub struct PropertyPattern {
    /// Property key-value pairs to match
    pub properties: HashMap<String, Expression>,
}

/// Relationship direction.
#[derive(Debug, Clone, PartialEq, Copy)]
pub enum RelationshipDirection {
    /// Outgoing relationship (->)
    Outgoing,
    /// Incoming relationship (<-)
    Incoming,
    /// Undirected relationship (--)
    Undirected,
}

/// Path length specification.
#[derive(Debug, Clone)]
pub enum PathLength {
    /// Exact path length (e.g., *5)
    Exact(usize),
    /// Range of path lengths (e.g., *2..5, *..3, *2..)
    Range(Option<usize>, Option<usize>),
    /// Variable length path (*)
    Variable,
}

/// WHERE/FILTER clause.
#[derive(Debug, Clone)]
pub struct FilterClause {
    /// The boolean condition to evaluate
    pub condition: Expression,
}

/// RETURN clause.
#[derive(Debug, Clone)]
pub struct ReturnClause {
    /// Whether to return distinct results only
    pub distinct: bool,
    /// Items to return
    pub items: Vec<ReturnItem>,
}

/// Item in RETURN clause.
#[derive(Debug, Clone)]
pub struct ReturnItem {
    /// Expression to evaluate and return
    pub expression: Expression,
    /// Optional alias for the returned value
    pub alias: Option<String>,
}

/// WITH clause for piping data.
#[derive(Debug, Clone)]
pub struct WithClause {
    /// Items to pass to the next query part
    pub items: Vec<ReturnItem>,
}

/// ORDER BY clause.
#[derive(Debug, Clone)]
pub struct OrderByClause {
    /// Items to sort by
    pub items: Vec<OrderByItem>,
}

/// Item in ORDER BY clause.
#[derive(Debug, Clone)]
pub struct OrderByItem {
    /// Expression to sort by
    pub expression: Expression,
    /// Sort direction (ascending or descending)
    pub direction: SortDirection,
}

/// Sort direction.
#[derive(Debug, Clone)]
pub enum SortDirection {
    /// Ascending sort order
    Asc,
    /// Descending sort order
    Desc,
}

/// LIMIT clause.
#[derive(Debug, Clone)]
pub struct LimitClause {
    /// Maximum number of results to return
    pub count: Expression,
}

/// OFFSET clause.
#[derive(Debug, Clone)]
pub struct OffsetClause {
    /// Number of results to skip
    pub count: Expression,
}

/// INSERT clause.
#[derive(Debug, Clone)]
pub struct InsertClause {
    /// Graph patterns to insert
    pub patterns: Vec<GraphPattern>,
}

/// UPDATE clause.
#[derive(Debug, Clone)]
pub struct UpdateClause {
    /// Pattern to match for updating
    pub pattern: GraphPattern,
    /// Items to set during update
    pub set_items: Vec<SetItem>,
}

/// DELETE clause.
#[derive(Debug, Clone)]
pub struct DeleteClause {
    /// Whether to detach relationships before deleting
    pub detach: bool,
    /// Expressions identifying what to delete
    pub expressions: Vec<Expression>,
}

/// SET clause.
#[derive(Debug, Clone)]
pub struct SetClause {
    /// Items to set
    pub items: Vec<SetItem>,
}

/// Item in SET clause.
#[derive(Debug, Clone)]
pub struct SetItem {
    /// Target to set (property or variable)
    pub target: Expression,
    /// Value to assign
    pub value: Expression,
}

/// REMOVE clause.
#[derive(Debug, Clone)]
pub struct RemoveClause {
    /// Items to remove
    pub items: Vec<RemoveItem>,
}

/// Item in REMOVE clause.
#[derive(Debug, Clone)]
pub enum RemoveItem {
    /// Remove a property from a node or relationship
    Property(Expression),
    /// Remove a label from a node
    Label(Expression, String),
}

/// Expressions in GQL.
#[derive(Debug, Clone)]
pub enum Expression {
    /// Literal value (string, number, boolean, null)
    Literal(Value),
    /// Parameter reference ($param)
    Parameter(String),

    /// Variable reference
    Variable(String),
    /// Property access (object.property)
    Property {
        /// Object being accessed
        object: Box<Expression>,
        /// Property name
        property: String,
    },

    /// Binary operation (left op right)
    Binary {
        /// Left operand
        left: Box<Expression>,
        /// Binary operator
        operator: BinaryOperator,
        /// Right operand
        right: Box<Expression>,
    },

    /// Unary operation (op operand)
    Unary {
        /// Unary operator
        operator: UnaryOperator,
        /// Operand
        operand: Box<Expression>,
    },

    /// Function call
    FunctionCall {
        /// Function name
        name: String,
        /// Function arguments
        args: Vec<Expression>,
    },

    /// List literal \[expr1, expr2, ...\]
    List(Vec<Expression>),
    /// List element access list\[index\]
    ListAccess {
        /// List expression
        list: Box<Expression>,
        /// Index expression
        index: Box<Expression>,
    },
    /// List slice list\[start..end\]
    ListSlice {
        /// List expression
        list: Box<Expression>,
        /// Start index (optional)
        start: Option<Box<Expression>>,
        /// End index (optional)
        end: Option<Box<Expression>>,
    },

    /// Path expression for graph patterns
    PathExpression(Box<PathPattern>),

    /// CASE expression for conditional logic
    Case {
        /// WHEN clauses (condition, result)
        when_clauses: Vec<(Expression, Expression)>,
        /// ELSE clause
        else_clause: Option<Box<Expression>>,
    },

    /// Aggregate function call
    Aggregate {
        /// Aggregate function type
        function: AggregateFunction,
        /// Expression to aggregate (None for COUNT(*))
        expression: Option<Box<Expression>>,
        /// Whether to use DISTINCT
        distinct: bool,
    },
}

/// Binary operators.
#[derive(Debug, Clone)]
pub enum BinaryOperator {
    /// Addition (+)
    Add,
    /// Subtraction (-)
    Subtract,
    /// Multiplication (*)
    Multiply,
    /// Division (/)
    Divide,
    /// Modulo (%)
    Modulo,

    /// Equality (=, ==)
    Equal,
    /// Inequality (<>, !=)
    NotEqual,
    /// Less than (<)
    LessThan,
    /// Less than or equal (<=)
    LessEqual,
    /// Greater than (>)
    GreaterThan,
    /// Greater than or equal (>=)
    GreaterEqual,

    /// Logical AND
    And,
    /// Logical OR
    Or,

    /// String contains operation
    Contains,
    /// String starts with operation
    StartsWith,
    /// String ends with operation
    EndsWith,

    /// Collection membership (IN)
    In,
}

/// Unary operators.
#[derive(Debug, Clone)]
pub enum UnaryOperator {
    /// Logical NOT
    Not,
    /// Arithmetic negation (-)
    Minus,
    /// Arithmetic positive (+)
    Plus,
}

/// Aggregate functions.
#[derive(Debug, Clone)]
pub enum AggregateFunction {
    /// Count of elements
    Count,
    /// Sum of numeric values
    Sum,
    /// Average of numeric values
    Avg,
    /// Minimum value
    Min,
    /// Maximum value
    Max,
    /// Collect values into a list
    Collect,
}

impl LinearQuery {
    /// Create a new empty linear query.
    pub fn new() -> Self {
        Self {
            clauses: Vec::new(),
        }
    }

    /// Add a clause to the query.
    pub fn add_clause(&mut self, clause: QueryClause) {
        self.clauses.push(clause);
    }

    /// Get all MATCH clauses.
    pub fn match_clauses(&self) -> Vec<&MatchClause> {
        self.clauses
            .iter()
            .filter_map(|c| {
                if let QueryClause::Match(m) = c {
                    Some(m)
                } else {
                    None
                }
            })
            .collect()
    }

    /// Get the RETURN clause if present.
    pub fn return_clause(&self) -> Option<&ReturnClause> {
        self.clauses.iter().find_map(|c| {
            if let QueryClause::Return(r) = c {
                Some(r)
            } else {
                None
            }
        })
    }

    /// Get all WHERE/FILTER clauses.
    pub fn filter_clauses(&self) -> Vec<&FilterClause> {
        self.clauses
            .iter()
            .filter_map(|c| {
                if let QueryClause::Filter(f) = c {
                    Some(f)
                } else {
                    None
                }
            })
            .collect()
    }
}

impl NodePattern {
    /// Create a new node pattern.
    pub fn new(variable: Option<String>) -> Self {
        Self {
            variable,
            labels: Vec::new(),
            properties: None,
            where_clause: None,
        }
    }

    /// Add a label to the node pattern.
    pub fn with_label(mut self, label: String) -> Self {
        self.labels.push(label);
        self
    }

    /// Add properties to the node pattern.
    pub fn with_properties(mut self, properties: PropertyPattern) -> Self {
        self.properties = Some(properties);
        self
    }
}

impl RelationshipPattern {
    /// Create a new relationship pattern.
    pub fn new(direction: RelationshipDirection) -> Self {
        Self {
            variable: None,
            rel_type: None,
            properties: None,
            direction,
            length: None,
        }
    }

    /// Set the relationship type.
    pub fn with_type(mut self, rel_type: String) -> Self {
        self.rel_type = Some(rel_type);
        self
    }

    /// Set the variable name.
    pub fn with_variable(mut self, variable: String) -> Self {
        self.variable = Some(variable);
        self
    }
}

impl Expression {
    /// Create a literal expression.
    pub fn literal(value: Value) -> Self {
        Expression::Literal(value)
    }

    /// Create a variable expression.
    pub fn variable(name: String) -> Self {
        Expression::Variable(name)
    }

    /// Create a property access expression.
    pub fn property(object: Expression, property: String) -> Self {
        Expression::Property {
            object: Box::new(object),
            property,
        }
    }

    /// Create a binary expression.
    pub fn binary(left: Expression, operator: BinaryOperator, right: Expression) -> Self {
        Expression::Binary {
            left: Box::new(left),
            operator,
            right: Box::new(right),
        }
    }
}

impl Default for LinearQuery {
    fn default() -> Self {
        Self::new()
    }
}