uni-query 1.1.0

OpenCypher query parser, planner, and vectorized executor for Uni
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
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
/// Expression tree walker for applying rewrite rules
use crate::query::rewrite::context::RewriteContext;
use crate::query::rewrite::error::RewriteError;
use crate::query::rewrite::registry::RewriteRegistry;
use uni_cypher::ast::{Expr, MapProjectionItem, Query, Statement};

/// Walks expression trees and applies rewrite rules
pub struct ExpressionWalker<'a> {
    registry: &'a RewriteRegistry,
    context: RewriteContext,
}

impl<'a> ExpressionWalker<'a> {
    /// Create a new expression walker
    pub fn new(registry: &'a RewriteRegistry, context: RewriteContext) -> Self {
        Self { registry, context }
    }

    /// Get the rewrite context (for accessing statistics)
    pub fn context(&self) -> &RewriteContext {
        &self.context
    }

    /// Get a mutable reference to the rewrite context
    pub fn context_mut(&mut self) -> &mut RewriteContext {
        &mut self.context
    }

    /// Take ownership of the context (for retrieving statistics)
    pub fn into_context(self) -> RewriteContext {
        self.context
    }

    /// Rewrite a complete statement
    pub fn rewrite_statement(&mut self, stmt: Statement) -> Statement {
        Statement {
            clauses: stmt
                .clauses
                .into_iter()
                .map(|c| self.rewrite_clause(c))
                .collect(),
        }
    }

    /// Rewrite a query
    pub fn rewrite_query(&mut self, query: Query) -> Query {
        match query {
            Query::Single(stmt) => Query::Single(self.rewrite_statement(stmt)),
            Query::Union { left, right, all } => Query::Union {
                left: Box::new(self.rewrite_query(*left)),
                right: Box::new(self.rewrite_query(*right)),
                all,
            },
            Query::Schema(schema_cmd) => Query::Schema(schema_cmd),
            Query::Explain(inner) => Query::Explain(Box::new(self.rewrite_query(*inner))),
            Query::TimeTravel { .. } => {
                unreachable!("TimeTravel should be resolved at API layer before rewriting")
            }
        }
    }

    /// Rewrite a clause
    fn rewrite_clause(&mut self, clause: uni_cypher::ast::Clause) -> uni_cypher::ast::Clause {
        use uni_cypher::ast::Clause;

        match clause {
            Clause::Match(m) => Clause::Match(self.rewrite_match_clause(m)),
            Clause::Create(c) => Clause::Create(self.rewrite_create_clause(c)),
            Clause::Return(r) => Clause::Return(self.rewrite_return_clause(r)),
            Clause::With(w) => Clause::With(self.rewrite_with_clause(w)),
            Clause::Unwind(u) => Clause::Unwind(self.rewrite_unwind_clause(u)),
            Clause::Set(s) => Clause::Set(self.rewrite_set_clause(s)),
            Clause::Delete(d) => Clause::Delete(self.rewrite_delete_clause(d)),
            Clause::Remove(r) => Clause::Remove(self.rewrite_remove_clause(r)),
            // Other clauses that don't contain expressions or are not yet handled
            other => other,
        }
    }

    fn rewrite_match_clause(
        &mut self,
        m: uni_cypher::ast::MatchClause,
    ) -> uni_cypher::ast::MatchClause {
        uni_cypher::ast::MatchClause {
            optional: m.optional,
            pattern: self.rewrite_pattern(m.pattern),
            where_clause: m.where_clause.map(|e| self.rewrite_expr(e)),
        }
    }

    fn rewrite_create_clause(
        &mut self,
        c: uni_cypher::ast::CreateClause,
    ) -> uni_cypher::ast::CreateClause {
        uni_cypher::ast::CreateClause {
            pattern: self.rewrite_pattern(c.pattern),
        }
    }

    fn rewrite_delete_clause(
        &mut self,
        d: uni_cypher::ast::DeleteClause,
    ) -> uni_cypher::ast::DeleteClause {
        uni_cypher::ast::DeleteClause {
            detach: d.detach,
            items: d.items.into_iter().map(|e| self.rewrite_expr(e)).collect(),
        }
    }

    fn rewrite_set_clause(&mut self, s: uni_cypher::ast::SetClause) -> uni_cypher::ast::SetClause {
        uni_cypher::ast::SetClause {
            items: s
                .items
                .into_iter()
                .map(|item| self.rewrite_set_item(item))
                .collect(),
        }
    }

    fn rewrite_set_item(&mut self, item: uni_cypher::ast::SetItem) -> uni_cypher::ast::SetItem {
        use uni_cypher::ast::SetItem;

        match item {
            SetItem::Property { expr, value } => SetItem::Property {
                expr: self.rewrite_expr(expr),
                value: self.rewrite_expr(value),
            },
            SetItem::Variable { variable, value } => SetItem::Variable {
                variable,
                value: self.rewrite_expr(value),
            },
            SetItem::VariablePlus { variable, value } => SetItem::VariablePlus {
                variable,
                value: self.rewrite_expr(value),
            },
            SetItem::Labels { variable, labels } => SetItem::Labels { variable, labels },
        }
    }

    fn rewrite_remove_clause(
        &mut self,
        r: uni_cypher::ast::RemoveClause,
    ) -> uni_cypher::ast::RemoveClause {
        uni_cypher::ast::RemoveClause {
            items: r
                .items
                .into_iter()
                .map(|item| self.rewrite_remove_item(item))
                .collect(),
        }
    }

    fn rewrite_remove_item(
        &mut self,
        item: uni_cypher::ast::RemoveItem,
    ) -> uni_cypher::ast::RemoveItem {
        use uni_cypher::ast::RemoveItem;

        match item {
            RemoveItem::Property(expr) => RemoveItem::Property(self.rewrite_expr(expr)),
            RemoveItem::Labels { variable, labels } => RemoveItem::Labels { variable, labels },
        }
    }

    fn rewrite_unwind_clause(
        &mut self,
        u: uni_cypher::ast::UnwindClause,
    ) -> uni_cypher::ast::UnwindClause {
        uni_cypher::ast::UnwindClause {
            expr: self.rewrite_expr(u.expr),
            variable: u.variable,
        }
    }

    fn rewrite_pattern(&mut self, pattern: uni_cypher::ast::Pattern) -> uni_cypher::ast::Pattern {
        uni_cypher::ast::Pattern {
            paths: pattern
                .paths
                .into_iter()
                .map(|path| self.rewrite_path_pattern(path))
                .collect(),
        }
    }

    fn rewrite_path_pattern(
        &mut self,
        path: uni_cypher::ast::PathPattern,
    ) -> uni_cypher::ast::PathPattern {
        uni_cypher::ast::PathPattern {
            variable: path.variable,
            elements: path
                .elements
                .into_iter()
                .map(|elem| self.rewrite_pattern_element(elem))
                .collect(),
            shortest_path_mode: path.shortest_path_mode,
        }
    }

    fn rewrite_pattern_element(
        &mut self,
        elem: uni_cypher::ast::PatternElement,
    ) -> uni_cypher::ast::PatternElement {
        use uni_cypher::ast::PatternElement;

        match elem {
            PatternElement::Node(node) => PatternElement::Node(uni_cypher::ast::NodePattern {
                variable: node.variable,
                labels: node.labels,
                properties: node.properties.map(|expr| self.rewrite_expr(expr)),
                where_clause: node.where_clause.map(|expr| self.rewrite_expr(expr)),
            }),
            PatternElement::Relationship(rel) => {
                PatternElement::Relationship(uni_cypher::ast::RelationshipPattern {
                    variable: rel.variable,
                    types: rel.types,
                    direction: rel.direction,
                    properties: rel.properties.map(|expr| self.rewrite_expr(expr)),
                    range: rel.range,
                    where_clause: rel.where_clause.map(|expr| self.rewrite_expr(expr)),
                })
            }
            PatternElement::Parenthesized { pattern, range } => PatternElement::Parenthesized {
                pattern: Box::new(self.rewrite_path_pattern(*pattern)),
                range,
            },
        }
    }

    fn rewrite_order_by(
        &mut self,
        order_by: Option<Vec<uni_cypher::ast::SortItem>>,
    ) -> Option<Vec<uni_cypher::ast::SortItem>> {
        order_by.map(|items| {
            items
                .into_iter()
                .map(|item| uni_cypher::ast::SortItem {
                    expr: self.rewrite_expr(item.expr),
                    ascending: item.ascending,
                })
                .collect()
        })
    }

    fn rewrite_return_clause(
        &mut self,
        r: uni_cypher::ast::ReturnClause,
    ) -> uni_cypher::ast::ReturnClause {
        uni_cypher::ast::ReturnClause {
            distinct: r.distinct,
            items: r
                .items
                .into_iter()
                .map(|item| self.rewrite_return_item(item))
                .collect(),
            order_by: self.rewrite_order_by(r.order_by),
            skip: r.skip.map(|e| self.rewrite_expr(e)),
            limit: r.limit.map(|e| self.rewrite_expr(e)),
        }
    }

    fn rewrite_return_item(
        &mut self,
        item: uni_cypher::ast::ReturnItem,
    ) -> uni_cypher::ast::ReturnItem {
        use uni_cypher::ast::ReturnItem;

        match item {
            ReturnItem::All => ReturnItem::All,
            ReturnItem::Expr {
                expr,
                alias,
                source_text,
            } => ReturnItem::Expr {
                expr: self.rewrite_expr(expr),
                alias,
                source_text,
            },
        }
    }

    fn rewrite_with_clause(
        &mut self,
        w: uni_cypher::ast::WithClause,
    ) -> uni_cypher::ast::WithClause {
        uni_cypher::ast::WithClause {
            distinct: w.distinct,
            items: w
                .items
                .into_iter()
                .map(|item| self.rewrite_return_item(item))
                .collect(),
            order_by: self.rewrite_order_by(w.order_by),
            skip: w.skip.map(|e| self.rewrite_expr(e)),
            limit: w.limit.map(|e| self.rewrite_expr(e)),
            where_clause: w.where_clause.map(|e| self.rewrite_expr(e)),
        }
    }

    /// Walk and rewrite an expression tree
    pub fn rewrite_expr(&mut self, expr: Expr) -> Expr {
        match expr {
            Expr::PatternComprehension {
                path_variable,
                pattern,
                where_clause,
                map_expr,
            } => Expr::PatternComprehension {
                path_variable,
                pattern, // Pattern structure doesn't need rewriting
                where_clause: where_clause.map(|e| Box::new(self.rewrite_expr(*e))),
                map_expr: Box::new(self.rewrite_expr(*map_expr)),
            },
            Expr::CollectSubquery(query) => {
                Expr::CollectSubquery(Box::new(self.rewrite_query(*query)))
            }
            // Try to rewrite function calls
            Expr::FunctionCall {
                name,
                args,
                distinct,
                window_spec,
            } => self.try_rewrite_function(name, args, distinct, window_spec),

            // Recursively handle all other expression variants
            Expr::BinaryOp { left, op, right } => Expr::BinaryOp {
                left: Box::new(self.rewrite_expr(*left)),
                op,
                right: Box::new(self.rewrite_expr(*right)),
            },

            Expr::UnaryOp { op, expr } => Expr::UnaryOp {
                op,
                expr: Box::new(self.rewrite_expr(*expr)),
            },

            Expr::Property(expr, prop) => Expr::Property(Box::new(self.rewrite_expr(*expr)), prop),

            Expr::List(exprs) => {
                Expr::List(exprs.into_iter().map(|e| self.rewrite_expr(e)).collect())
            }

            Expr::Map(entries) => Expr::Map(
                entries
                    .into_iter()
                    .map(|(k, v)| (k, self.rewrite_expr(v)))
                    .collect(),
            ),

            Expr::Case {
                expr,
                when_then,
                else_expr,
            } => Expr::Case {
                expr: expr.map(|e| Box::new(self.rewrite_expr(*e))),
                when_then: when_then
                    .into_iter()
                    .map(|(w, t)| (self.rewrite_expr(w), self.rewrite_expr(t)))
                    .collect(),
                else_expr: else_expr.map(|e| Box::new(self.rewrite_expr(*e))),
            },

            Expr::Exists {
                query,
                from_pattern_predicate,
            } => Expr::Exists {
                query: Box::new(self.rewrite_query(*query)),
                from_pattern_predicate,
            },

            Expr::CountSubquery(query) => Expr::CountSubquery(Box::new(self.rewrite_query(*query))),

            Expr::IsNull(expr) => Expr::IsNull(Box::new(self.rewrite_expr(*expr))),

            Expr::IsNotNull(expr) => Expr::IsNotNull(Box::new(self.rewrite_expr(*expr))),

            Expr::IsUnique(expr) => Expr::IsUnique(Box::new(self.rewrite_expr(*expr))),

            Expr::In { expr, list } => Expr::In {
                expr: Box::new(self.rewrite_expr(*expr)),
                list: Box::new(self.rewrite_expr(*list)),
            },

            Expr::ArrayIndex { array, index } => Expr::ArrayIndex {
                array: Box::new(self.rewrite_expr(*array)),
                index: Box::new(self.rewrite_expr(*index)),
            },

            Expr::ArraySlice { array, start, end } => Expr::ArraySlice {
                array: Box::new(self.rewrite_expr(*array)),
                start: start.map(|e| Box::new(self.rewrite_expr(*e))),
                end: end.map(|e| Box::new(self.rewrite_expr(*e))),
            },

            Expr::Quantifier {
                quantifier,
                variable,
                list,
                predicate,
            } => Expr::Quantifier {
                quantifier,
                variable,
                list: Box::new(self.rewrite_expr(*list)),
                predicate: Box::new(self.rewrite_expr(*predicate)),
            },

            Expr::Reduce {
                accumulator,
                init,
                variable,
                list,
                expr,
            } => Expr::Reduce {
                accumulator,
                init: Box::new(self.rewrite_expr(*init)),
                variable,
                list: Box::new(self.rewrite_expr(*list)),
                expr: Box::new(self.rewrite_expr(*expr)),
            },

            Expr::ListComprehension {
                variable,
                list,
                where_clause,
                map_expr,
            } => Expr::ListComprehension {
                variable,
                list: Box::new(self.rewrite_expr(*list)),
                where_clause: where_clause.map(|e| Box::new(self.rewrite_expr(*e))),
                map_expr: Box::new(self.rewrite_expr(*map_expr)),
            },

            Expr::ValidAt {
                entity,
                timestamp,
                start_prop,
                end_prop,
            } => Expr::ValidAt {
                entity: Box::new(self.rewrite_expr(*entity)),
                timestamp: Box::new(self.rewrite_expr(*timestamp)),
                start_prop,
                end_prop,
            },

            Expr::MapProjection { base, items } => Expr::MapProjection {
                base: Box::new(self.rewrite_expr(*base)),
                items: items
                    .into_iter()
                    .map(|item| match item {
                        MapProjectionItem::LiteralEntry(k, v) => {
                            MapProjectionItem::LiteralEntry(k, Box::new(self.rewrite_expr(*v)))
                        }
                        other => other,
                    })
                    .collect(),
            },

            Expr::LabelCheck { expr, labels } => Expr::LabelCheck {
                expr: Box::new(self.rewrite_expr(*expr)),
                labels,
            },

            // Leaf nodes - no rewriting needed
            Expr::Literal(_) | Expr::Parameter(_) | Expr::Variable(_) | Expr::Wildcard => expr,
        }
    }

    /// Try to rewrite a function call
    fn try_rewrite_function(
        &mut self,
        name: String,
        args: Vec<Expr>,
        distinct: bool,
        window_spec: Option<uni_cypher::ast::WindowSpec>,
    ) -> Expr {
        // First, recursively rewrite arguments
        let rewritten_args: Vec<Expr> =
            args.into_iter().map(|arg| self.rewrite_expr(arg)).collect();

        // Record that we visited this function
        self.context.stats.record_visit();

        // Helper to construct fallback function call
        let make_fallback = |name, args| Expr::FunctionCall {
            name,
            args,
            distinct,
            window_spec: window_spec.clone(),
        };

        // Check if we have a rewrite rule for this function
        let Some(rule) = self.registry.get_rule(&name) else {
            return make_fallback(name, rewritten_args);
        };

        // Validate arguments
        if let Err(e) = rule.validate_args(&rewritten_args) {
            self.context.stats.record_failure(&name, e);
            if self.context.config.verbose_logging {
                tracing::debug!(
                    "Rewrite validation failed for {}: {:?}",
                    name,
                    self.context.stats.errors.last()
                );
            }
            return make_fallback(name, rewritten_args);
        }

        // Check if rule is applicable in current context
        if !rule.is_applicable(&self.context) {
            let error = RewriteError::NotApplicable {
                reason: "Context requirements not met".to_string(),
            };
            self.context.stats.record_failure(&name, error);
            if self.context.config.verbose_logging {
                tracing::debug!("Rewrite not applicable for {}", name);
            }
            return make_fallback(name, rewritten_args);
        }

        // Apply rewrite
        match rule.rewrite(rewritten_args.clone(), &self.context) {
            Ok(rewritten_expr) => {
                self.context.stats.record_success(&name);
                if self.context.config.verbose_logging {
                    tracing::debug!("Rewrote function call: {} -> {:?}", name, rewritten_expr);
                } else {
                    tracing::info!("Rewrote function: {}", name);
                }
                rewritten_expr
            }
            Err(e) => {
                self.context.stats.record_failure(&name, e);
                if self.context.config.verbose_logging {
                    tracing::debug!(
                        "Rewrite failed for {}: {:?}",
                        name,
                        self.context.stats.errors.last()
                    );
                }
                make_fallback(name, rewritten_args)
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::query::rewrite::context::RewriteConfig;
    use uni_cypher::ast::CypherLiteral;

    #[test]
    fn test_walker_visits_nested_expressions() {
        let registry = RewriteRegistry::new();
        let config = RewriteConfig::default();
        let mut walker = ExpressionWalker::new(&registry, RewriteContext::with_config(config));

        // Nested expression with function calls
        let expr = Expr::BinaryOp {
            left: Box::new(Expr::FunctionCall {
                name: "func1".into(),
                args: vec![Expr::Literal(CypherLiteral::Integer(1))],
                distinct: false,
                window_spec: None,
            }),
            op: uni_cypher::ast::BinaryOp::And,
            right: Box::new(Expr::FunctionCall {
                name: "func2".into(),
                args: vec![Expr::Literal(CypherLiteral::Integer(2))],
                distinct: false,
                window_spec: None,
            }),
        };

        let _ = walker.rewrite_expr(expr);

        // Both function calls should have been visited
        assert_eq!(walker.context().stats.functions_visited, 2);
    }

    #[test]
    fn test_walker_fallback_without_rules() {
        let registry = RewriteRegistry::new();
        let config = RewriteConfig::default();
        let mut walker = ExpressionWalker::new(&registry, RewriteContext::with_config(config));

        let original = Expr::FunctionCall {
            name: "unknown".into(),
            args: vec![Expr::Literal(CypherLiteral::Integer(1))],
            distinct: false,
            window_spec: None,
        };

        let rewritten = walker.rewrite_expr(original.clone());

        // Should return unchanged (but with potentially rewritten arguments)
        assert!(matches!(rewritten, Expr::FunctionCall { name, .. } if name == "unknown"));
        assert_eq!(walker.context().stats.functions_visited, 1);
    }
}