ruvector-postgres 2.0.5

High-performance PostgreSQL vector database extension v2 - pgvector drop-in replacement with 230+ SQL functions, SIMD acceleration, Flash Attention, GNN layers, hybrid search, multi-tenancy, self-healing, and self-learning capabilities
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
631
// Cypher query executor

use super::ast::*;
use crate::graph::storage::GraphStore;
use serde_json::{json, Value as JsonValue};
use std::collections::HashMap;

// Direction is re-exported from ast::*

/// Execute a parsed Cypher query
pub fn execute_cypher(
    graph: &GraphStore,
    query: &CypherQuery,
    params: Option<&JsonValue>,
) -> Result<JsonValue, String> {
    let mut context = ExecutionContext::new(params);

    for clause in &query.clauses {
        match clause {
            Clause::Match(m) => execute_match(graph, m, &mut context)?,
            Clause::Create(c) => execute_create(graph, c, &mut context)?,
            Clause::Return(r) => return execute_return(graph, r, &context),
            Clause::Where(w) => execute_where(graph, w, &mut context)?,
            Clause::Set(s) => execute_set(graph, s, &mut context)?,
            Clause::Delete(d) => execute_delete(graph, d, &mut context)?,
            Clause::With(w) => execute_with(graph, w, &mut context)?,
        }
    }

    // If no RETURN clause, return empty result
    Ok(json!([]))
}

/// Execution context holding variable bindings
struct ExecutionContext<'a> {
    bindings: Vec<HashMap<String, Binding>>,
    params: Option<&'a JsonValue>,
}

impl<'a> ExecutionContext<'a> {
    fn new(params: Option<&'a JsonValue>) -> Self {
        Self {
            bindings: vec![HashMap::new()],
            params,
        }
    }

    fn bind(&mut self, var: &str, binding: Binding) {
        if let Some(last) = self.bindings.last_mut() {
            last.insert(var.to_string(), binding);
        }
    }

    fn get(&self, var: &str) -> Option<&Binding> {
        for bindings in self.bindings.iter().rev() {
            if let Some(binding) = bindings.get(var) {
                return Some(binding);
            }
        }
        None
    }

    fn get_param(&self, name: &str) -> Option<&JsonValue> {
        self.params.and_then(|p| p.get(name))
    }

    fn push_scope(&mut self) {
        self.bindings.push(HashMap::new());
    }

    fn pop_scope(&mut self) {
        self.bindings.pop();
    }
}

#[derive(Debug, Clone)]
enum Binding {
    Node(u64),
    Edge(u64),
    Value(JsonValue),
}

fn execute_match(
    graph: &GraphStore,
    match_clause: &MatchClause,
    context: &mut ExecutionContext,
) -> Result<(), String> {
    for pattern in &match_clause.patterns {
        match_pattern(graph, pattern, context)?;
    }
    Ok(())
}

fn match_pattern(
    graph: &GraphStore,
    pattern: &Pattern,
    context: &mut ExecutionContext,
) -> Result<(), String> {
    // Collect the pattern as alternating nodes and relationships:
    // (a:Person)-[:KNOWS]->(b:Person) = [Node(a), Rel(KNOWS), Node(b)]
    let mut node_patterns: Vec<&NodePattern> = Vec::new();
    let mut rel_patterns: Vec<&RelationshipPattern> = Vec::new();

    for element in &pattern.elements {
        match element {
            PatternElement::Node(np) => node_patterns.push(np),
            PatternElement::Relationship(rp) => rel_patterns.push(rp),
        }
    }

    // Case 1: Single node pattern — find all matching nodes
    if rel_patterns.is_empty() {
        if let Some(np) = node_patterns.first() {
            let candidates = find_matching_nodes(graph, np);
            if candidates.is_empty() {
                return Ok(());
            }
            // Create a binding row per matching node
            let mut rows: Vec<HashMap<String, Binding>> = Vec::new();
            for node in &candidates {
                let mut row = HashMap::new();
                if let Some(var) = &np.variable {
                    row.insert(var.clone(), Binding::Node(node.id));
                }
                rows.push(row);
            }
            context.bindings = rows;
            return Ok(());
        }
        return Ok(());
    }

    // Case 2: Pattern with relationships — traverse edges
    // For each relationship pattern, we need pairs of (source_node, target_node)
    // Pattern: (a)-[r:TYPE]->(b) means: find all edges of TYPE,
    // check source matches a's pattern and target matches b's pattern
    let mut result_rows: Vec<HashMap<String, Binding>> = Vec::new();

    // We process node-rel-node triples
    for i in 0..rel_patterns.len() {
        let src_pattern = node_patterns.get(i);
        let dst_pattern = node_patterns.get(i + 1);
        let rel_pattern = rel_patterns[i];

        // Get candidate edges by type
        let edges = if let Some(ref rel_type) = rel_pattern.rel_type {
            graph.edges.find_by_type(rel_type)
        } else {
            graph.edges.all_edges()
        };

        for edge in &edges {
            let (src_id, dst_id) = match rel_pattern.direction {
                Direction::Outgoing | Direction::Both => (edge.source, edge.target),
                Direction::Incoming => (edge.target, edge.source),
            };

            // Check source node matches pattern
            if let Some(sp) = src_pattern {
                if !node_matches_pattern(graph, src_id, sp) {
                    continue;
                }
            }

            // Check target node matches pattern
            if let Some(dp) = dst_pattern {
                if !node_matches_pattern(graph, dst_id, dp) {
                    continue;
                }
            }

            // Reject self-references when variables are different
            if let (Some(sp), Some(dp)) = (src_pattern, dst_pattern) {
                if let (Some(sv), Some(dv)) = (&sp.variable, &dp.variable) {
                    if sv != dv && src_id == dst_id {
                        continue;
                    }
                }
            }

            // Build binding row
            let mut row = HashMap::new();
            if let Some(sp) = src_pattern {
                if let Some(var) = &sp.variable {
                    row.insert(var.clone(), Binding::Node(src_id));
                }
            }
            if let Some(dp) = dst_pattern {
                if let Some(var) = &dp.variable {
                    row.insert(var.clone(), Binding::Node(dst_id));
                }
            }
            if let Some(var) = &rel_pattern.variable {
                row.insert(var.clone(), Binding::Edge(edge.id));
            }

            result_rows.push(row);

            // Also match the reverse direction for Both
            if rel_pattern.direction == Direction::Both && edge.source != edge.target {
                let mut rev_row = HashMap::new();
                if let Some(sp) = src_pattern {
                    if let Some(var) = &sp.variable {
                        rev_row.insert(var.clone(), Binding::Node(edge.target));
                    }
                }
                if let Some(dp) = dst_pattern {
                    if let Some(var) = &dp.variable {
                        rev_row.insert(var.clone(), Binding::Node(edge.source));
                    }
                }
                if let Some(var) = &rel_pattern.variable {
                    rev_row.insert(var.clone(), Binding::Edge(edge.id));
                }
                if let (Some(sp), Some(dp)) = (src_pattern, dst_pattern) {
                    if node_matches_pattern(graph, edge.target, sp)
                        && node_matches_pattern(graph, edge.source, dp)
                    {
                        result_rows.push(rev_row);
                    }
                }
            }
        }
    }

    if !result_rows.is_empty() {
        context.bindings = result_rows;
    }

    Ok(())
}

/// Find all nodes matching a node pattern (labels + properties)
fn find_matching_nodes(
    graph: &GraphStore,
    pattern: &NodePattern,
) -> Vec<crate::graph::storage::Node> {
    let candidates = if pattern.labels.is_empty() {
        graph.nodes.all_nodes()
    } else {
        graph.nodes.find_by_label(&pattern.labels[0])
    };

    candidates
        .into_iter()
        .filter(|node| {
            // Check all labels
            if !pattern.labels.iter().all(|l| node.has_label(l)) {
                return false;
            }
            // Check properties
            pattern.properties.iter().all(|(key, expr)| {
                if let Some(node_value) = node.get_property(key) {
                    if let Expression::Literal(expected) = expr {
                        node_value == expected
                    } else {
                        false
                    }
                } else {
                    false
                }
            })
        })
        .collect()
}

/// Check if a specific node ID matches a node pattern
fn node_matches_pattern(graph: &GraphStore, node_id: u64, pattern: &NodePattern) -> bool {
    if let Some(node) = graph.nodes.get(node_id) {
        // Check labels
        if !pattern.labels.iter().all(|l| node.has_label(l)) {
            return false;
        }
        // Check properties
        pattern.properties.iter().all(|(key, expr)| {
            if let Some(node_value) = node.get_property(key) {
                if let Expression::Literal(expected) = expr {
                    node_value == expected
                } else {
                    false
                }
            } else {
                false
            }
        })
    } else {
        false
    }
}

fn execute_create(
    graph: &GraphStore,
    create_clause: &CreateClause,
    context: &mut ExecutionContext,
) -> Result<(), String> {
    for pattern in &create_clause.patterns {
        create_pattern(graph, pattern, context)?;
    }
    Ok(())
}

fn create_pattern(
    graph: &GraphStore,
    pattern: &Pattern,
    context: &mut ExecutionContext,
) -> Result<(), String> {
    let mut last_node_id: Option<u64> = None;

    for element in &pattern.elements {
        match element {
            PatternElement::Node(node_pattern) => {
                let node_id = create_node(graph, node_pattern, context)?;
                last_node_id = Some(node_id);

                if let Some(var) = &node_pattern.variable {
                    context.bind(var, Binding::Node(node_id));
                }
            }
            PatternElement::Relationship(rel_pattern) => {
                if let Some(source_id) = last_node_id {
                    // For CREATE, we need to get the target node from context or create it
                    // This is simplified - production code would handle more complex patterns
                    let edge_id = create_relationship(graph, rel_pattern, source_id, context)?;

                    if let Some(var) = &rel_pattern.variable {
                        context.bind(var, Binding::Edge(edge_id));
                    }
                }
            }
        }
    }

    Ok(())
}

fn create_node(
    graph: &GraphStore,
    pattern: &NodePattern,
    context: &ExecutionContext,
) -> Result<u64, String> {
    let mut properties = HashMap::new();

    for (key, expr) in &pattern.properties {
        let value = evaluate_expression(expr, context)?;
        properties.insert(key.clone(), value);
    }

    let node_id = graph.add_node(pattern.labels.clone(), properties);
    Ok(node_id)
}

fn create_relationship(
    graph: &GraphStore,
    pattern: &RelationshipPattern,
    source_id: u64,
    context: &ExecutionContext,
) -> Result<u64, String> {
    let mut properties = HashMap::new();

    for (key, expr) in &pattern.properties {
        let value = evaluate_expression(expr, context)?;
        properties.insert(key.clone(), value);
    }

    let edge_type = pattern
        .rel_type
        .clone()
        .unwrap_or_else(|| "RELATED".to_string());

    // Resolve target from the next node in the pattern (bound in context)
    // Look through bindings for any node binding that isn't the source
    let target_id = context
        .bindings
        .iter()
        .rev()
        .flat_map(|b| b.values())
        .find_map(|binding| match binding {
            Binding::Node(id) if *id != source_id => Some(*id),
            _ => None,
        })
        .unwrap_or(source_id);

    graph.add_edge(source_id, target_id, edge_type, properties)
}

fn execute_return(
    graph: &GraphStore,
    return_clause: &ReturnClause,
    context: &ExecutionContext,
) -> Result<JsonValue, String> {
    let mut results = Vec::new();

    // If no bindings, return empty
    if context.bindings.is_empty() || context.bindings[0].is_empty() {
        return Ok(json!([]));
    }

    // For each binding combination
    for bindings in &context.bindings {
        if bindings.is_empty() {
            continue;
        }

        let mut row = serde_json::Map::new();

        for item in &return_clause.items {
            let value = evaluate_return_item(graph, item, bindings)?;
            let key = item.alias.clone().unwrap_or_else(|| {
                // Generate key from expression
                match &item.expression {
                    Expression::Variable(v) => v.clone(),
                    Expression::Property(v, p) => format!("{}.{}", v, p),
                    _ => "result".to_string(),
                }
            });

            row.insert(key, value);
        }

        results.push(JsonValue::Object(row));
    }

    // Apply DISTINCT
    if return_clause.distinct {
        results.sort_by(|a, b| a.to_string().cmp(&b.to_string()));
        results.dedup();
    }

    // Apply SKIP
    if let Some(skip) = return_clause.skip {
        results = results.into_iter().skip(skip).collect();
    }

    // Apply LIMIT
    if let Some(limit) = return_clause.limit {
        results.truncate(limit);
    }

    Ok(JsonValue::Array(results))
}

fn evaluate_return_item(
    graph: &GraphStore,
    item: &ReturnItem,
    bindings: &HashMap<String, Binding>,
) -> Result<JsonValue, String> {
    match &item.expression {
        Expression::Variable(var) => {
            if let Some(binding) = bindings.get(var) {
                match binding {
                    Binding::Node(id) => {
                        if let Some(node) = graph.nodes.get(*id) {
                            Ok(serde_json::to_value(&node).unwrap())
                        } else {
                            Ok(JsonValue::Null)
                        }
                    }
                    Binding::Edge(id) => {
                        if let Some(edge) = graph.edges.get(*id) {
                            Ok(serde_json::to_value(&edge).unwrap())
                        } else {
                            Ok(JsonValue::Null)
                        }
                    }
                    Binding::Value(v) => Ok(v.clone()),
                }
            } else {
                Ok(JsonValue::Null)
            }
        }
        Expression::Property(var, prop) => {
            if let Some(Binding::Node(id)) = bindings.get(var) {
                if let Some(node) = graph.nodes.get(*id) {
                    Ok(node.get_property(prop).cloned().unwrap_or(JsonValue::Null))
                } else {
                    Ok(JsonValue::Null)
                }
            } else {
                Ok(JsonValue::Null)
            }
        }
        Expression::Literal(value) => Ok(value.clone()),
        _ => Err("Unsupported return expression".to_string()),
    }
}

fn execute_where(
    _graph: &GraphStore,
    where_clause: &WhereClause,
    context: &mut ExecutionContext,
) -> Result<(), String> {
    // Evaluate WHERE condition and filter bindings
    // Simplified implementation
    let result = evaluate_expression(&where_clause.condition, context)?;

    if !result.as_bool().unwrap_or(false) {
        // Clear bindings if condition is false
        if let Some(last) = context.bindings.last_mut() {
            last.clear();
        }
    }

    Ok(())
}

fn execute_set(
    _graph: &GraphStore,
    _set_clause: &SetClause,
    _context: &mut ExecutionContext,
) -> Result<(), String> {
    // Simplified SET implementation
    Ok(())
}

fn execute_delete(
    _graph: &GraphStore,
    _delete_clause: &DeleteClause,
    _context: &mut ExecutionContext,
) -> Result<(), String> {
    // Simplified DELETE implementation
    Ok(())
}

fn execute_with(
    _graph: &GraphStore,
    _with_clause: &WithClause,
    _context: &mut ExecutionContext,
) -> Result<(), String> {
    // Simplified WITH implementation
    Ok(())
}

fn evaluate_expression(expr: &Expression, context: &ExecutionContext) -> Result<JsonValue, String> {
    match expr {
        Expression::Literal(value) => Ok(value.clone()),
        Expression::Variable(var) => {
            if let Some(binding) = context.get(var) {
                match binding {
                    Binding::Value(v) => Ok(v.clone()),
                    Binding::Node(id) => Ok(json!({ "id": id })),
                    Binding::Edge(id) => Ok(json!({ "id": id })),
                }
            } else {
                Ok(JsonValue::Null)
            }
        }
        Expression::Parameter(name) => {
            Ok(context.get_param(name).cloned().unwrap_or(JsonValue::Null))
        }
        Expression::BinaryOp(left, op, right) => {
            let left_val = evaluate_expression(left, context)?;
            let right_val = evaluate_expression(right, context)?;

            match op {
                BinaryOperator::Eq => Ok(json!(left_val == right_val)),
                BinaryOperator::Neq => Ok(json!(left_val != right_val)),
                BinaryOperator::Lt => {
                    if let (Some(l), Some(r)) = (left_val.as_f64(), right_val.as_f64()) {
                        Ok(json!(l < r))
                    } else {
                        Ok(json!(false))
                    }
                }
                BinaryOperator::Gt => {
                    if let (Some(l), Some(r)) = (left_val.as_f64(), right_val.as_f64()) {
                        Ok(json!(l > r))
                    } else {
                        Ok(json!(false))
                    }
                }
                _ => Err(format!("Unsupported binary operator: {:?}", op)),
            }
        }
        _ => Err("Unsupported expression type".to_string()),
    }
}

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

    #[test]
    fn test_execute_create() {
        let graph = GraphStore::new();

        let pattern = Pattern::new().with_element(PatternElement::Node(
            NodePattern::new()
                .with_variable("n")
                .with_label("Person")
                .with_property("name", Expression::literal("Alice")),
        ));

        let create = CreateClause::new(vec![pattern]);
        let query = CypherQuery::new()
            .with_clause(Clause::Create(create))
            .with_clause(Clause::Return(ReturnClause::new(vec![ReturnItem::new(
                Expression::variable("n"),
            )])));

        let result = execute_cypher(&graph, &query, None);
        assert!(result.is_ok());

        let json = result.unwrap();
        assert!(json.is_array());
    }

    #[test]
    fn test_execute_match() {
        let graph = GraphStore::new();

        // Create a node first
        graph.add_node(
            vec!["Person".to_string()],
            HashMap::from([("name".to_string(), "Alice".into())]),
        );

        let pattern = Pattern::new().with_element(PatternElement::Node(
            NodePattern::new().with_variable("n").with_label("Person"),
        ));

        let match_clause = MatchClause::new(vec![pattern]);
        let query = CypherQuery::new()
            .with_clause(Clause::Match(match_clause))
            .with_clause(Clause::Return(ReturnClause::new(vec![ReturnItem::new(
                Expression::property("n", "name"),
            )])));

        let result = execute_cypher(&graph, &query, None);
        assert!(result.is_ok());
    }
}