uqa-graph 0.3.0

Graph store, RPQ, Cypher (lexer/parser/AST/compiler), graph algorithms
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
//
// Unified Query Algebra
//
// Copyright (c) 2023-2026 Cognica, Inc.
//

//! Shared Cypher value, sorting, aggregate, arithmetic, and string helpers.

use super::{
    agtype, exact_i64_to_f64, usize_to_i64, CypherError, CypherExpr, OrderByItem, PathElement,
    PathPattern, ReturnItem, Value,
};

// ------------------------------------------------------------------
// Helpers
// ------------------------------------------------------------------

pub(super) fn validated_path_elements(value: &Value) -> Result<&[Value], CypherError> {
    let elements = agtype::path_elements(value)
        .ok_or_else(|| CypherError::Storage("path entity is missing its elements".into()))?;
    if elements.is_empty() || elements.len().is_multiple_of(2) {
        return Err(CypherError::Storage(format!(
            "path entity has invalid element count {}",
            elements.len()
        )));
    }
    for (index, element) in elements.iter().enumerate() {
        let expected = if index.is_multiple_of(2) {
            agtype::EntityKind::Vertex
        } else {
            agtype::EntityKind::Edge
        };
        if agtype::entity_kind(element) != Some(expected) {
            return Err(CypherError::Storage(format!(
                "path entity element {index} is not a {}",
                if index.is_multiple_of(2) {
                    "vertex"
                } else {
                    "relationship"
                }
            )));
        }
    }
    Ok(elements)
}

/// Variables declared by a set of path patterns (node, relationship,
/// and path variables), used to pad OPTIONAL MATCH misses with nulls.
pub(super) fn pattern_variables(patterns: &[PathPattern]) -> Vec<String> {
    let mut vars = Vec::new();
    for pattern in patterns {
        if let Some(v) = &pattern.variable {
            vars.push(v.clone());
        }
        for element in &pattern.elements {
            match element {
                PathElement::Node(np) => {
                    if let Some(v) = &np.variable {
                        vars.push(v.clone());
                    }
                }
                PathElement::Rel(rp) => {
                    if let Some(v) = &rp.variable {
                        vars.push(v.clone());
                    }
                }
            }
        }
    }
    vars
}

pub(super) fn null_or_bool(lhs: &Value, rhs: &Value, result: bool) -> Value {
    if *lhs == Value::Null || *rhs == Value::Null {
        Value::Null
    } else {
        Value::Bool(result)
    }
}

pub(super) fn sort_keyed<R>(keyed: &mut [(Vec<Value>, R)], order: &[OrderByItem]) {
    keyed.sort_by(|a, b| {
        for (i, (av, bv)) in a.0.iter().zip(b.0.iter()).enumerate() {
            let cmp = agtype::cmp(av, bv);
            let cmp = if order.get(i).is_some_and(|o| !o.ascending) {
                cmp.reverse()
            } else {
                cmp
            };
            if cmp != std::cmp::Ordering::Equal {
                return cmp;
            }
        }
        std::cmp::Ordering::Equal
    });
}

pub(super) fn return_label(item: &ReturnItem, position: usize) -> String {
    if let Some(alias) = &item.alias {
        return alias.clone();
    }
    match &item.expr {
        CypherExpr::Variable(v) => v.name.clone(),
        CypherExpr::PropertyAccess(p) => format!("{}.{}", p.variable, p.keys.join(".")),
        CypherExpr::FunctionCall(f) => f.name.clone(),
        _ => format!("expr_{position}"),
    }
}

pub(super) fn is_aggregate(expr: &CypherExpr) -> bool {
    if let CypherExpr::FunctionCall(fc) = expr {
        is_aggregate_name(&fc.name)
    } else {
        false
    }
}

pub(super) fn is_aggregate_name(name: &str) -> bool {
    matches!(
        name.to_lowercase().as_str(),
        "count" | "sum" | "avg" | "min" | "max" | "collect"
    )
}

pub(super) fn number_as_f64(v: &Value) -> Result<Option<f64>, CypherError> {
    match v {
        Value::Int(n) => exact_i64_to_f64(*n, "integer operand").map(Some),
        Value::Float(f) => Ok(Some(*f)),
        Value::Decimal(d) => d.to_f64().map(Some).ok_or_else(|| {
            CypherError::TypeError(format!(
                "numeric value {d:?} cannot be represented as a float"
            ))
        }),
        _ => Ok(None),
    }
}

/// min / max over non-null values in agtype order, preserving the
/// original value type. Empty input yields null.
pub(super) fn aggregate_extreme(values: &[Value], want_min: bool) -> Value {
    let mut best: Option<&Value> = None;
    for v in values {
        let replace = match best {
            None => true,
            Some(current) => {
                let cmp = agtype::cmp(v, current);
                if want_min {
                    cmp == std::cmp::Ordering::Less
                } else {
                    cmp == std::cmp::Ordering::Greater
                }
            }
        };
        if replace {
            best = Some(v);
        }
    }
    best.cloned().unwrap_or(Value::Null)
}

/// sum keeps integer typing while every input is an integer (AGE:
/// `sum([1,2,3])` = 6, `sum([1,2.5])` = 3.5); empty input yields null.
pub(super) fn aggregate_sum(values: &[Value]) -> Result<Value, CypherError> {
    if values.is_empty() {
        return Ok(Value::Null);
    }
    if values.iter().all(|value| matches!(value, Value::Int(_))) {
        let mut sum = 0_i64;
        for value in values {
            let Value::Int(integer) = value else {
                return Err(CypherError::Storage(
                    "integer aggregate validation became inconsistent".into(),
                ));
            };
            sum = sum.wrapping_add(*integer);
        }
        return Ok(Value::Int(sum));
    }

    let mut sum = 0.0;
    for value in values {
        sum += number_as_f64(value)?
            .ok_or_else(|| CypherError::TypeError("arguments must resolve to a number".into()))?;
    }
    Ok(Value::Float(sum))
}

pub(super) fn aggregate_avg(values: &[Value]) -> Result<Value, CypherError> {
    if values.is_empty() {
        return Ok(Value::Null);
    }
    let mut total = 0.0;
    for v in values {
        total += number_as_f64(v)?
            .ok_or_else(|| CypherError::TypeError("arguments must resolve to a number".into()))?;
    }
    let count = exact_i64_to_f64(
        usize_to_i64(values.len(), "average count")?,
        "average count",
    )?;
    Ok(Value::Float(total / count))
}

/// Concatenation contribution of a scalar joined to a string with `+`.
/// AGE quirk (verified): booleans contribute an empty string.
pub(super) fn concat_fragment(v: &Value) -> Option<String> {
    match v {
        Value::Str(s) => Some(s.clone()),
        Value::Int(n) => Some(n.to_string()),
        Value::Float(f) => Some(agtype::format_float_pg(*f)),
        Value::Bool(_) => Some(String::new()),
        _ => None,
    }
}

pub(super) fn agtype_add(lhs: &Value, rhs: &Value) -> Result<Value, CypherError> {
    if *lhs == Value::Null || *rhs == Value::Null {
        return Ok(Value::Null);
    }
    match (lhs, rhs) {
        (Value::Int(a), Value::Int(b)) => Ok(Value::Int(a.wrapping_add(*b))),
        (Value::List(a), Value::List(b)) => {
            let mut out = a.clone();
            out.extend(b.iter().cloned());
            Ok(Value::List(out))
        }
        // `[1, 2] + 3` appends, `3 + [1, 2]` prepends.
        (Value::List(a), b) => {
            let mut out = a.clone();
            out.push(b.clone());
            Ok(Value::List(out))
        }
        (a, Value::List(b)) => {
            let mut out = vec![a.clone()];
            out.extend(b.iter().cloned());
            Ok(Value::List(out))
        }
        (Value::Map(a), Value::Map(b)) => {
            let mut out = a.clone();
            for (k, v) in b {
                out.insert(k.clone(), v.clone());
            }
            Ok(Value::Map(out))
        }
        (Value::Str(_), _) | (_, Value::Str(_)) => {
            match (concat_fragment(lhs), concat_fragment(rhs)) {
                (Some(a), Some(b)) => Ok(Value::Str(format!("{a}{b}"))),
                _ => Err(CypherError::TypeError(
                    "Invalid input parameter types for agtype_add".into(),
                )),
            }
        }
        _ => match (number_as_f64(lhs)?, number_as_f64(rhs)?) {
            (Some(a), Some(b)) => Ok(Value::Float(a + b)),
            _ => Err(CypherError::TypeError(
                "Invalid input parameter types for agtype_add".into(),
            )),
        },
    }
}

pub(super) fn numeric_op(
    lhs: &Value,
    rhs: &Value,
    age_name: &str,
    f_int: impl Fn(i64, i64) -> i64,
    f_float: impl Fn(f64, f64) -> f64,
) -> Result<Value, CypherError> {
    if *lhs == Value::Null || *rhs == Value::Null {
        return Ok(Value::Null);
    }
    if let (Value::Int(a), Value::Int(b)) = (lhs, rhs) {
        return Ok(Value::Int(f_int(*a, *b)));
    }
    match (number_as_f64(lhs)?, number_as_f64(rhs)?) {
        (Some(a), Some(b)) => Ok(Value::Float(f_float(a, b))),
        _ => Err(CypherError::TypeError(format!(
            "Invalid input parameter types for {age_name}"
        ))),
    }
}

pub(super) fn agtype_div(lhs: &Value, rhs: &Value) -> Result<Value, CypherError> {
    if *lhs == Value::Null || *rhs == Value::Null {
        return Ok(Value::Null);
    }
    if let (Value::Int(a), Value::Int(b)) = (lhs, rhs) {
        if *b == 0 {
            return Err(CypherError::TypeError("division by zero".into()));
        }
        return Ok(Value::Int(a.wrapping_div(*b)));
    }
    match (number_as_f64(lhs)?, number_as_f64(rhs)?) {
        (Some(a), Some(b)) => {
            if b == 0.0 {
                return Err(CypherError::TypeError("division by zero".into()));
            }
            Ok(Value::Float(a / b))
        }
        _ => Err(CypherError::TypeError(
            "Invalid input parameter types for agtype_div".into(),
        )),
    }
}

pub(super) fn agtype_mod(lhs: &Value, rhs: &Value) -> Result<Value, CypherError> {
    if *lhs == Value::Null || *rhs == Value::Null {
        return Ok(Value::Null);
    }
    if let (Value::Int(a), Value::Int(b)) = (lhs, rhs) {
        // AGE quirk (verified on 1.6.0): integer modulo by zero
        // returns the dividend instead of raising.
        if *b == 0 {
            return Ok(Value::Int(*a));
        }
        return Ok(Value::Int(a.wrapping_rem(*b)));
    }
    match (number_as_f64(lhs)?, number_as_f64(rhs)?) {
        // fmod semantics: sign follows the dividend; x % 0.0 = NaN.
        (Some(a), Some(b)) => Ok(Value::Float(a % b)),
        _ => Err(CypherError::TypeError(
            "Invalid input parameter types for agtype_mod".into(),
        )),
    }
}

pub(super) fn agtype_pow(lhs: &Value, rhs: &Value) -> Result<Value, CypherError> {
    if *lhs == Value::Null || *rhs == Value::Null {
        return Ok(Value::Null);
    }
    match (number_as_f64(lhs)?, number_as_f64(rhs)?) {
        // `^` ALWAYS yields a float in AGE (2^2 = 4.0).
        (Some(a), Some(b)) => Ok(Value::Float(a.powf(b))),
        _ => Err(CypherError::TypeError(
            "Invalid input parameter types for agtype_pow".into(),
        )),
    }
}

/// STARTS WITH / ENDS WITH / CONTAINS: null propagates, non-string
/// operands compare false (verified: `'abc' STARTS WITH 1` = false).
pub(super) fn str_predicate(lhs: &Value, rhs: &Value, f: impl Fn(&str, &str) -> bool) -> Value {
    match (lhs, rhs) {
        (Value::Null, _) | (_, Value::Null) => Value::Null,
        (Value::Str(a), Value::Str(b)) => Value::Bool(f(a, b)),
        _ => Value::Bool(false),
    }
}

/// `=~` is an UNANCHORED regular-expression search in AGE
/// (`PostgreSQL` `~` semantics): `'abc' =~ 'b'` is true. Non-string
/// operands (including null) yield null.
pub(super) fn regex_match(lhs: &Value, rhs: &Value) -> Result<Value, CypherError> {
    match (lhs, rhs) {
        (Value::Str(a), Value::Str(pattern)) => {
            let re = regex::Regex::new(pattern)
                .map_err(|e| CypherError::TypeError(format!("invalid regular expression: {e}")))?;
            Ok(Value::Bool(re.is_match(a)))
        }
        _ => Ok(Value::Null),
    }
}

pub(super) fn unsupported_argument(function: &str, value: &Value) -> CypherError {
    CypherError::TypeError(format!(
        "{function}() unsupported argument agtype {}",
        agtype::agtype_type_ordinal(value)
    ))
}

pub(super) fn string_fn(
    arg: Option<&Value>,
    name: &str,
    f: impl Fn(&str) -> String,
) -> Result<Value, CypherError> {
    match arg {
        Some(Value::Null) | None => Ok(Value::Null),
        Some(Value::Str(s)) => Ok(Value::Str(f(s))),
        Some(v) => Err(unsupported_argument(name, v)),
    }
}

/// Numeric function that always yields a float (AGE: `ceil(2)` = 2.0).
pub(super) fn float_fn(
    arg: Option<&Value>,
    name: &str,
    f: impl Fn(f64) -> f64,
) -> Result<Value, CypherError> {
    match arg {
        Some(Value::Null) | None => Ok(Value::Null),
        Some(v) => match number_as_f64(v)? {
            Some(x) => Ok(Value::Float(f(x))),
            None => Err(unsupported_argument(name, v)),
        },
    }
}

/// Numeric function with a restricted domain; out-of-domain inputs
/// return null (AGE: `sqrt(-1)` = null, `log(0)` = null).
pub(super) fn domain_float_fn(
    arg: Option<&Value>,
    name: &str,
    f: impl Fn(f64) -> Option<f64>,
) -> Result<Value, CypherError> {
    match arg {
        Some(Value::Null) | None => Ok(Value::Null),
        Some(v) => match number_as_f64(v)? {
            Some(x) => Ok(f(x).map_or(Value::Null, Value::Float)),
            None => Err(unsupported_argument(name, v)),
        },
    }
}