kglite 0.16.4

Pure-Rust embedded Cypher knowledge graph engine with in-memory, mmap, and disk storage, and agent-facing schema introspection
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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
//! Bind label / relationship-type positions written as parameters.
//!
//! `MATCH (n:$label)`, `MATCH (n:$(label))`, `-[:$type]->`, `CREATE (n:$label)`,
//! `SET n:$label`, `REMOVE n:$label`, `WHERE n:$label`.
//!
//! ## Why this is a resolution pass and not a planner/executor feature
//!
//! A parameter's value is fixed for the whole statement — it cannot vary per
//! row — so a dynamic label is *knowable before planning*. Substituting it
//! here, immediately after parse and before schema validation, means the
//! planner and the executor never learn that the feature exists: every pass
//! that reads a label (schema warnings, index selection, join ordering, the
//! `skip_target_type_check` annotation, fusion admission) keeps seeing a
//! literal, and none of them needs an unknown-until-bind case. The alternative
//! — a label variant threaded through to execution — would have put an
//! "unknown label" branch into each of those, where a missed branch
//! over-returns rows.
//!
//! What the parser *cannot* do is substitute directly, because parsed ASTs are
//! cached by query text and the same text is re-run with different parameters.
//! So the parser records the reference out of band
//! ([`crate::graph::core::pattern_matching::ParamLabel`]) and this pass, which
//! runs per execution with the caller's parameters in hand, writes the bound
//! name into the string slot and clears the marker.
//!
//! ## The property this buys callers
//!
//! A parameter value becomes a *name*, never grammar. It is written into an
//! already-parsed AST slot, so no spelling of it — backticks, braces, a closing
//! paren, another label — can restructure the query. Together with value
//! parameters, that removes the last position where a caller had to escape
//! untrusted input into Cypher text.
//!
//! Cache interaction, verified: a parameterised statement is never entered into
//! the plan cache (`session::execute::prepare` gates insertion on
//! `params.is_empty()`), and the parse cache stores the *pre*-resolution AST
//! and hands out clones, so a resolved label can never be served to a later
//! call with different parameters.

// Every function below is one step of the same walk and returns
// `Result<(), KgError>`; KgError carries structured query context, so it trips
// `result_large_err` uniformly. Boxing it here would change the signature of
// every caller in the prepare path, which threads the unboxed error — so the
// allowance is module-scoped once rather than repeated on each step.
#![allow(clippy::result_large_err)]

use std::collections::HashMap;

use super::ast::*;
use crate::datatypes::values::Value;
use crate::error::KgError;
use crate::graph::core::pattern_matching::{ParamLabel, Pattern, PatternElement};

/// Bind every parameterised label / relationship type in `query` against
/// `params`. Idempotent: a query with no parameterised names is walked and
/// left untouched.
///
/// Errors when a referenced parameter is missing or is not a string — a
/// dynamic label has no sensible fallback, and silently matching nothing would
/// hide the caller's bug behind an empty result.
pub fn resolve(query: &mut CypherQuery, params: &HashMap<String, Value>) -> Result<(), KgError> {
    resolve_clauses(&mut query.clauses, params)
}

/// Look up one parameter and validate it as a name.
fn bind<'a>(params: &'a HashMap<String, Value>, param: &str) -> Result<&'a str, KgError> {
    match params.get(param) {
        Some(Value::String(name)) => Ok(name),
        Some(other) => Err(execution_error(format!(
            "Parameter ${param} is used as a label or relationship type, so it must be a \
             string, but a {} was supplied.",
            other.type_name()
        ))),
        None => Err(execution_error(format!(
            "Missing parameter: ${param} (used as a label or relationship type)"
        ))),
    }
}

fn execution_error(message: String) -> KgError {
    KgError::CypherExecution {
        message,
        position: None,
    }
}

/// Write `params` into the `slots` a pattern's markers point at.
///
/// `slots(i)` yields the string slot for marker slot `i`; a marker whose slot
/// no longer exists is impossible (the parser numbers them from the same list
/// it fills) and is skipped rather than panicking.
fn apply(
    markers: &mut Vec<ParamLabel>,
    params: &HashMap<String, Value>,
    mut slot: impl FnMut(usize, &str),
) -> Result<(), KgError> {
    for marker in markers.iter() {
        let name = bind(params, &marker.param)?;
        slot(marker.slot, name);
    }
    markers.clear();
    Ok(())
}

/// One label slot, for the `SET`/`REMOVE`/`WHERE` forms that carry a single
/// name and a single optional marker.
fn apply_one(
    label: &mut String,
    marker: &mut Option<String>,
    params: &HashMap<String, Value>,
) -> Result<(), KgError> {
    if let Some(param) = marker.take() {
        *label = bind(params, &param)?.to_string();
    }
    Ok(())
}

fn resolve_clauses(clauses: &mut [Clause], params: &HashMap<String, Value>) -> Result<(), KgError> {
    for clause in clauses.iter_mut() {
        match clause {
            Clause::Match(m) | Clause::OptionalMatch(m) => {
                for pattern in &mut m.patterns {
                    resolve_pattern(pattern, params)?;
                }
                if let Some(wc) = &mut m.where_clause {
                    resolve_predicate(&mut wc.predicate, params)?;
                }
            }
            Clause::Where(w) => resolve_predicate(&mut w.predicate, params)?,
            Clause::With(w) => {
                for item in &mut w.items {
                    resolve_return_item(item, params)?;
                }
                if let Some(wc) = &mut w.where_clause {
                    resolve_predicate(&mut wc.predicate, params)?;
                }
            }
            Clause::Return(r) => {
                for item in &mut r.items {
                    resolve_return_item(item, params)?;
                }
            }
            Clause::Create(c) => {
                for pattern in &mut c.patterns {
                    resolve_create_elements(&mut pattern.elements, params)?;
                }
            }
            Clause::Merge(m) => {
                resolve_create_elements(&mut m.pattern.elements, params)?;
                for items in [m.on_create.as_mut(), m.on_match.as_mut()]
                    .into_iter()
                    .flatten()
                {
                    resolve_set_items(items, params)?;
                }
            }
            Clause::Set(s) => resolve_set_items(&mut s.items, params)?,
            Clause::Remove(r) => {
                for item in &mut r.items {
                    if let RemoveItem::Label {
                        label, label_param, ..
                    } = item
                    {
                        apply_one(label, label_param, params)?;
                    }
                }
            }
            Clause::Foreach { body, .. } => resolve_clauses(body, params)?,
            Clause::CallSubquery { body, .. } => resolve_clauses(&mut body.clauses, params)?,
            Clause::Union(u) => resolve_clauses(&mut u.query.clauses, params)?,
            // Every remaining clause is either name-free (ORDER BY, SKIP,
            // LIMIT, UNWIND, DELETE, LOAD CSV, CALL, schema DDL) or a fused
            // shape, which only the optimizer builds — and the optimizer runs
            // after this pass, so a fused clause is unreachable here.
            _ => {}
        }
    }
    Ok(())
}

fn resolve_pattern(pattern: &mut Pattern, params: &HashMap<String, Value>) -> Result<(), KgError> {
    for element in &mut pattern.elements {
        match element {
            PatternElement::Node(node) => {
                if node.label_params.is_empty() {
                    continue;
                }
                let mut markers = std::mem::take(&mut node.label_params);
                apply(&mut markers, params, |slot, name| match slot {
                    0 => node.node_type = Some(name.to_string()),
                    n => {
                        if let Some(extra) = node.extra_labels.get_mut(n - 1) {
                            *extra = name.to_string();
                        }
                    }
                })?;
            }
            PatternElement::Edge(edge) => {
                if edge.type_params.is_empty() {
                    continue;
                }
                let mut markers = std::mem::take(&mut edge.type_params);
                apply(&mut markers, params, |slot, name| {
                    if let Some(types) = &mut edge.connection_types {
                        if let Some(ty) = types.get_mut(slot) {
                            *ty = name.to_string();
                        }
                    }
                    // `connection_type` holds the first branch even when an
                    // alternation is present, so slot 0 writes both.
                    if slot == 0 {
                        edge.connection_type = Some(name.to_string());
                    }
                })?;
            }
        }
    }
    Ok(())
}

fn resolve_create_elements(
    elements: &mut [CreateElement],
    params: &HashMap<String, Value>,
) -> Result<(), KgError> {
    for element in elements.iter_mut() {
        match element {
            CreateElement::Node(node) => {
                if node.label_params.is_empty() {
                    continue;
                }
                let mut markers = std::mem::take(&mut node.label_params);
                apply(&mut markers, params, |slot, name| match slot {
                    0 => node.label = Some(name.to_string()),
                    n => {
                        if let Some(extra) = node.extra_labels.get_mut(n - 1) {
                            *extra = name.to_string();
                        }
                    }
                })?;
            }
            CreateElement::Edge(edge) => {
                if let Some(param) = edge.type_param.take() {
                    edge.connection_type = bind(params, &param)?.to_string();
                }
            }
        }
    }
    Ok(())
}

fn resolve_set_items(
    items: &mut [SetItem],
    params: &HashMap<String, Value>,
) -> Result<(), KgError> {
    for item in items.iter_mut() {
        match item {
            SetItem::Label {
                label, label_param, ..
            } => apply_one(label, label_param, params)?,
            SetItem::Property { expression, .. } | SetItem::Map { expression, .. } => {
                resolve_expression(expression, params)?
            }
        }
    }
    Ok(())
}

fn resolve_return_item(
    item: &mut ReturnItem,
    params: &HashMap<String, Value>,
) -> Result<(), KgError> {
    resolve_expression(&mut item.expression, params)
}

fn resolve_predicate(pred: &mut Predicate, params: &HashMap<String, Value>) -> Result<(), KgError> {
    match pred {
        Predicate::LabelCheck {
            label, label_param, ..
        } => apply_one(label, label_param, params)?,
        Predicate::Exists {
            patterns,
            where_clause,
            ..
        } => {
            for pattern in patterns.iter_mut() {
                resolve_pattern(pattern, params)?;
            }
            if let Some(inner) = where_clause {
                resolve_predicate(inner, params)?;
            }
        }
        Predicate::And(l, r) | Predicate::Or(l, r) | Predicate::Xor(l, r) => {
            resolve_predicate(l, params)?;
            resolve_predicate(r, params)?;
        }
        Predicate::Not(inner) => resolve_predicate(inner, params)?,
        Predicate::Comparison { left, right, .. } => {
            resolve_expression(left, params)?;
            resolve_expression(right, params)?;
        }
        Predicate::IsNull(expr)
        | Predicate::IsNotNull(expr)
        | Predicate::InLiteralSet { expr, .. } => resolve_expression(expr, params)?,
        Predicate::In { expr, list } => {
            resolve_expression(expr, params)?;
            for item in list.iter_mut() {
                resolve_expression(item, params)?;
            }
        }
        Predicate::StartsWith { expr, pattern }
        | Predicate::EndsWith { expr, pattern }
        | Predicate::Contains { expr, pattern } => {
            resolve_expression(expr, params)?;
            resolve_expression(pattern, params)?;
        }
        Predicate::InExpression { expr, list_expr } => {
            resolve_expression(expr, params)?;
            resolve_expression(list_expr, params)?;
        }
    }
    Ok(())
}

/// Walk an expression for the constructs that can nest a name position: a
/// predicate expression (`n:$label`, an inline pattern), a `COUNT { }`
/// subquery, and the binders that carry a predicate of their own. Everything
/// with no predicate or pattern under it is delegated to
/// [`resolve_operand_expressions`], which exists only to reach these.
fn resolve_expression(
    expr: &mut Expression,
    params: &HashMap<String, Value>,
) -> Result<(), KgError> {
    match expr {
        Expression::PredicateExpr(pred) => resolve_predicate(pred, params)?,
        Expression::CountSubquery {
            patterns,
            where_clause,
            ..
        } => {
            for pattern in patterns.iter_mut() {
                resolve_pattern(pattern, params)?;
            }
            if let Some(inner) = where_clause {
                resolve_predicate(inner, params)?;
            }
        }
        Expression::Case {
            operand,
            when_clauses,
            else_expr,
        } => {
            for inner in operand.iter_mut().chain(else_expr.iter_mut()) {
                resolve_expression(inner, params)?;
            }
            for (when, then) in when_clauses.iter_mut() {
                match when {
                    CaseCondition::Predicate(pred) => resolve_predicate(pred, params)?,
                    CaseCondition::Expression(expr) => resolve_expression(expr, params)?,
                }
                resolve_expression(then, params)?;
            }
        }
        Expression::ListComprehension {
            list_expr,
            filter,
            map_expr,
            ..
        } => {
            resolve_expression(list_expr, params)?;
            if let Some(filter) = filter {
                resolve_predicate(filter, params)?;
            }
            if let Some(map_expr) = map_expr {
                resolve_expression(map_expr, params)?;
            }
        }
        Expression::QuantifiedList {
            list_expr, filter, ..
        } => {
            resolve_expression(list_expr, params)?;
            resolve_predicate(filter, params)?;
        }
        other => resolve_operand_expressions(other, params)?,
    }
    Ok(())
}

/// The purely structural half of the expression walk: variants that can only
/// contain further *expressions*, recursed so a nested predicate or pattern
/// deeper down still gets reached.
fn resolve_operand_expressions(
    expr: &mut Expression,
    params: &HashMap<String, Value>,
) -> Result<(), KgError> {
    match expr {
        Expression::Add(l, r)
        | Expression::Subtract(l, r)
        | Expression::Multiply(l, r)
        | Expression::Divide(l, r)
        | Expression::Modulo(l, r)
        | Expression::Concat(l, r) => {
            resolve_expression(l, params)?;
            resolve_expression(r, params)?;
        }
        Expression::Negate(inner)
        | Expression::IsNull(inner)
        | Expression::IsNotNull(inner)
        | Expression::ExprPropertyAccess { expr: inner, .. } => resolve_expression(inner, params)?,
        Expression::FunctionCall { args, .. } | Expression::ListLiteral(args) => {
            for arg in args.iter_mut() {
                resolve_expression(arg, params)?;
            }
        }
        Expression::IndexAccess { expr, index } => {
            resolve_expression(expr, params)?;
            resolve_expression(index, params)?;
        }
        Expression::ListSlice { expr, start, end } => {
            resolve_expression(expr, params)?;
            for inner in start.iter_mut().chain(end.iter_mut()) {
                resolve_expression(inner, params)?;
            }
        }
        Expression::MapLiteral(entries) => {
            for (_, value) in entries.iter_mut() {
                resolve_expression(value, params)?;
            }
        }
        Expression::MapProjection { items, .. } => {
            for item in items.iter_mut() {
                if let MapProjectionItem::Alias { expr, .. } = item {
                    resolve_expression(expr, params)?;
                }
            }
        }
        Expression::Reduce {
            init,
            list_expr,
            body,
            ..
        } => {
            resolve_expression(init, params)?;
            resolve_expression(list_expr, params)?;
            resolve_expression(body, params)?;
        }
        Expression::WindowFunction {
            partition_by,
            order_by,
            ..
        } => {
            for inner in partition_by.iter_mut() {
                resolve_expression(inner, params)?;
            }
            for item in order_by.iter_mut() {
                resolve_expression(&mut item.expression, params)?;
            }
        }
        // Leaves: no nested expression, no name position. The four variants
        // `resolve_expression` handles itself are unreachable here.
        _ => {}
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::graph::core::pattern_matching::PatternElement;

    fn parse(query: &str) -> CypherQuery {
        super::super::parser::parse_cypher(query).expect("parse")
    }

    fn params(pairs: &[(&str, Value)]) -> HashMap<String, Value> {
        pairs
            .iter()
            .map(|(k, v)| (k.to_string(), v.clone()))
            .collect()
    }

    fn first_node_type(query: &CypherQuery) -> Option<String> {
        for clause in &query.clauses {
            if let Clause::Match(m) = clause {
                if let Some(PatternElement::Node(n)) = m.patterns[0].elements.first() {
                    return n.node_type.clone();
                }
            }
        }
        None
    }

    /// Before resolution the slot holds the source spelling, so an unresolved
    /// pattern names a type nothing has — it under-returns, never over-returns.
    #[test]
    fn an_unresolved_slot_parks_the_source_spelling() {
        let query = parse("MATCH (n:$label) RETURN n");
        assert_eq!(first_node_type(&query).as_deref(), Some("$label"));
    }

    #[test]
    fn resolution_writes_the_bound_name_and_clears_the_marker() {
        let mut query = parse("MATCH (n:$label) RETURN n");
        resolve(
            &mut query,
            &params(&[("label", Value::String("Person".into()))]),
        )
        .unwrap();
        assert_eq!(first_node_type(&query).as_deref(), Some("Person"));

        let Clause::Match(m) = &query.clauses[0] else {
            panic!("expected MATCH");
        };
        let Some(PatternElement::Node(n)) = m.patterns[0].elements.first() else {
            panic!("expected node");
        };
        assert!(n.label_params.is_empty(), "marker must be cleared");
    }

    /// A literal label spelled `` `$label` `` is a name, not a reference — the
    /// marker is out of band, so no spelling can forge one.
    #[test]
    fn a_backticked_dollar_label_is_never_treated_as_a_reference() {
        let mut query = parse("MATCH (n:`$label`) RETURN n");
        resolve(
            &mut query,
            &params(&[("label", Value::String("Person".into()))]),
        )
        .unwrap();
        assert_eq!(first_node_type(&query).as_deref(), Some("$label"));
    }

    #[test]
    fn a_missing_parameter_is_an_error() {
        let mut query = parse("MATCH (n:$label) RETURN n");
        let err = resolve(&mut query, &HashMap::new()).unwrap_err();
        assert!(err.to_string().contains("$label"), "{err}");
    }

    #[test]
    fn a_non_string_parameter_is_an_error() {
        let mut query = parse("MATCH (n:$label) RETURN n");
        let err = resolve(&mut query, &params(&[("label", Value::Int64(7))])).unwrap_err();
        assert!(err.to_string().contains("string"), "{err}");
    }

    #[test]
    fn resolution_reaches_every_name_position() {
        let bound = params(&[
            ("label", Value::String("Person".into())),
            ("type", Value::String("KNOWS".into())),
        ]);
        for query in [
            "MATCH (n:$label) RETURN n",
            "MATCH (n:Person:$label) RETURN n",
            "MATCH (a)-[:$type]->(b) RETURN a",
            "MATCH (a)-[:KNOWS|$type]->(b) RETURN a",
            "MATCH (a) WHERE EXISTS { MATCH (a)-[:$type]->(:$label) } RETURN a",
            "MATCH (a) WHERE a:$label RETURN a",
            "MATCH (a) RETURN COUNT { (a)-[:$type]->(:$label) } AS n",
            "CREATE (n:$label {id: 1})",
            "MATCH (a), (b) CREATE (a)-[:$type]->(b)",
            "MERGE (n:$label {id: 1})",
            "MATCH (n) SET n:$label",
            "MATCH (n) REMOVE n:$label",
            "MATCH (n) FOREACH (x IN [1] | SET n:$label)",
            "CALL { MATCH (n:$label) RETURN n } RETURN n",
            "MATCH (n:$label) RETURN n UNION MATCH (m:$label) RETURN m",
        ] {
            let mut parsed = parse(query);
            resolve(&mut parsed, &bound).unwrap_or_else(|e| panic!("{query}: {e}"));
            let rendered = format!("{:?}", parsed);
            assert!(
                !rendered.contains("$label") && !rendered.contains("$type"),
                "{query} left an unresolved name position: {rendered}"
            );
        }
    }
}