interstellar 0.2.0

A high-performance graph database with Gremlin-style traversals and GQL query language
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
//! Helper types and functions for the GQL compiler.
//!
//! This module contains:
//! - `ComparableValue`: A wrapper for `Value` that implements `Eq` and `Hash` for grouping
//! - Comparison and binary operation functions
//! - Inline WHERE expression evaluation utilities

use crate::gql::ast::{BinaryOperator, Expression, UnaryOperator};
use crate::storage::GraphStorage;
use crate::value::Value;

use super::Parameters;

// =============================================================================
// Helper Types for Aggregation
// =============================================================================

/// A comparable wrapper for Value that implements Eq and Hash for grouping.
#[derive(Debug, Clone)]
pub(super) struct ComparableValue(pub(super) Value);

impl PartialEq for ComparableValue {
    fn eq(&self, other: &Self) -> bool {
        match (&self.0, &other.0) {
            (Value::Null, Value::Null) => true,
            (Value::Bool(a), Value::Bool(b)) => a == b,
            (Value::Int(a), Value::Int(b)) => a == b,
            (Value::Float(a), Value::Float(b)) => {
                // Handle NaN and compare floats bitwise
                a.to_bits() == b.to_bits()
            }
            (Value::String(a), Value::String(b)) => a == b,
            (Value::Vertex(a), Value::Vertex(b)) => a == b,
            (Value::Edge(a), Value::Edge(b)) => a == b,
            (Value::List(a), Value::List(b)) => {
                if a.len() != b.len() {
                    return false;
                }
                a.iter()
                    .zip(b.iter())
                    .all(|(x, y)| ComparableValue(x.clone()) == ComparableValue(y.clone()))
            }
            (Value::Map(a), Value::Map(b)) => {
                if a.len() != b.len() {
                    return false;
                }
                a.iter().all(|(k, v)| {
                    b.get(k)
                        .map(|bv| ComparableValue(v.clone()) == ComparableValue(bv.clone()))
                        .unwrap_or(false)
                })
            }
            _ => false,
        }
    }
}

impl Eq for ComparableValue {}

impl std::hash::Hash for ComparableValue {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        std::mem::discriminant(&self.0).hash(state);
        match &self.0 {
            Value::Null => {}
            Value::Bool(b) => b.hash(state),
            Value::Int(n) => n.hash(state),
            Value::Float(f) => f.to_bits().hash(state),
            Value::String(s) => s.hash(state),
            Value::Vertex(id) => id.0.hash(state),
            Value::Edge(id) => id.0.hash(state),
            Value::Point(p) => {
                p.lon.to_bits().hash(state);
                p.lat.to_bits().hash(state);
            }
            Value::Polygon(p) => {
                for &(lon, lat) in &p.ring {
                    lon.to_bits().hash(state);
                    lat.to_bits().hash(state);
                }
            }
            Value::List(items) => {
                items.len().hash(state);
                for item in items {
                    ComparableValue(item.clone()).hash(state);
                }
            }
            Value::Map(map) => {
                map.len().hash(state);
                // Sort keys for deterministic hash ordering across runs
                let mut entries: Vec<_> = map.iter().collect();
                entries.sort_by(|(k1, _), (k2, _)| k1.cmp(k2));
                for (k, v) in entries {
                    k.hash(state);
                    ComparableValue(v.clone()).hash(state);
                }
            }
        }
    }
}

impl From<Value> for ComparableValue {
    fn from(v: Value) -> Self {
        ComparableValue(v)
    }
}

impl From<ComparableValue> for Value {
    fn from(cv: ComparableValue) -> Self {
        cv.0
    }
}

// =============================================================================
// Helper Functions for Expression Evaluation
// =============================================================================

/// Apply a comparison operator to two values.
pub(super) fn apply_comparison(op: BinaryOperator, left: &Value, right: &Value) -> bool {
    match op {
        BinaryOperator::Eq => left == right,
        BinaryOperator::Neq => left != right,
        BinaryOperator::Lt => compare_values(left, right) == std::cmp::Ordering::Less,
        BinaryOperator::Lte => {
            matches!(
                compare_values(left, right),
                std::cmp::Ordering::Less | std::cmp::Ordering::Equal
            )
        }
        BinaryOperator::Gt => compare_values(left, right) == std::cmp::Ordering::Greater,
        BinaryOperator::Gte => {
            matches!(
                compare_values(left, right),
                std::cmp::Ordering::Greater | std::cmp::Ordering::Equal
            )
        }
        BinaryOperator::And => value_to_bool(left) && value_to_bool(right),
        BinaryOperator::Or => value_to_bool(left) || value_to_bool(right),
        BinaryOperator::Contains => match (left, right) {
            (Value::String(s), Value::String(sub)) => s.contains(sub.as_str()),
            _ => false,
        },
        BinaryOperator::StartsWith => match (left, right) {
            (Value::String(s), Value::String(prefix)) => s.starts_with(prefix.as_str()),
            _ => false,
        },
        BinaryOperator::EndsWith => match (left, right) {
            (Value::String(s), Value::String(suffix)) => s.ends_with(suffix.as_str()),
            _ => false,
        },
        BinaryOperator::RegexMatch => match (left, right) {
            (Value::String(s), Value::String(pattern)) => {
                // Compile with size limits to prevent ReDoS attacks
                match regex::RegexBuilder::new(pattern)
                    .size_limit(1024 * 1024) // 1MB compiled regex limit
                    .dfa_size_limit(1024 * 1024) // 1MB DFA limit
                    .build()
                {
                    Ok(re) => re.is_match(s),
                    Err(_) => false, // Invalid or too-complex regex pattern returns false
                }
            }
            // NULL operands return false (not a match)
            (Value::Null, _) | (_, Value::Null) => false,
            // Non-string operands return false
            _ => false,
        },
        // Arithmetic operators don't return bool, but we handle them for completeness
        _ => false,
    }
}

/// Apply a binary operator and return the result as a Value.
pub(super) fn apply_binary_op(op: BinaryOperator, left: Value, right: Value) -> Value {
    match op {
        BinaryOperator::Add => match (left, right) {
            (Value::Int(a), Value::Int(b)) => Value::Int(a + b),
            (Value::Float(a), Value::Float(b)) => Value::Float(a + b),
            (Value::Int(a), Value::Float(b)) => Value::Float(a as f64 + b),
            (Value::Float(a), Value::Int(b)) => Value::Float(a + b as f64),
            (Value::String(a), Value::String(b)) => Value::String(a + b.as_str()),
            _ => Value::Null,
        },
        BinaryOperator::Sub => match (left, right) {
            (Value::Int(a), Value::Int(b)) => Value::Int(a - b),
            (Value::Float(a), Value::Float(b)) => Value::Float(a - b),
            (Value::Int(a), Value::Float(b)) => Value::Float(a as f64 - b),
            (Value::Float(a), Value::Int(b)) => Value::Float(a - b as f64),
            _ => Value::Null,
        },
        BinaryOperator::Mul => match (left, right) {
            (Value::Int(a), Value::Int(b)) => Value::Int(a * b),
            (Value::Float(a), Value::Float(b)) => Value::Float(a * b),
            (Value::Int(a), Value::Float(b)) => Value::Float(a as f64 * b),
            (Value::Float(a), Value::Int(b)) => Value::Float(a * b as f64),
            _ => Value::Null,
        },
        BinaryOperator::Div => match (left, right) {
            (Value::Int(a), Value::Int(b)) if b != 0 => Value::Int(a / b),
            (Value::Float(a), Value::Float(b)) if b != 0.0 => Value::Float(a / b),
            (Value::Int(a), Value::Float(b)) if b != 0.0 => Value::Float(a as f64 / b),
            (Value::Float(a), Value::Int(b)) if b != 0 => Value::Float(a / b as f64),
            _ => Value::Null,
        },
        BinaryOperator::Mod => match (left, right) {
            (Value::Int(a), Value::Int(b)) if b != 0 => Value::Int(a % b),
            _ => Value::Null,
        },
        BinaryOperator::Pow => match (left, right) {
            // Integer to non-negative integer power
            (Value::Int(a), Value::Int(b)) if b >= 0 => {
                // Validate exponent fits in u32 to prevent truncation
                if b > u32::MAX as i64 {
                    // Exponent too large - fall back to float
                    Value::Float((a as f64).powf(b as f64))
                } else {
                    // Use checked arithmetic to prevent overflow
                    match a.checked_pow(b as u32) {
                        Some(result) => Value::Int(result),
                        None => Value::Float((a as f64).powf(b as f64)), // Overflow - fall back to float
                    }
                }
            }
            // Integer to negative power becomes float
            (Value::Int(a), Value::Int(b)) => {
                // Clamp exponent to i32 range for powi
                let exp = b.clamp(i32::MIN as i64, i32::MAX as i64) as i32;
                Value::Float((a as f64).powi(exp))
            }
            // Float to integer power
            (Value::Float(a), Value::Int(b)) => {
                // Clamp exponent to i32 range for powi
                let exp = b.clamp(i32::MIN as i64, i32::MAX as i64) as i32;
                Value::Float(a.powi(exp))
            }
            // Float to float power
            (Value::Float(a), Value::Float(b)) => Value::Float(a.powf(b)),
            // Integer base with float exponent
            (Value::Int(a), Value::Float(b)) => Value::Float((a as f64).powf(b)),
            _ => Value::Null,
        },
        // String concatenation operator
        BinaryOperator::Concat => match (&left, &right) {
            (Value::Null, _) | (_, Value::Null) => Value::Null,
            _ => {
                let left_str = value_to_string(&left);
                let right_str = value_to_string(&right);
                Value::String(format!("{}{}", left_str, right_str))
            }
        },
        // Comparison operators return Bool
        op => Value::Bool(apply_comparison(op, &left, &right)),
    }
}

/// Compare two values, returning Ordering.
pub(super) fn compare_values(left: &Value, right: &Value) -> std::cmp::Ordering {
    match (left, right) {
        (Value::Int(a), Value::Int(b)) => a.cmp(b),
        (Value::Float(a), Value::Float(b)) => a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal),
        (Value::Int(a), Value::Float(b)) => (*a as f64)
            .partial_cmp(b)
            .unwrap_or(std::cmp::Ordering::Equal),
        (Value::Float(a), Value::Int(b)) => a
            .partial_cmp(&(*b as f64))
            .unwrap_or(std::cmp::Ordering::Equal),
        (Value::String(a), Value::String(b)) => a.cmp(b),
        (Value::Bool(a), Value::Bool(b)) => a.cmp(b),
        // Null is less than everything except Null
        (Value::Null, Value::Null) => std::cmp::Ordering::Equal,
        (Value::Null, _) => std::cmp::Ordering::Less,
        (_, Value::Null) => std::cmp::Ordering::Greater,
        // Incompatible types - default to equal
        _ => std::cmp::Ordering::Equal,
    }
}

/// Convert a Value to a boolean for truthiness checks.
pub(super) fn value_to_bool(val: &Value) -> bool {
    match val {
        Value::Bool(b) => *b,
        Value::Null => false,
        Value::Int(n) => *n != 0,
        Value::Float(f) => *f != 0.0,
        Value::String(s) => !s.is_empty(),
        _ => true,
    }
}

/// Convert a Value to a string representation for concatenation.
pub(super) fn value_to_string(val: &Value) -> String {
    match val {
        Value::String(s) => s.clone(),
        Value::Int(n) => n.to_string(),
        Value::Float(f) => f.to_string(),
        Value::Bool(b) => b.to_string(),
        Value::Null => "null".to_string(),
        Value::List(items) => {
            let inner: Vec<String> = items.iter().map(value_to_string).collect();
            format!("[{}]", inner.join(", "))
        }
        Value::Map(map) => {
            let inner: Vec<String> = map
                .iter()
                .map(|(k, v)| format!("{}: {}", k, value_to_string(v)))
                .collect();
            format!("{{{}}}", inner.join(", "))
        }
        Value::Vertex(vid) => format!("Vertex({})", vid.0),
        Value::Edge(eid) => format!("Edge({})", eid.0),
        Value::Point(p) => p.to_string(),
        Value::Polygon(p) => p.to_string(),
    }
}

// =============================================================================
// Inline WHERE Expression Evaluation
// =============================================================================
//
// These functions evaluate expressions for inline WHERE clauses in patterns.
// They are designed to be called from within filter closures, taking a
// GraphSnapshot reference and an element Value.

/// Extract a property value from a vertex or edge using a storage backend.
///
/// This is a standalone version of `Compiler::extract_property` for use in closures.
pub(super) fn extract_property_from_storage(
    storage: &dyn GraphStorage,
    element: &Value,
    property: &str,
) -> Option<Value> {
    match element {
        Value::Vertex(id) => {
            let vertex = storage.get_vertex(*id)?;
            vertex.properties.get(property).cloned()
        }
        Value::Edge(id) => {
            let edge = storage.get_edge(*id)?;
            edge.properties.get(property).cloned()
        }
        Value::Null => Some(Value::Null),
        _ => None,
    }
}

/// Evaluate an expression to a Value for inline WHERE clauses.
///
/// This is a standalone version of `Compiler::evaluate_value` that takes a
/// storage reference, suitable for use within filter closures.
pub(super) fn eval_inline_value(
    storage: &dyn GraphStorage,
    expr: &Expression,
    element: &Value,
    params: &Parameters,
) -> Value {
    match expr {
        Expression::Literal(lit) => lit.clone().into(),
        Expression::Variable(_) => {
            // Return the element itself when referencing a variable
            element.clone()
        }
        Expression::Parameter(name) => {
            // Resolve parameter value
            params.get(name).cloned().unwrap_or(Value::Null)
        }
        Expression::Property { property, .. } => {
            // Extract property from the element
            extract_property_from_storage(storage, element, property).unwrap_or(Value::Null)
        }
        Expression::BinaryOp { left, op, right } => {
            let left_val = eval_inline_value(storage, left, element, params);
            let right_val = eval_inline_value(storage, right, element, params);
            apply_binary_op(*op, left_val, right_val)
        }
        Expression::UnaryOp { op, expr } => match op {
            UnaryOperator::Not => {
                let val = eval_inline_value(storage, expr, element, params);
                match val {
                    Value::Bool(b) => Value::Bool(!b),
                    _ => Value::Null,
                }
            }
            UnaryOperator::Neg => {
                let val = eval_inline_value(storage, expr, element, params);
                match val {
                    Value::Int(n) => Value::Int(-n),
                    Value::Float(f) => Value::Float(-f),
                    _ => Value::Null,
                }
            }
        },
        Expression::IsNull { expr, negated } => {
            let val = eval_inline_value(storage, expr, element, params);
            let is_null = matches!(val, Value::Null);
            Value::Bool(if *negated { !is_null } else { is_null })
        }
        Expression::InList {
            expr,
            list,
            negated,
        } => {
            let val = eval_inline_value(storage, expr, element, params);
            let in_list = list.iter().any(|item| {
                let item_val = eval_inline_value(storage, item, element, params);
                val == item_val
            });
            Value::Bool(if *negated { !in_list } else { in_list })
        }
        Expression::List(items) => {
            let values: Vec<Value> = items
                .iter()
                .map(|item| eval_inline_value(storage, item, element, params))
                .collect();
            Value::List(values)
        }
        Expression::Map(entries) => {
            let map: crate::value::ValueMap = entries
                .iter()
                .map(|(key, value_expr)| {
                    let value = eval_inline_value(storage, value_expr, element, params);
                    (key.clone(), value)
                })
                .collect();
            Value::Map(map)
        }
        // For inline WHERE, we don't support complex expressions like EXISTS, CASE, or function calls
        // These would require additional context or be expensive to evaluate per-element
        _ => Value::Null,
    }
}

/// Evaluate a predicate expression for inline WHERE clauses.
///
/// This is a standalone version of `Compiler::evaluate_predicate` that takes a
/// storage reference, suitable for use within filter closures.
pub(super) fn eval_inline_predicate(
    storage: &dyn GraphStorage,
    expr: &Expression,
    element: &Value,
    params: &Parameters,
) -> bool {
    match expr {
        Expression::BinaryOp { left, op, right } => {
            match op {
                // Logical operators
                BinaryOperator::And => {
                    eval_inline_predicate(storage, left, element, params)
                        && eval_inline_predicate(storage, right, element, params)
                }
                BinaryOperator::Or => {
                    eval_inline_predicate(storage, left, element, params)
                        || eval_inline_predicate(storage, right, element, params)
                }
                // Comparison and other operators
                _ => {
                    let left_val = eval_inline_value(storage, left, element, params);
                    let right_val = eval_inline_value(storage, right, element, params);
                    apply_comparison(*op, &left_val, &right_val)
                }
            }
        }
        Expression::UnaryOp { op, expr } => match op {
            UnaryOperator::Not => !eval_inline_predicate(storage, expr, element, params),
            UnaryOperator::Neg => {
                // Negation of a value - treat non-zero as true
                match eval_inline_value(storage, expr, element, params) {
                    Value::Int(n) => n == 0,
                    Value::Float(f) => f == 0.0,
                    Value::Bool(b) => !b,
                    Value::Null => true,
                    _ => false,
                }
            }
        },
        Expression::IsNull { expr, negated } => {
            let val = eval_inline_value(storage, expr, element, params);
            let is_null = matches!(val, Value::Null);
            if *negated {
                !is_null
            } else {
                is_null
            }
        }
        Expression::InList {
            expr,
            list,
            negated,
        } => {
            let val = eval_inline_value(storage, expr, element, params);
            let in_list = list.iter().any(|item| {
                let item_val = eval_inline_value(storage, item, element, params);
                val == item_val
            });
            if *negated {
                !in_list
            } else {
                in_list
            }
        }
        // For other expressions, evaluate and check truthiness
        _ => {
            let val = eval_inline_value(storage, expr, element, params);
            value_to_bool(&val)
        }
    }
}