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
// SPDX-License-Identifier: Apache-2.0
// Copyright 2024-2026 Dragonscale Team

use uni_common::core::schema::{LabelMeta, Schema, SchemaElementState};
use uni_cypher::ast::{BinaryOp, CypherLiteral, Expr};
use uni_query::query::pushdown::{IndexAwareAnalyzer, LanceFilterGenerator, PredicateAnalyzer};

#[test]
fn test_lance_filter_generation() {
    // n.name CONTAINS 'foo'
    let expr = Expr::BinaryOp {
        left: Box::new(Expr::Property(
            Box::new(Expr::Variable("n".to_string())),
            "name".to_string(),
        )),
        op: BinaryOp::Contains,
        right: Box::new(Expr::Literal(CypherLiteral::String("foo".to_string()))),
    };

    let filter = LanceFilterGenerator::generate(&[expr], "n", None).unwrap();
    assert_eq!(filter, "name LIKE '%foo%'");

    // n.title STARTS WITH 'Intro'
    let expr = Expr::BinaryOp {
        left: Box::new(Expr::Property(
            Box::new(Expr::Variable("n".to_string())),
            "title".to_string(),
        )),
        op: BinaryOp::StartsWith,
        right: Box::new(Expr::Literal(CypherLiteral::String("Intro".to_string()))),
    };

    let filter = LanceFilterGenerator::generate(&[expr], "n", None).unwrap();
    assert_eq!(filter, "title LIKE 'Intro%'");
}

#[test]
fn test_or_to_in_conversion() {
    // Manually construct: n.status = 'a' OR n.status = 'b'
    let expr = Expr::BinaryOp {
        left: Box::new(Expr::BinaryOp {
            left: Box::new(Expr::Property(
                Box::new(Expr::Variable("n".to_string())),
                "status".to_string(),
            )),
            op: BinaryOp::Eq,
            right: Box::new(Expr::Literal(CypherLiteral::String("a".to_string()))),
        }),
        op: BinaryOp::Or,
        right: Box::new(Expr::BinaryOp {
            left: Box::new(Expr::Property(
                Box::new(Expr::Variable("n".to_string())),
                "status".to_string(),
            )),
            op: BinaryOp::Eq,
            right: Box::new(Expr::Literal(CypherLiteral::String("b".to_string()))),
        }),
    };

    let analyzer = PredicateAnalyzer::new();
    let analysis = analyzer.analyze(&expr, "n");

    // Should be pushed as a single IN expression
    assert_eq!(analysis.pushable.len(), 1);
    assert!(analysis.residual.is_empty());

    let pushed = &analysis.pushable[0];
    if let Expr::In { list, .. } = pushed {
        if let Expr::List(items) = list.as_ref() {
            assert_eq!(items.len(), 2);
        } else {
            panic!("Expected list on RHS of IN");
        }
    } else {
        panic!("Expected IN expression, got {:?}", pushed);
    }

    // Verify SQL generation
    let sql = LanceFilterGenerator::generate(&analysis.pushable, "n", None).unwrap();
    // order might vary? No, vec insertion order.
    assert!(sql == "status IN ('a', 'b')" || sql == "status IN ('b', 'a')");
}

#[test]
fn test_is_null_pushdown() {
    let expr = Expr::IsNull(Box::new(Expr::Property(
        Box::new(Expr::Variable("n".to_string())),
        "email".to_string(),
    )));

    let analyzer = PredicateAnalyzer::new();
    let analysis = analyzer.analyze(&expr, "n");

    assert_eq!(analysis.pushable.len(), 1);
    assert!(analysis.residual.is_empty());

    let sql = LanceFilterGenerator::generate(&analysis.pushable, "n", None).unwrap();
    assert_eq!(sql, "email IS NULL");
}

#[test]
fn test_is_not_null_pushdown() {
    let expr = Expr::IsNotNull(Box::new(Expr::Property(
        Box::new(Expr::Variable("n".to_string())),
        "email".to_string(),
    )));

    let analyzer = PredicateAnalyzer::new();
    let analysis = analyzer.analyze(&expr, "n");

    assert_eq!(analysis.pushable.len(), 1);

    let sql = LanceFilterGenerator::generate(&analysis.pushable, "n", None).unwrap();
    assert_eq!(sql, "email IS NOT NULL");
}

#[test]
fn test_predicate_flattening() {
    // (a=1 AND b=2)
    // Analyzer splits conjuncts into vector
    let expr = Expr::BinaryOp {
        left: Box::new(Expr::BinaryOp {
            left: Box::new(Expr::Property(
                Box::new(Expr::Variable("n".to_string())),
                "a".to_string(),
            )),
            op: BinaryOp::Eq,
            right: Box::new(Expr::Literal(CypherLiteral::Integer(1))),
        }),
        op: BinaryOp::And,
        right: Box::new(Expr::BinaryOp {
            left: Box::new(Expr::Property(
                Box::new(Expr::Variable("n".to_string())),
                "b".to_string(),
            )),
            op: BinaryOp::Eq,
            right: Box::new(Expr::Literal(CypherLiteral::Integer(2))),
        }),
    };

    let analyzer = PredicateAnalyzer::new();
    let analysis = analyzer.analyze(&expr, "n");

    assert_eq!(analysis.pushable.len(), 2);

    let sql = LanceFilterGenerator::generate(&analysis.pushable, "n", None).unwrap();
    assert_eq!(sql, "a = 1 AND b = 2");
}

// =====================================================================
// IndexAwareAnalyzer Tests
// =====================================================================

fn create_test_schema_with_label(label: &str, label_id: u16) -> Schema {
    let mut schema = Schema::default();
    schema.labels.insert(
        label.to_string(),
        LabelMeta {
            id: label_id,
            created_at: chrono::Utc::now(),
            state: SchemaElementState::Active,
        },
    );
    schema
}

#[test]
fn test_index_aware_uid_extraction() {
    // Test that _uid = 'valid_base32' is recognized
    // Note: We can't test actual UID lookup without a valid Base32Lower multibase string
    // but we can verify the pattern detection

    let schema = create_test_schema_with_label("Person", 1);

    // Create a predicate: n._uid = 'invalid_format'
    // This should NOT be extracted (invalid UID format)
    let expr = Expr::BinaryOp {
        left: Box::new(Expr::Property(
            Box::new(Expr::Variable("n".to_string())),
            "_uid".to_string(),
        )),
        op: BinaryOp::Eq,
        right: Box::new(Expr::Literal(CypherLiteral::String(
            "not-a-valid-uid".to_string(),
        ))),
    };

    let analyzer = IndexAwareAnalyzer::new(&schema);
    let strategy = analyzer.analyze(&expr, "n", 1);

    // Invalid UID should not be extracted
    assert!(strategy.uid_lookup.is_none());
    // Should become residual since _uid column doesn't exist in Lance
    assert!(!strategy.residual.is_empty() || !strategy.lance_predicates.is_empty());
}

#[test]
fn test_index_aware_jsonpath_extraction() {
    let schema = create_test_schema_with_label("Doc", 2);

    // Create predicate: n.title = 'Hello'
    let expr = Expr::BinaryOp {
        left: Box::new(Expr::Property(
            Box::new(Expr::Variable("n".to_string())),
            "title".to_string(),
        )),
        op: BinaryOp::Eq,
        right: Box::new(Expr::Literal(CypherLiteral::String("Hello".to_string()))),
    };

    let analyzer = IndexAwareAnalyzer::new(&schema);
    let strategy = analyzer.analyze(&expr, "n", 2);

    // Without json_indexes, title should go to lance_predicates
    assert!(strategy.json_fts_predicates.is_empty());
    assert_eq!(strategy.lance_predicates.len(), 1);
}

#[test]
fn test_index_aware_non_indexed_property() {
    let schema = create_test_schema_with_label("Doc", 2);

    // Create predicate: n.author = 'John' (not indexed)
    let expr = Expr::BinaryOp {
        left: Box::new(Expr::Property(
            Box::new(Expr::Variable("n".to_string())),
            "author".to_string(),
        )),
        op: BinaryOp::Eq,
        right: Box::new(Expr::Literal(CypherLiteral::String("John".to_string()))),
    };

    let analyzer = IndexAwareAnalyzer::new(&schema);
    let strategy = analyzer.analyze(&expr, "n", 2);

    // Should NOT be extracted as jsonpath lookup (no index)
    assert!(strategy.json_fts_predicates.is_empty());

    // Should go to lance_predicates
    assert_eq!(strategy.lance_predicates.len(), 1);
}

#[test]
fn test_index_aware_combined_predicates() {
    let schema = create_test_schema_with_label("Doc", 2);

    // Create predicate: n.title = 'Hello' AND n.author = 'John'
    // Without json_indexes, both go to lance_predicates
    let expr = Expr::BinaryOp {
        left: Box::new(Expr::BinaryOp {
            left: Box::new(Expr::Property(
                Box::new(Expr::Variable("n".to_string())),
                "title".to_string(),
            )),
            op: BinaryOp::Eq,
            right: Box::new(Expr::Literal(CypherLiteral::String("Hello".to_string()))),
        }),
        op: BinaryOp::And,
        right: Box::new(Expr::BinaryOp {
            left: Box::new(Expr::Property(
                Box::new(Expr::Variable("n".to_string())),
                "author".to_string(),
            )),
            op: BinaryOp::Eq,
            right: Box::new(Expr::Literal(CypherLiteral::String("John".to_string()))),
        }),
    };

    let analyzer = IndexAwareAnalyzer::new(&schema);
    let strategy = analyzer.analyze(&expr, "n", 2);

    // Without json_indexes, both should go to lance_predicates
    assert!(strategy.json_fts_predicates.is_empty());
    assert_eq!(strategy.lance_predicates.len(), 2);
}

// =====================================================================
// BTree STARTS WITH Pushdown Tests
// =====================================================================

use uni_common::core::schema::{IndexDefinition, IndexStatus, ScalarIndexConfig, ScalarIndexType};

fn create_test_schema_with_btree_index(label: &str, label_id: u16, index_property: &str) -> Schema {
    let mut schema = Schema::default();
    schema.labels.insert(
        label.to_string(),
        LabelMeta {
            id: label_id,
            created_at: chrono::Utc::now(),
            state: SchemaElementState::Active,
        },
    );
    schema
        .indexes
        .push(IndexDefinition::Scalar(ScalarIndexConfig {
            name: format!("idx_{}_{}", label, index_property),
            label: label.to_string(),
            properties: vec![index_property.to_string()],
            index_type: ScalarIndexType::BTree,
            where_clause: None,
            metadata: Default::default(),
        }));
    schema
}

#[test]
fn test_btree_starts_with_extraction() {
    let schema = create_test_schema_with_btree_index("Person", 1, "name");

    // Create predicate: n.name STARTS WITH 'John'
    let expr = Expr::BinaryOp {
        left: Box::new(Expr::Property(
            Box::new(Expr::Variable("n".to_string())),
            "name".to_string(),
        )),
        op: BinaryOp::StartsWith,
        right: Box::new(Expr::Literal(CypherLiteral::String("John".to_string()))),
    };

    let analyzer = IndexAwareAnalyzer::new(&schema);
    let strategy = analyzer.analyze(&expr, "n", 1);

    // Should be extracted as BTree prefix scan
    assert_eq!(strategy.btree_prefix_scans.len(), 1);
    assert_eq!(strategy.btree_prefix_scans[0].0, "name");
    assert_eq!(strategy.btree_prefix_scans[0].1, "John");
    assert_eq!(strategy.btree_prefix_scans[0].2, "Joho"); // 'n' + 1 = 'o'

    // Should NOT be in lance_predicates (routed to BTree scan instead)
    assert!(strategy.lance_predicates.is_empty());
}

#[test]
fn test_btree_starts_with_non_indexed_property() {
    let schema = create_test_schema_with_btree_index("Person", 1, "name");

    // Create predicate: n.email STARTS WITH 'john@' (not indexed)
    let expr = Expr::BinaryOp {
        left: Box::new(Expr::Property(
            Box::new(Expr::Variable("n".to_string())),
            "email".to_string(),
        )),
        op: BinaryOp::StartsWith,
        right: Box::new(Expr::Literal(CypherLiteral::String("john@".to_string()))),
    };

    let analyzer = IndexAwareAnalyzer::new(&schema);
    let strategy = analyzer.analyze(&expr, "n", 1);

    // Should NOT be extracted as BTree prefix scan (no index on email)
    assert!(strategy.btree_prefix_scans.is_empty());

    // Should go to lance_predicates as LIKE predicate
    assert_eq!(strategy.lance_predicates.len(), 1);
}

#[test]
fn test_btree_starts_with_empty_prefix() {
    let schema = create_test_schema_with_btree_index("Person", 1, "name");

    // Create predicate: n.name STARTS WITH '' (empty prefix - matches all)
    let expr = Expr::BinaryOp {
        left: Box::new(Expr::Property(
            Box::new(Expr::Variable("n".to_string())),
            "name".to_string(),
        )),
        op: BinaryOp::StartsWith,
        right: Box::new(Expr::Literal(CypherLiteral::String("".to_string()))),
    };

    let analyzer = IndexAwareAnalyzer::new(&schema);
    let strategy = analyzer.analyze(&expr, "n", 1);

    // Empty prefix should NOT be optimized via BTree (matches all, no benefit)
    assert!(strategy.btree_prefix_scans.is_empty());

    // Should go to lance_predicates
    assert_eq!(strategy.lance_predicates.len(), 1);
}

#[test]
fn test_btree_starts_with_hash_index_not_used() {
    let mut schema = create_test_schema_with_label("Person", 1);
    // Add a Hash index instead of BTree
    schema
        .indexes
        .push(IndexDefinition::Scalar(ScalarIndexConfig {
            name: "idx_person_name".to_string(),
            label: "Person".to_string(),
            properties: vec!["name".to_string()],
            index_type: ScalarIndexType::Hash, // Not BTree
            where_clause: None,
            metadata: Default::default(),
        }));

    // Create predicate: n.name STARTS WITH 'John'
    let expr = Expr::BinaryOp {
        left: Box::new(Expr::Property(
            Box::new(Expr::Variable("n".to_string())),
            "name".to_string(),
        )),
        op: BinaryOp::StartsWith,
        right: Box::new(Expr::Literal(CypherLiteral::String("John".to_string()))),
    };

    let analyzer = IndexAwareAnalyzer::new(&schema);
    let strategy = analyzer.analyze(&expr, "n", 1);

    // Hash index should NOT be used for STARTS WITH
    assert!(strategy.btree_prefix_scans.is_empty());

    // Should go to lance_predicates as LIKE predicate
    assert_eq!(strategy.lance_predicates.len(), 1);
}

#[test]
fn test_btree_prefix_increment_logic() {
    // Test the increment_last_char helper via BTree extraction
    let schema = create_test_schema_with_btree_index("Person", 1, "name");

    // Test various prefixes and verify upper bounds
    let test_cases = vec![
        ("A", "B"),       // Simple single char
        ("Z", "["),       // Z + 1 = [
        ("abc", "abd"),   // c + 1 = d
        ("test", "tesu"), // t + 1 = u
        ("123", "124"),   // Numeric strings
    ];

    for (prefix, expected_upper) in test_cases {
        let expr = Expr::BinaryOp {
            left: Box::new(Expr::Property(
                Box::new(Expr::Variable("n".to_string())),
                "name".to_string(),
            )),
            op: BinaryOp::StartsWith,
            right: Box::new(Expr::Literal(CypherLiteral::String(prefix.to_string()))),
        };

        let analyzer = IndexAwareAnalyzer::new(&schema);
        let strategy = analyzer.analyze(&expr, "n", 1);

        assert_eq!(
            strategy.btree_prefix_scans.len(),
            1,
            "Failed for prefix: {}",
            prefix
        );
        assert_eq!(strategy.btree_prefix_scans[0].1, prefix);
        assert_eq!(
            strategy.btree_prefix_scans[0].2, expected_upper,
            "Upper bound mismatch for prefix: {}",
            prefix
        );
    }
}

#[test]
fn test_btree_starts_with_special_characters() {
    let schema = create_test_schema_with_btree_index("Person", 1, "name");

    // Prefix with single quote (should be escaped in SQL)
    let expr = Expr::BinaryOp {
        left: Box::new(Expr::Property(
            Box::new(Expr::Variable("n".to_string())),
            "name".to_string(),
        )),
        op: BinaryOp::StartsWith,
        right: Box::new(Expr::Literal(CypherLiteral::String("O'Brien".to_string()))),
    };

    let analyzer = IndexAwareAnalyzer::new(&schema);
    let strategy = analyzer.analyze(&expr, "n", 1);

    // Should still be extracted
    assert_eq!(strategy.btree_prefix_scans.len(), 1);
    assert_eq!(strategy.btree_prefix_scans[0].1, "O'Brien");
}

#[test]
fn test_btree_starts_with_unicode() {
    let schema = create_test_schema_with_btree_index("Person", 1, "name");

    // Unicode prefix
    let expr = Expr::BinaryOp {
        left: Box::new(Expr::Property(
            Box::new(Expr::Variable("n".to_string())),
            "name".to_string(),
        )),
        op: BinaryOp::StartsWith,
        right: Box::new(Expr::Literal(CypherLiteral::String("日本".to_string()))),
    };

    let analyzer = IndexAwareAnalyzer::new(&schema);
    let strategy = analyzer.analyze(&expr, "n", 1);

    // Should be extracted (Unicode char increment works)
    assert_eq!(strategy.btree_prefix_scans.len(), 1);
    assert_eq!(strategy.btree_prefix_scans[0].1, "日本");
}

#[test]
fn test_btree_starts_with_multiple_indexed_properties() {
    let mut schema = create_test_schema_with_label("Person", 1);
    // Index covers multiple properties
    schema
        .indexes
        .push(IndexDefinition::Scalar(ScalarIndexConfig {
            name: "idx_person_name_email".to_string(),
            label: "Person".to_string(),
            properties: vec!["name".to_string(), "email".to_string()],
            index_type: ScalarIndexType::BTree,
            where_clause: None,
            metadata: Default::default(),
        }));

    // Test name (indexed)
    let expr1 = Expr::BinaryOp {
        left: Box::new(Expr::Property(
            Box::new(Expr::Variable("n".to_string())),
            "name".to_string(),
        )),
        op: BinaryOp::StartsWith,
        right: Box::new(Expr::Literal(CypherLiteral::String("John".to_string()))),
    };

    // Test email (also indexed)
    let expr2 = Expr::BinaryOp {
        left: Box::new(Expr::Property(
            Box::new(Expr::Variable("n".to_string())),
            "email".to_string(),
        )),
        op: BinaryOp::StartsWith,
        right: Box::new(Expr::Literal(CypherLiteral::String("john@".to_string()))),
    };

    let analyzer = IndexAwareAnalyzer::new(&schema);

    let strategy1 = analyzer.analyze(&expr1, "n", 1);
    assert_eq!(strategy1.btree_prefix_scans.len(), 1);

    let strategy2 = analyzer.analyze(&expr2, "n", 1);
    assert_eq!(strategy2.btree_prefix_scans.len(), 1);
}

#[test]
fn test_btree_prefix_scan_skips_non_online_index() {
    // Start with a normal BTree-indexed schema, then set the index to Building
    let mut schema = create_test_schema_with_btree_index("Person", 1, "name");
    if let IndexDefinition::Scalar(cfg) = &mut schema.indexes[0] {
        cfg.metadata.status = IndexStatus::Building;
    }

    // Create predicate: n.name STARTS WITH 'John'
    let expr = Expr::BinaryOp {
        left: Box::new(Expr::Property(
            Box::new(Expr::Variable("n".to_string())),
            "name".to_string(),
        )),
        op: BinaryOp::StartsWith,
        right: Box::new(Expr::Literal(CypherLiteral::String("John".to_string()))),
    };

    let analyzer = IndexAwareAnalyzer::new(&schema);
    let strategy = analyzer.analyze(&expr, "n", 1);

    // Building index should NOT be used for BTree prefix scan
    assert!(strategy.btree_prefix_scans.is_empty());
    // Should fall through to lance_predicates
    assert_eq!(strategy.lance_predicates.len(), 1);

    // Now set to Online — should be used
    if let IndexDefinition::Scalar(cfg) = &mut schema.indexes[0] {
        cfg.metadata.status = IndexStatus::Online;
    }
    let analyzer = IndexAwareAnalyzer::new(&schema);
    let strategy = analyzer.analyze(&expr, "n", 1);
    assert_eq!(strategy.btree_prefix_scans.len(), 1);
    assert_eq!(strategy.btree_prefix_scans[0].0, "name");
    assert!(strategy.lance_predicates.is_empty());
}