tensorlogic-oxirs-bridge 0.1.0

RDF/GraphQL/SHACL integration and provenance tracking for TensorLogic
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
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
//! Advanced SPARQL query compilation to TensorLogic operations
//!
//! This module provides comprehensive support for compiling SPARQL 1.1 queries
//! into TensorLogic expressions. Supports:
//! - SELECT queries (basic and complex)
//! - ASK queries (boolean existence checks)
//! - DESCRIBE queries (resource descriptions)
//! - CONSTRUCT queries (RDF graph construction)
//! - Triple patterns with variables and constants
//! - Filter constraints (comparison, regex)
//! - OPTIONAL patterns (left-outer join semantics)
//! - UNION patterns (disjunction)
//!
//! For production SPARQL federation and advanced features, consider using a dedicated SPARQL engine.

mod compiler;
mod types;

pub use compiler::SparqlCompiler;
pub use types::{
    AggregateFunction, BindExpr, FilterCondition, GraphPattern, PatternElement, QueryType,
    SelectElement, SparqlQuery, TriplePattern,
};

#[cfg(test)]
mod tests {
    use super::*;

    // ====== Basic SELECT Query Tests ======

    #[test]
    fn test_parse_simple_query() {
        let compiler = SparqlCompiler::new();
        let query = r#"
            SELECT ?x ?y WHERE {
              ?x <http://example.org/knows> ?y .
            }
        "#;

        let parsed = compiler.parse_query(query).expect("unwrap");

        // Check query type
        match &parsed.query_type {
            QueryType::Select {
                select_vars,
                distinct,
                ..
            } => {
                assert_eq!(select_vars, &vec!["x", "y"]);
                assert!(!distinct);
            }
            _ => panic!("Expected SELECT query"),
        }

        // Check WHERE pattern
        match &parsed.where_pattern {
            GraphPattern::Triple(pattern) => {
                assert_eq!(pattern.subject, PatternElement::Variable("x".to_string()));
                assert_eq!(
                    pattern.predicate,
                    PatternElement::Constant("http://example.org/knows".to_string())
                );
                assert_eq!(pattern.object, PatternElement::Variable("y".to_string()));
            }
            _ => panic!("Expected Triple pattern"),
        }
    }

    #[test]
    fn test_parse_select_distinct() {
        let compiler = SparqlCompiler::new();
        let query = r#"
            SELECT DISTINCT ?x WHERE {
              ?x <http://example.org/type> ?t .
            }
        "#;

        let parsed = compiler.parse_query(query).expect("unwrap");

        match &parsed.query_type {
            QueryType::Select {
                select_vars,
                distinct,
                ..
            } => {
                assert_eq!(select_vars, &vec!["x"]);
                assert!(distinct);
            }
            _ => panic!("Expected SELECT DISTINCT query"),
        }
    }

    #[test]
    fn test_parse_query_with_filter() {
        let compiler = SparqlCompiler::new();
        let query = r#"
            SELECT ?x ?age WHERE {
              ?x <http://example.org/age> ?age .
              FILTER(?age > 18)
            }
        "#;

        let parsed = compiler.parse_query(query).expect("unwrap");

        match &parsed.query_type {
            QueryType::Select { select_vars, .. } => {
                assert_eq!(select_vars, &vec!["x", "age"]);
            }
            _ => panic!("Expected SELECT query"),
        }

        // Check WHERE pattern contains filter
        match &parsed.where_pattern {
            GraphPattern::Group(patterns) => {
                assert_eq!(patterns.len(), 2);
                // One Triple, one Filter
                assert!(matches!(patterns[0], GraphPattern::Triple(_)));
                assert!(matches!(patterns[1], GraphPattern::Filter(_)));
            }
            _ => panic!("Expected Group pattern with filter"),
        }
    }

    #[test]
    fn test_parse_query_with_limit_offset() {
        let compiler = SparqlCompiler::new();
        let query = r#"
            SELECT ?x WHERE {
              ?x <http://example.org/type> ?t .
            } LIMIT 10 OFFSET 20
        "#;

        let parsed = compiler.parse_query(query).expect("unwrap");
        assert_eq!(parsed.limit, Some(10));
        assert_eq!(parsed.offset, Some(20));
    }

    #[test]
    fn test_parse_query_with_order_by() {
        let compiler = SparqlCompiler::new();
        let query = r#"
            SELECT ?x ?name WHERE {
              ?x <http://example.org/name> ?name .
            } ORDER BY ?name
        "#;

        let parsed = compiler.parse_query(query).expect("unwrap");
        assert_eq!(parsed.order_by, vec!["name"]);
    }

    // ====== ASK Query Tests ======

    #[test]
    fn test_parse_ask_query() {
        let compiler = SparqlCompiler::new();
        let query = r#"
            ASK WHERE {
              ?x <http://example.org/knows> ?y .
            }
        "#;

        let parsed = compiler.parse_query(query).expect("unwrap");

        match &parsed.query_type {
            QueryType::Ask => {
                // Success
            }
            _ => panic!("Expected ASK query"),
        }
    }

    #[test]
    fn test_compile_ask_query() {
        let mut compiler = SparqlCompiler::new();
        compiler.add_predicate_mapping("http://example.org/knows".to_string(), "knows".to_string());

        let query = r#"
            ASK WHERE {
              ?x <http://example.org/knows> ?y .
            }
        "#;

        let parsed = compiler.parse_query(query).expect("unwrap");
        let tl_expr = compiler.compile_to_tensorlogic(&parsed).expect("unwrap");

        // Should generate existence check
        let expr_str = format!("{:?}", tl_expr);
        assert!(expr_str.contains("knows"));
    }

    // ====== DESCRIBE Query Tests ======

    #[test]
    fn test_parse_describe_query() {
        let compiler = SparqlCompiler::new();
        let query = r#"
            DESCRIBE ?x WHERE {
              ?x <http://example.org/type> <http://example.org/Person> .
            }
        "#;

        let parsed = compiler.parse_query(query).expect("unwrap");

        match &parsed.query_type {
            QueryType::Describe { resources } => {
                assert_eq!(resources, &vec!["x"]);
            }
            _ => panic!("Expected DESCRIBE query"),
        }
    }

    #[test]
    fn test_compile_describe_query() {
        let mut compiler = SparqlCompiler::new();
        compiler.add_predicate_mapping("http://example.org/type".to_string(), "type".to_string());

        let query = r#"
            DESCRIBE ?x WHERE {
              ?x <http://example.org/type> ?t .
            }
        "#;

        let parsed = compiler.parse_query(query).expect("unwrap");
        let tl_expr = compiler.compile_to_tensorlogic(&parsed).expect("unwrap");

        let expr_str = format!("{:?}", tl_expr);
        assert!(expr_str.contains("type"));
    }

    // ====== CONSTRUCT Query Tests ======

    #[test]
    fn test_parse_construct_query() {
        let compiler = SparqlCompiler::new();
        let query = r#"
            CONSTRUCT { ?x <http://example.org/friend> ?y }
            WHERE {
              ?x <http://example.org/knows> ?y .
            }
        "#;

        let parsed = compiler.parse_query(query).expect("unwrap");

        match &parsed.query_type {
            QueryType::Construct { template } => {
                assert_eq!(template.len(), 1);
                let pattern = &template[0];
                assert_eq!(pattern.subject, PatternElement::Variable("x".to_string()));
                assert_eq!(
                    pattern.predicate,
                    PatternElement::Constant("http://example.org/friend".to_string())
                );
                assert_eq!(pattern.object, PatternElement::Variable("y".to_string()));
            }
            _ => panic!("Expected CONSTRUCT query"),
        }
    }

    #[test]
    fn test_compile_construct_query() {
        let mut compiler = SparqlCompiler::new();
        compiler.add_predicate_mapping("http://example.org/knows".to_string(), "knows".to_string());

        let query = r#"
            CONSTRUCT { ?x <http://example.org/friend> ?y }
            WHERE {
              ?x <http://example.org/knows> ?y .
            }
        "#;

        let parsed = compiler.parse_query(query).expect("unwrap");
        let tl_expr = compiler.compile_to_tensorlogic(&parsed).expect("unwrap");

        let expr_str = format!("{:?}", tl_expr);
        assert!(expr_str.contains("knows"));
    }

    // ====== OPTIONAL Pattern Tests ======

    #[test]
    fn test_parse_optional_pattern() {
        let compiler = SparqlCompiler::new();
        let query = r#"
            SELECT ?x ?name ?age WHERE {
              ?x <http://example.org/name> ?name .
              OPTIONAL { ?x <http://example.org/age> ?age }
            }
        "#;

        let parsed = compiler.parse_query(query).expect("unwrap");

        match &parsed.where_pattern {
            GraphPattern::Group(patterns) => {
                assert_eq!(patterns.len(), 2);
                assert!(matches!(patterns[0], GraphPattern::Triple(_)));
                assert!(matches!(patterns[1], GraphPattern::Optional(_)));
            }
            _ => panic!("Expected Group with OPTIONAL"),
        }
    }

    #[test]
    fn test_compile_optional_pattern() {
        let mut compiler = SparqlCompiler::new();
        compiler.add_predicate_mapping("http://example.org/name".to_string(), "name".to_string());
        compiler.add_predicate_mapping("http://example.org/age".to_string(), "age".to_string());

        let query = r#"
            SELECT ?x ?name WHERE {
              ?x <http://example.org/name> ?name .
              OPTIONAL { ?x <http://example.org/age> ?age }
            }
        "#;

        let parsed = compiler.parse_query(query).expect("unwrap");
        let tl_expr = compiler.compile_to_tensorlogic(&parsed).expect("unwrap");

        // Should have OR for optional semantics
        let expr_str = format!("{:?}", tl_expr);
        assert!(expr_str.contains("name"));
        assert!(expr_str.contains("Or"));
    }

    // ====== UNION Pattern Tests ======

    #[test]
    fn test_parse_union_pattern() {
        let compiler = SparqlCompiler::new();
        let query = r#"
            SELECT ?x ?y WHERE {
              { ?x <http://example.org/knows> ?y }
              UNION
              { ?x <http://example.org/likes> ?y }
            }
        "#;

        let parsed = compiler.parse_query(query).expect("unwrap");

        match &parsed.where_pattern {
            GraphPattern::Union(_, _) => {
                // Success - found UNION pattern
            }
            _ => panic!("Expected UNION pattern"),
        }
    }

    #[test]
    fn test_compile_union_pattern() {
        let mut compiler = SparqlCompiler::new();
        compiler.add_predicate_mapping("http://example.org/knows".to_string(), "knows".to_string());
        compiler.add_predicate_mapping("http://example.org/likes".to_string(), "likes".to_string());

        let query = r#"
            SELECT ?x ?y WHERE {
              { ?x <http://example.org/knows> ?y }
              UNION
              { ?x <http://example.org/likes> ?y }
            }
        "#;

        let parsed = compiler.parse_query(query).expect("unwrap");
        let tl_expr = compiler.compile_to_tensorlogic(&parsed).expect("unwrap");

        // Should have OR for union
        let expr_str = format!("{:?}", tl_expr);
        assert!(expr_str.contains("knows") || expr_str.contains("likes"));
        assert!(expr_str.contains("Or"));
    }

    // ====== Filter Conditions Tests ======

    #[test]
    fn test_filter_greater_or_equal() {
        let compiler = SparqlCompiler::new();
        let query = r#"
            SELECT ?x WHERE {
              ?x <http://example.org/age> ?age .
              FILTER(?age >= 18)
            }
        "#;

        let parsed = compiler.parse_query(query).expect("unwrap");

        match &parsed.where_pattern {
            GraphPattern::Group(patterns) => {
                if let Some(GraphPattern::Filter(FilterCondition::GreaterOrEqual(var, val))) =
                    patterns.get(1)
                {
                    assert_eq!(var, "age");
                    assert_eq!(val, "18");
                } else {
                    panic!("Expected GreaterOrEqual filter");
                }
            }
            _ => panic!("Expected Group pattern"),
        }
    }

    // ====== Compilation Tests ======

    #[test]
    fn test_compile_simple_query() {
        let mut compiler = SparqlCompiler::new();
        compiler.add_predicate_mapping("http://example.org/knows".to_string(), "knows".to_string());

        let query = r#"
            SELECT ?x ?y WHERE {
              ?x <http://example.org/knows> ?y .
            }
        "#;

        let parsed = compiler.parse_query(query).expect("unwrap");
        let tl_expr = compiler.compile_to_tensorlogic(&parsed).expect("unwrap");

        // Should generate a predicate expression
        let expr_str = format!("{:?}", tl_expr);
        assert!(expr_str.contains("knows"));
    }

    #[test]
    fn test_compile_query_with_multiple_patterns() {
        let mut compiler = SparqlCompiler::new();
        compiler.add_predicate_mapping("http://example.org/knows".to_string(), "knows".to_string());

        let query = r#"
            SELECT ?x ?y ?z WHERE {
              ?x <http://example.org/knows> ?y .
              ?y <http://example.org/knows> ?z .
            }
        "#;

        let parsed = compiler.parse_query(query).expect("unwrap");
        let tl_expr = compiler.compile_to_tensorlogic(&parsed).expect("unwrap");

        // Should generate AND of predicates
        let expr_str = format!("{:?}", tl_expr);
        assert!(expr_str.contains("knows"));
        assert!(expr_str.contains("And"));
    }

    #[test]
    fn test_compile_query_with_filter() {
        let mut compiler = SparqlCompiler::new();
        compiler.add_predicate_mapping("http://example.org/age".to_string(), "age".to_string());

        let query = r#"
            SELECT ?x ?a WHERE {
              ?x <http://example.org/age> ?a .
              FILTER(?a > 18)
            }
        "#;

        let parsed = compiler.parse_query(query).expect("unwrap");
        let tl_expr = compiler.compile_to_tensorlogic(&parsed).expect("unwrap");

        // Should include both predicate and filter
        let expr_str = format!("{:?}", tl_expr);
        assert!(expr_str.contains("age"));
        assert!(expr_str.contains("greaterThan"));
    }

    // ====== Complex Integration Tests ======

    #[test]
    fn test_complex_query_with_optional_and_filter() {
        let mut compiler = SparqlCompiler::new();
        compiler.add_predicate_mapping("http://example.org/name".to_string(), "name".to_string());
        compiler.add_predicate_mapping("http://example.org/age".to_string(), "age".to_string());

        let query = r#"
            SELECT DISTINCT ?x ?name WHERE {
              ?x <http://example.org/name> ?name .
              OPTIONAL {
                ?x <http://example.org/age> ?age .
                FILTER(?age >= 21)
              }
            } LIMIT 100 ORDER BY ?name
        "#;

        let parsed = compiler.parse_query(query).expect("unwrap");

        // Check all components
        match &parsed.query_type {
            QueryType::Select {
                select_vars,
                distinct,
                ..
            } => {
                assert_eq!(select_vars, &vec!["x", "name"]);
                assert!(distinct);
            }
            _ => panic!("Expected SELECT DISTINCT"),
        }

        assert_eq!(parsed.limit, Some(100));
        assert_eq!(parsed.order_by, vec!["name"]);

        // Check WHERE pattern structure - should be a Group with at least 2 patterns
        match &parsed.where_pattern {
            GraphPattern::Group(patterns) => {
                assert!(patterns.len() >= 2, "Expected at least 2 patterns in group");
                // First should be a Triple (name predicate)
                assert!(matches!(patterns[0], GraphPattern::Triple(_)));
            }
            _ => panic!("Expected Group pattern"),
        }

        // Compile and check basic predicates are present
        let tl_expr = compiler.compile_to_tensorlogic(&parsed).expect("unwrap");
        let expr_str = format!("{:?}", tl_expr);
        assert!(expr_str.contains("name"));
        // Should have logical operators combining the patterns
        assert!(expr_str.contains("And") || expr_str.contains("Or"));
    }

    // ====== Aggregate Function Tests ======

    #[test]
    fn test_parse_count_aggregate() {
        let compiler = SparqlCompiler::new();
        let query = r#"
            SELECT (COUNT(?x) AS ?count) WHERE {
              ?x <http://example.org/type> <http://example.org/Person> .
            }
        "#;

        let parsed = compiler.parse_query(query).expect("unwrap");

        match &parsed.query_type {
            QueryType::Select { projections, .. } => {
                assert_eq!(projections.len(), 1);
                match &projections[0] {
                    SelectElement::Aggregate { function, alias } => {
                        assert!(matches!(function, AggregateFunction::Count { .. }));
                        assert_eq!(alias, &Some("count".to_string()));
                    }
                    _ => panic!("Expected Aggregate element"),
                }
            }
            _ => panic!("Expected SELECT"),
        }
    }

    #[test]
    fn test_parse_sum_aggregate() {
        let compiler = SparqlCompiler::new();
        let query = r#"
            SELECT (SUM(?amount) AS ?total) WHERE {
              ?x <http://example.org/amount> ?amount .
            }
        "#;

        let parsed = compiler.parse_query(query).expect("unwrap");

        match &parsed.query_type {
            QueryType::Select { projections, .. } => {
                assert_eq!(projections.len(), 1);
                match &projections[0] {
                    SelectElement::Aggregate { function, .. } => {
                        if let AggregateFunction::Sum { variable, .. } = function {
                            assert_eq!(variable, "amount");
                        } else {
                            panic!("Expected SUM aggregate");
                        }
                    }
                    _ => panic!("Expected Aggregate element"),
                }
            }
            _ => panic!("Expected SELECT"),
        }
    }

    #[test]
    fn test_parse_avg_min_max() {
        let compiler = SparqlCompiler::new();
        let query = r#"
            SELECT (AVG(?age) AS ?avg_age) (MIN(?age) AS ?min_age) (MAX(?age) AS ?max_age) WHERE {
              ?x <http://example.org/age> ?age .
            }
        "#;

        let parsed = compiler.parse_query(query).expect("unwrap");

        match &parsed.query_type {
            QueryType::Select { projections, .. } => {
                assert_eq!(projections.len(), 3);
                // Check AVG
                match &projections[0] {
                    SelectElement::Aggregate { function, .. } => {
                        assert!(matches!(function, AggregateFunction::Avg { .. }));
                    }
                    _ => panic!("Expected Aggregate element"),
                }
                // Check MIN
                match &projections[1] {
                    SelectElement::Aggregate { function, .. } => {
                        assert!(matches!(function, AggregateFunction::Min { .. }));
                    }
                    _ => panic!("Expected Aggregate element"),
                }
                // Check MAX
                match &projections[2] {
                    SelectElement::Aggregate { function, .. } => {
                        assert!(matches!(function, AggregateFunction::Max { .. }));
                    }
                    _ => panic!("Expected Aggregate element"),
                }
            }
            _ => panic!("Expected SELECT"),
        }
    }

    #[test]
    fn test_parse_group_by() {
        let compiler = SparqlCompiler::new();
        let query = r#"
            SELECT ?dept (COUNT(?person) AS ?count) WHERE {
              ?person <http://example.org/department> ?dept .
            } GROUP BY ?dept
        "#;

        let parsed = compiler.parse_query(query).expect("unwrap");

        assert_eq!(parsed.group_by, vec!["dept"]);

        match &parsed.query_type {
            QueryType::Select { projections, .. } => {
                assert_eq!(projections.len(), 2);
                // First should be variable
                match &projections[0] {
                    SelectElement::Variable(name) => assert_eq!(name, "dept"),
                    _ => panic!("Expected Variable element"),
                }
                // Second should be aggregate
                match &projections[1] {
                    SelectElement::Aggregate { function, .. } => {
                        assert!(matches!(function, AggregateFunction::Count { .. }));
                    }
                    _ => panic!("Expected Aggregate element"),
                }
            }
            _ => panic!("Expected SELECT"),
        }
    }

    #[test]
    fn test_parse_having() {
        let compiler = SparqlCompiler::new();
        let query = r#"
            SELECT ?dept (COUNT(?person) AS ?count) WHERE {
              ?person <http://example.org/department> ?dept .
            } GROUP BY ?dept HAVING(?count > 10)
        "#;

        let parsed = compiler.parse_query(query).expect("unwrap");

        assert_eq!(parsed.group_by, vec!["dept"]);
        assert_eq!(parsed.having.len(), 1);

        match &parsed.having[0] {
            FilterCondition::GreaterThan(var, val) => {
                assert_eq!(var, "count");
                assert_eq!(val, "10");
            }
            _ => panic!("Expected GreaterThan condition"),
        }
    }

    #[test]
    fn test_parse_count_distinct() {
        let compiler = SparqlCompiler::new();
        let query = r#"
            SELECT (COUNT(DISTINCT ?person) AS ?unique) WHERE {
              ?person <http://example.org/type> <http://example.org/Person> .
            }
        "#;

        let parsed = compiler.parse_query(query).expect("unwrap");

        match &parsed.query_type {
            QueryType::Select { projections, .. } => match &projections[0] {
                SelectElement::Aggregate { function, .. } => {
                    if let AggregateFunction::Count { distinct, .. } = function {
                        assert!(distinct);
                    } else {
                        panic!("Expected COUNT aggregate");
                    }
                }
                _ => panic!("Expected Aggregate element"),
            },
            _ => panic!("Expected SELECT"),
        }
    }

    #[test]
    fn test_parse_count_star() {
        let compiler = SparqlCompiler::new();
        let query = r#"
            SELECT (COUNT(*) AS ?total) WHERE {
              ?x <http://example.org/type> ?type .
            }
        "#;

        let parsed = compiler.parse_query(query).expect("unwrap");

        match &parsed.query_type {
            QueryType::Select { projections, .. } => match &projections[0] {
                SelectElement::Aggregate { function, .. } => {
                    if let AggregateFunction::Count { variable, .. } = function {
                        assert!(variable.is_none());
                    } else {
                        panic!("Expected COUNT aggregate");
                    }
                }
                _ => panic!("Expected Aggregate element"),
            },
            _ => panic!("Expected SELECT"),
        }
    }

    #[test]
    fn test_compile_bind_constant() {
        let compiler = SparqlCompiler::new();
        let query = r#"SELECT ?greeting WHERE { BIND ( "hello" AS ?greeting ) }"#;
        let parsed = compiler.parse_query(query).expect("parse_query failed");
        let tl_expr = compiler
            .compile_to_tensorlogic(&parsed)
            .expect("compile failed");
        let expr_str = format!("{tl_expr:?}");
        assert!(
            expr_str.contains("equals"),
            "compiled Bind should contain 'equals': {expr_str}"
        );
        assert!(
            expr_str.contains("greeting"),
            "compiled Bind should contain 'greeting': {expr_str}"
        );
    }

    #[test]
    fn test_compile_values_single_var() {
        let compiler = SparqlCompiler::new();
        let query = r#"SELECT ?x WHERE { VALUES ?x { 1 2 } }"#;
        let parsed = compiler.parse_query(query).expect("parse_query failed");
        let tl_expr = compiler
            .compile_to_tensorlogic(&parsed)
            .expect("compile failed");
        let expr_str = format!("{tl_expr:?}");
        assert!(
            expr_str.contains("Or"),
            "compiled Values should contain 'Or' for row disjunction: {expr_str}"
        );
        assert!(
            expr_str.contains("equals"),
            "compiled Values should contain 'equals': {expr_str}"
        );
    }

    #[test]
    fn test_combined_variables_and_aggregates() {
        let compiler = SparqlCompiler::new();
        let query = r#"
            SELECT ?category (SUM(?price) AS ?total) (AVG(?price) AS ?average) WHERE {
              ?item <http://example.org/category> ?category .
              ?item <http://example.org/price> ?price .
            } GROUP BY ?category ORDER BY ?total LIMIT 10
        "#;

        let parsed = compiler.parse_query(query).expect("unwrap");

        // Check projections
        match &parsed.query_type {
            QueryType::Select {
                projections,
                select_vars,
                ..
            } => {
                assert_eq!(projections.len(), 3);
                assert_eq!(select_vars, &vec!["category", "total", "average"]);
            }
            _ => panic!("Expected SELECT"),
        }

        // Check modifiers
        assert_eq!(parsed.group_by, vec!["category"]);
        assert_eq!(parsed.order_by, vec!["total"]);
        assert_eq!(parsed.limit, Some(10));
    }
}