ruvector-graph 2.0.6

Distributed Neo4j-compatible hypergraph database with SIMD optimization
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
//! Abstract Syntax Tree definitions for Cypher query language
//!
//! Represents the parsed structure of Cypher queries including:
//! - Pattern matching (MATCH, OPTIONAL MATCH)
//! - Filtering (WHERE)
//! - Projections (RETURN, WITH)
//! - Mutations (CREATE, MERGE, DELETE, SET)
//! - Aggregations and ordering
//! - Hyperedge support for N-ary relationships

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Top-level query representation
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Query {
    pub statements: Vec<Statement>,
}

/// Individual query statement
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum Statement {
    Match(MatchClause),
    Create(CreateClause),
    Merge(MergeClause),
    Delete(DeleteClause),
    Set(SetClause),
    Remove(RemoveClause),
    Return(ReturnClause),
    With(WithClause),
}

/// MATCH clause for pattern matching
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MatchClause {
    pub optional: bool,
    pub patterns: Vec<Pattern>,
    pub where_clause: Option<WhereClause>,
}

/// Pattern matching expressions
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum Pattern {
    /// Simple node pattern: (n:Label {props})
    Node(NodePattern),
    /// Relationship pattern: (a)-[r:TYPE]->(b)
    Relationship(RelationshipPattern),
    /// Path pattern: p = (a)-[*1..5]->(b)
    Path(PathPattern),
    /// Hyperedge pattern for N-ary relationships: (a)-[r:TYPE]->(b,c,d)
    Hyperedge(HyperedgePattern),
}

/// Node pattern: (variable:Label {property: value})
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct NodePattern {
    pub variable: Option<String>,
    pub labels: Vec<String>,
    pub properties: Option<PropertyMap>,
}

/// Relationship pattern: [variable:Type {properties}]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RelationshipPattern {
    pub variable: Option<String>,
    pub rel_type: Option<String>,
    pub properties: Option<PropertyMap>,
    pub direction: Direction,
    pub range: Option<RelationshipRange>,
    /// Source node pattern
    pub from: Box<NodePattern>,
    /// Target - can be a NodePattern or another Pattern for chained relationships
    /// For simple relationships like (a)-[r]->(b), this is just the node
    /// For chained patterns like (a)-[r]->(b)<-[s]-(c), the target is nested
    pub to: Box<Pattern>,
}

/// Hyperedge pattern for N-ary relationships
/// Example: (person)-[r:TRANSACTION]->(account1, account2, merchant)
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct HyperedgePattern {
    pub variable: Option<String>,
    pub rel_type: String,
    pub properties: Option<PropertyMap>,
    pub from: Box<NodePattern>,
    pub to: Vec<NodePattern>, // Multiple target nodes for N-ary relationships
    pub arity: usize,         // Number of participating nodes (including source)
}

/// Relationship direction
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum Direction {
    Outgoing,   // ->
    Incoming,   // <-
    Undirected, // -
}

/// Relationship range for path queries: [*min..max]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RelationshipRange {
    pub min: Option<usize>,
    pub max: Option<usize>,
}

/// Path pattern: p = (a)-[*]->(b)
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PathPattern {
    pub variable: String,
    pub pattern: Box<Pattern>,
}

/// Property map: {key: value, ...}
pub type PropertyMap = HashMap<String, Expression>;

/// WHERE clause for filtering
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct WhereClause {
    pub condition: Expression,
}

/// CREATE clause for creating nodes and relationships
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CreateClause {
    pub patterns: Vec<Pattern>,
}

/// MERGE clause for create-or-match
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MergeClause {
    pub pattern: Pattern,
    pub on_create: Option<SetClause>,
    pub on_match: Option<SetClause>,
}

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

/// SET clause for updating properties
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SetClause {
    pub items: Vec<SetItem>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum SetItem {
    Property {
        variable: String,
        property: String,
        value: Expression,
    },
    Variable {
        variable: String,
        value: Expression,
    },
    Labels {
        variable: String,
        labels: Vec<String>,
    },
}

/// REMOVE clause for removing properties or labels
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RemoveClause {
    pub items: Vec<RemoveItem>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum RemoveItem {
    /// Remove a property: REMOVE n.property
    Property { variable: String, property: String },
    /// Remove labels: REMOVE n:Label1:Label2
    Labels {
        variable: String,
        labels: Vec<String>,
    },
}

/// RETURN clause for projection
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ReturnClause {
    pub distinct: bool,
    pub items: Vec<ReturnItem>,
    pub order_by: Option<OrderBy>,
    pub skip: Option<Expression>,
    pub limit: Option<Expression>,
}

/// WITH clause for chaining queries
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct WithClause {
    pub distinct: bool,
    pub items: Vec<ReturnItem>,
    pub where_clause: Option<WhereClause>,
    pub order_by: Option<OrderBy>,
    pub skip: Option<Expression>,
    pub limit: Option<Expression>,
}

/// Return item: expression AS alias
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ReturnItem {
    pub expression: Expression,
    pub alias: Option<String>,
}

/// ORDER BY clause
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct OrderBy {
    pub items: Vec<OrderByItem>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct OrderByItem {
    pub expression: Expression,
    pub ascending: bool,
}

/// Expression tree
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum Expression {
    // Literals
    Integer(i64),
    Float(f64),
    String(String),
    Boolean(bool),
    Null,

    // Variables and properties
    Variable(String),
    Property {
        object: Box<Expression>,
        property: String,
    },

    // Collections
    List(Vec<Expression>),
    Map(HashMap<String, Expression>),

    // Operators
    BinaryOp {
        left: Box<Expression>,
        op: BinaryOperator,
        right: Box<Expression>,
    },
    UnaryOp {
        op: UnaryOperator,
        operand: Box<Expression>,
    },

    // Functions and aggregations
    FunctionCall {
        name: String,
        args: Vec<Expression>,
    },
    Aggregation {
        function: AggregationFunction,
        expression: Box<Expression>,
        distinct: bool,
    },

    // Pattern predicates
    PatternPredicate(Box<Pattern>),

    // Case expressions
    Case {
        expression: Option<Box<Expression>>,
        alternatives: Vec<(Expression, Expression)>,
        default: Option<Box<Expression>>,
    },
}

/// Binary operators
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum BinaryOperator {
    // Arithmetic
    Add,
    Subtract,
    Multiply,
    Divide,
    Modulo,
    Power,

    // Comparison
    Equal,
    NotEqual,
    LessThan,
    LessThanOrEqual,
    GreaterThan,
    GreaterThanOrEqual,

    // Logical
    And,
    Or,
    Xor,

    // String
    Contains,
    StartsWith,
    EndsWith,
    Matches, // Regex

    // Collection
    In,

    // Null checking
    Is,
    IsNot,
}

/// Unary operators
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum UnaryOperator {
    Not,
    Minus,
    Plus,
    IsNull,
    IsNotNull,
}

/// Aggregation functions
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum AggregationFunction {
    Count,
    Sum,
    Avg,
    Min,
    Max,
    Collect,
    StdDev,
    StdDevP,
    Percentile,
}

impl Query {
    pub fn new(statements: Vec<Statement>) -> Self {
        Self { statements }
    }

    /// Check if query contains only read operations
    pub fn is_read_only(&self) -> bool {
        self.statements.iter().all(|stmt| {
            matches!(
                stmt,
                Statement::Match(_) | Statement::Return(_) | Statement::With(_)
            )
        })
    }

    /// Check if query contains hyperedges
    pub fn has_hyperedges(&self) -> bool {
        self.statements.iter().any(|stmt| match stmt {
            Statement::Match(m) => m
                .patterns
                .iter()
                .any(|p| matches!(p, Pattern::Hyperedge(_))),
            Statement::Create(c) => c
                .patterns
                .iter()
                .any(|p| matches!(p, Pattern::Hyperedge(_))),
            Statement::Merge(m) => matches!(&m.pattern, Pattern::Hyperedge(_)),
            _ => false,
        })
    }
}

impl Pattern {
    /// Get the arity of the pattern (number of nodes involved)
    pub fn arity(&self) -> usize {
        match self {
            Pattern::Node(_) => 1,
            Pattern::Relationship(_) => 2,
            Pattern::Path(_) => 2, // Simplified, could be variable
            Pattern::Hyperedge(h) => h.arity,
        }
    }
}

impl Expression {
    /// Check if expression is constant (no variables)
    pub fn is_constant(&self) -> bool {
        match self {
            Expression::Integer(_)
            | Expression::Float(_)
            | Expression::String(_)
            | Expression::Boolean(_)
            | Expression::Null => true,
            Expression::List(items) => items.iter().all(|e| e.is_constant()),
            Expression::Map(map) => map.values().all(|e| e.is_constant()),
            Expression::BinaryOp { left, right, .. } => left.is_constant() && right.is_constant(),
            Expression::UnaryOp { operand, .. } => operand.is_constant(),
            _ => false,
        }
    }

    /// Check if expression contains aggregation
    pub fn has_aggregation(&self) -> bool {
        match self {
            Expression::Aggregation { .. } => true,
            Expression::BinaryOp { left, right, .. } => {
                left.has_aggregation() || right.has_aggregation()
            }
            Expression::UnaryOp { operand, .. } => operand.has_aggregation(),
            Expression::FunctionCall { args, .. } => args.iter().any(|e| e.has_aggregation()),
            Expression::List(items) => items.iter().any(|e| e.has_aggregation()),
            Expression::Property { object, .. } => object.has_aggregation(),
            _ => false,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_query_is_read_only() {
        let query = Query::new(vec![
            Statement::Match(MatchClause {
                optional: false,
                patterns: vec![],
                where_clause: None,
            }),
            Statement::Return(ReturnClause {
                distinct: false,
                items: vec![],
                order_by: None,
                skip: None,
                limit: None,
            }),
        ]);
        assert!(query.is_read_only());
    }

    #[test]
    fn test_expression_is_constant() {
        assert!(Expression::Integer(42).is_constant());
        assert!(Expression::String("test".to_string()).is_constant());
        assert!(!Expression::Variable("x".to_string()).is_constant());
    }

    #[test]
    fn test_hyperedge_arity() {
        let hyperedge = Pattern::Hyperedge(HyperedgePattern {
            variable: Some("r".to_string()),
            rel_type: "TRANSACTION".to_string(),
            properties: None,
            from: Box::new(NodePattern {
                variable: Some("a".to_string()),
                labels: vec![],
                properties: None,
            }),
            to: vec![
                NodePattern {
                    variable: Some("b".to_string()),
                    labels: vec![],
                    properties: None,
                },
                NodePattern {
                    variable: Some("c".to_string()),
                    labels: vec![],
                    properties: None,
                },
            ],
            arity: 3,
        });
        assert_eq!(hyperedge.arity(), 3);
    }
}