oxirs-core 0.2.2

Core RDF and SPARQL functionality for OxiRS - native Rust implementation with zero dependencies
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
//! Query execution engine
//!
//! This module executes query plans against RDF stores.

use crate::model::*;
use crate::query::algebra::*;
use crate::query::plan::ExecutionPlan;
use crate::OxirsError;
use crate::Store;
use std::collections::{HashMap, HashSet};

/// A solution mapping (binding of variables to values)
#[derive(Debug, Clone, PartialEq)]
pub struct Solution {
    bindings: HashMap<Variable, Term>,
}

impl Solution {
    /// Creates a new empty solution
    pub fn new() -> Self {
        Solution {
            bindings: HashMap::new(),
        }
    }

    /// Binds a variable to a value
    pub fn bind(&mut self, var: Variable, value: Term) {
        self.bindings.insert(var, value);
    }

    /// Gets the value bound to a variable
    pub fn get(&self, var: &Variable) -> Option<&Term> {
        self.bindings.get(var)
    }

    /// Merges two solutions (for joins)
    pub fn merge(&self, other: &Solution) -> Option<Solution> {
        let mut merged = self.clone();

        for (var, value) in &other.bindings {
            if let Some(existing) = merged.bindings.get(var) {
                if existing != value {
                    return None; // Incompatible bindings
                }
            } else {
                merged.bindings.insert(var.clone(), value.clone());
            }
        }

        Some(merged)
    }

    /// Projects specific variables
    pub fn project(&self, vars: &[Variable]) -> Solution {
        let mut projected = Solution::new();
        for var in vars {
            if let Some(value) = self.bindings.get(var) {
                projected.bind(var.clone(), value.clone());
            }
        }
        projected
    }

    /// Returns an iterator over the variable-term bindings
    pub fn iter(&self) -> std::collections::hash_map::Iter<'_, Variable, Term> {
        self.bindings.iter()
    }

    /// Returns an iterator over the variables in this solution
    pub fn variables(&self) -> impl Iterator<Item = &Variable> {
        self.bindings.keys()
    }
}

/// Query results
#[derive(Debug)]
pub enum QueryResults {
    /// Boolean result (for ASK queries)
    Boolean(bool),
    /// Solutions (for SELECT queries)
    Solutions(Vec<Solution>),
    /// Graph (for CONSTRUCT queries)
    Graph(Vec<Triple>),
}

/// Query executor
pub struct QueryExecutor<'a> {
    store: &'a dyn Store,
}

impl<'a> QueryExecutor<'a> {
    /// Creates a new query executor
    pub fn new(store: &'a dyn Store) -> Self {
        QueryExecutor { store }
    }

    /// Executes a query plan
    pub fn execute(&self, plan: &ExecutionPlan) -> Result<Vec<Solution>, OxirsError> {
        self.execute_plan(plan)
    }

    fn execute_plan(&self, plan: &ExecutionPlan) -> Result<Vec<Solution>, OxirsError> {
        match plan {
            ExecutionPlan::TripleScan { pattern } => self.execute_triple_scan(pattern),
            ExecutionPlan::HashJoin {
                left,
                right,
                join_vars,
            } => self.execute_hash_join(left, right, join_vars),
            ExecutionPlan::Filter { input, condition } => self.execute_filter(input, condition),
            ExecutionPlan::Project { input, vars } => self.execute_project(input, vars),
            ExecutionPlan::Sort { input, order_by } => self.execute_sort(input, order_by),
            ExecutionPlan::Limit {
                input,
                limit,
                offset,
            } => self.execute_limit(input, *limit, *offset),
            ExecutionPlan::Union { left, right } => self.execute_union(left, right),
            ExecutionPlan::Distinct { input } => self.execute_distinct(input),
        }
    }

    fn execute_triple_scan(
        &self,
        pattern: &crate::model::pattern::TriplePattern,
    ) -> Result<Vec<Solution>, OxirsError> {
        let mut solutions = Vec::new();

        // Get all triples from the store
        let triples = self.store.triples()?;

        for triple in triples {
            if let Some(solution) = self.match_triple_pattern(&triple, pattern) {
                solutions.push(solution);
            }
        }

        Ok(solutions)
    }

    fn match_triple_pattern(
        &self,
        triple: &Triple,
        pattern: &crate::model::pattern::TriplePattern,
    ) -> Option<Solution> {
        let mut solution = Solution::new();

        // Match subject
        if let Some(ref subject_pattern) = pattern.subject {
            if !self.match_subject_pattern(triple.subject(), subject_pattern, &mut solution) {
                return None;
            }
        }

        // Match predicate
        if let Some(ref predicate_pattern) = pattern.predicate {
            if !self.match_predicate_pattern(triple.predicate(), predicate_pattern, &mut solution) {
                return None;
            }
        }

        // Match object
        if let Some(ref object_pattern) = pattern.object {
            if !self.match_object_pattern(triple.object(), object_pattern, &mut solution) {
                return None;
            }
        }

        Some(solution)
    }

    #[allow(dead_code)]
    fn match_term_pattern(
        &self,
        term: &Term,
        pattern: &TermPattern,
        solution: &mut Solution,
    ) -> bool {
        match pattern {
            TermPattern::Variable(var) => {
                if let Some(bound_value) = solution.get(var) {
                    bound_value == term
                } else {
                    solution.bind(var.clone(), term.clone());
                    true
                }
            }
            TermPattern::NamedNode(n) => {
                matches!(term, Term::NamedNode(nn) if nn == n)
            }
            TermPattern::BlankNode(b) => {
                matches!(term, Term::BlankNode(bn) if bn == b)
            }
            TermPattern::Literal(l) => {
                matches!(term, Term::Literal(lit) if lit == l)
            }
            TermPattern::QuotedTriple(_) => {
                panic!("RDF-star quoted triples not yet supported in query execution")
            }
        }
    }

    fn match_subject_pattern(
        &self,
        subject: &Subject,
        pattern: &crate::model::pattern::SubjectPattern,
        solution: &mut Solution,
    ) -> bool {
        use crate::model::pattern::SubjectPattern;
        match pattern {
            SubjectPattern::Variable(var) => {
                if let Some(bound_value) = solution.get(var) {
                    match (subject, bound_value) {
                        (Subject::NamedNode(n1), Term::NamedNode(n2)) => n1 == n2,
                        (Subject::BlankNode(b1), Term::BlankNode(b2)) => b1 == b2,
                        _ => false,
                    }
                } else {
                    solution
                        .bindings
                        .insert(var.clone(), Term::from_subject(subject));
                    true
                }
            }
            SubjectPattern::NamedNode(n) => matches!(subject, Subject::NamedNode(nn) if nn == n),
            SubjectPattern::BlankNode(b) => matches!(subject, Subject::BlankNode(bn) if bn == b),
        }
    }

    fn match_predicate_pattern(
        &self,
        predicate: &Predicate,
        pattern: &crate::model::pattern::PredicatePattern,
        solution: &mut Solution,
    ) -> bool {
        use crate::model::pattern::PredicatePattern;
        match pattern {
            PredicatePattern::Variable(var) => {
                if let Some(bound_value) = solution.get(var) {
                    match (predicate, bound_value) {
                        (Predicate::NamedNode(n1), Term::NamedNode(n2)) => n1 == n2,
                        _ => false,
                    }
                } else {
                    solution
                        .bindings
                        .insert(var.clone(), Term::from_predicate(predicate));
                    true
                }
            }
            PredicatePattern::NamedNode(n) => {
                matches!(predicate, Predicate::NamedNode(nn) if nn == n)
            }
        }
    }

    fn match_object_pattern(
        &self,
        object: &Object,
        pattern: &crate::model::pattern::ObjectPattern,
        solution: &mut Solution,
    ) -> bool {
        use crate::model::pattern::ObjectPattern;
        match pattern {
            ObjectPattern::Variable(var) => {
                if let Some(bound_value) = solution.get(var) {
                    match (object, bound_value) {
                        (Object::NamedNode(n1), Term::NamedNode(n2)) => n1 == n2,
                        (Object::BlankNode(b1), Term::BlankNode(b2)) => b1 == b2,
                        (Object::Literal(l1), Term::Literal(l2)) => l1 == l2,
                        _ => false,
                    }
                } else {
                    solution
                        .bindings
                        .insert(var.clone(), Term::from_object(object));
                    true
                }
            }
            ObjectPattern::NamedNode(n) => matches!(object, Object::NamedNode(nn) if nn == n),
            ObjectPattern::BlankNode(b) => matches!(object, Object::BlankNode(bn) if bn == b),
            ObjectPattern::Literal(l) => matches!(object, Object::Literal(lit) if lit == l),
        }
    }

    fn execute_hash_join(
        &self,
        left: &ExecutionPlan,
        right: &ExecutionPlan,
        join_vars: &[Variable],
    ) -> Result<Vec<Solution>, OxirsError> {
        let left_solutions = self.execute_plan(left)?;
        let right_solutions = self.execute_plan(right)?;

        let mut results = Vec::new();

        // Build hash table from left solutions
        let mut hash_table: HashMap<Vec<Term>, Vec<Solution>> = HashMap::new();
        for solution in left_solutions {
            let key: Vec<Term> = join_vars
                .iter()
                .filter_map(|var| solution.get(var).cloned())
                .collect();
            hash_table.entry(key).or_default().push(solution);
        }

        // Probe with right solutions
        for right_solution in right_solutions {
            let key: Vec<Term> = join_vars
                .iter()
                .filter_map(|var| right_solution.get(var).cloned())
                .collect();

            if let Some(left_solutions) = hash_table.get(&key) {
                for left_solution in left_solutions {
                    if let Some(merged) = left_solution.merge(&right_solution) {
                        results.push(merged);
                    }
                }
            }
        }

        Ok(results)
    }

    fn execute_filter(
        &self,
        input: &ExecutionPlan,
        condition: &Expression,
    ) -> Result<Vec<Solution>, OxirsError> {
        let solutions = self.execute_plan(input)?;

        Ok(solutions
            .into_iter()
            .filter(|solution| {
                self.evaluate_expression(condition, solution)
                    .unwrap_or(false)
            })
            .collect())
    }

    fn execute_project(
        &self,
        input: &ExecutionPlan,
        vars: &[Variable],
    ) -> Result<Vec<Solution>, OxirsError> {
        let solutions = self.execute_plan(input)?;

        Ok(solutions
            .into_iter()
            .map(|solution| solution.project(vars))
            .collect())
    }

    fn execute_sort(
        &self,
        input: &ExecutionPlan,
        _order_by: &[OrderExpression],
    ) -> Result<Vec<Solution>, OxirsError> {
        // Placeholder - would implement proper sorting
        self.execute_plan(input)
    }

    fn execute_limit(
        &self,
        input: &ExecutionPlan,
        limit: usize,
        offset: usize,
    ) -> Result<Vec<Solution>, OxirsError> {
        let solutions = self.execute_plan(input)?;

        Ok(solutions.into_iter().skip(offset).take(limit).collect())
    }

    fn execute_union(
        &self,
        left: &ExecutionPlan,
        right: &ExecutionPlan,
    ) -> Result<Vec<Solution>, OxirsError> {
        let mut solutions = self.execute_plan(left)?;
        solutions.extend(self.execute_plan(right)?);
        Ok(solutions)
    }

    fn execute_distinct(&self, input: &ExecutionPlan) -> Result<Vec<Solution>, OxirsError> {
        let solutions = self.execute_plan(input)?;
        let mut seen = HashSet::new();
        let mut distinct_solutions = Vec::new();

        for solution in solutions {
            if seen.insert(format!("{solution:?}")) {
                distinct_solutions.push(solution);
            }
        }

        Ok(distinct_solutions)
    }

    fn evaluate_expression(&self, expr: &Expression, solution: &Solution) -> Option<bool> {
        match expr {
            Expression::Variable(var) => {
                if let Some(term) = solution.get(var) {
                    // Convert term to boolean (non-empty strings and non-zero numbers are true)
                    match term {
                        Term::Literal(lit) => {
                            let value = lit.as_str();
                            match lit.datatype().as_str() {
                                "http://www.w3.org/2001/XMLSchema#boolean" => {
                                    value.parse::<bool>().ok()
                                }
                                "http://www.w3.org/2001/XMLSchema#integer"
                                | "http://www.w3.org/2001/XMLSchema#decimal"
                                | "http://www.w3.org/2001/XMLSchema#double" => {
                                    value.parse::<f64>().map(|n| n != 0.0).ok()
                                }
                                "http://www.w3.org/2001/XMLSchema#string" => {
                                    Some(!value.is_empty())
                                }
                                _ => Some(!value.is_empty()),
                            }
                        }
                        _ => Some(true), // Non-literal terms are considered true
                    }
                } else {
                    Some(false) // Unbound variables are false
                }
            }
            Expression::Literal(lit) => {
                let value = lit.as_str();
                match lit.datatype().as_str() {
                    "http://www.w3.org/2001/XMLSchema#boolean" => value.parse::<bool>().ok(),
                    "http://www.w3.org/2001/XMLSchema#integer"
                    | "http://www.w3.org/2001/XMLSchema#decimal"
                    | "http://www.w3.org/2001/XMLSchema#double" => {
                        value.parse::<f64>().map(|n| n != 0.0).ok()
                    }
                    _ => Some(!value.is_empty()),
                }
            }
            Expression::And(left, right) => {
                let left_result = self.evaluate_expression(left, solution)?;
                let right_result = self.evaluate_expression(right, solution)?;
                Some(left_result && right_result)
            }
            Expression::Or(left, right) => {
                let left_result = self.evaluate_expression(left, solution)?;
                let right_result = self.evaluate_expression(right, solution)?;
                Some(left_result || right_result)
            }
            Expression::Not(expr) => {
                let result = self.evaluate_expression(expr, solution)?;
                Some(!result)
            }
            Expression::Equal(left, right) => {
                let left_term = self.evaluate_expression_to_term(left, solution)?;
                let right_term = self.evaluate_expression_to_term(right, solution)?;
                Some(left_term == right_term)
            }
            Expression::NotEqual(left, right) => {
                let left_term = self.evaluate_expression_to_term(left, solution)?;
                let right_term = self.evaluate_expression_to_term(right, solution)?;
                Some(left_term != right_term)
            }
            Expression::Less(left, right) => {
                self.evaluate_numeric_comparison(left, right, solution, |a, b| a < b)
            }
            Expression::LessOrEqual(left, right) => {
                self.evaluate_numeric_comparison(left, right, solution, |a, b| a <= b)
            }
            Expression::Greater(left, right) => {
                self.evaluate_numeric_comparison(left, right, solution, |a, b| a > b)
            }
            Expression::GreaterOrEqual(left, right) => {
                self.evaluate_numeric_comparison(left, right, solution, |a, b| a >= b)
            }
            Expression::Bound(var) => Some(solution.get(var).is_some()),
            Expression::IsIri(expr) => {
                if let Some(term) = self.evaluate_expression_to_term(expr, solution) {
                    Some(matches!(term, Term::NamedNode(_)))
                } else {
                    Some(false)
                }
            }
            Expression::IsBlank(expr) => {
                if let Some(term) = self.evaluate_expression_to_term(expr, solution) {
                    Some(matches!(term, Term::BlankNode(_)))
                } else {
                    Some(false)
                }
            }
            Expression::IsLiteral(expr) => {
                if let Some(term) = self.evaluate_expression_to_term(expr, solution) {
                    Some(matches!(term, Term::Literal(_)))
                } else {
                    Some(false)
                }
            }
            Expression::IsNumeric(expr) => {
                if let Some(Term::Literal(lit)) = self.evaluate_expression_to_term(expr, solution) {
                    let datatype_str = lit.datatype().as_str().to_string();
                    Some(matches!(
                        datatype_str.as_str(),
                        "http://www.w3.org/2001/XMLSchema#integer"
                            | "http://www.w3.org/2001/XMLSchema#decimal"
                            | "http://www.w3.org/2001/XMLSchema#double"
                            | "http://www.w3.org/2001/XMLSchema#float"
                    ))
                } else {
                    Some(false)
                }
            }
            Expression::Str(expr) => {
                // STR() always succeeds, so it's always "true" for filtering purposes
                Some(self.evaluate_expression_to_term(expr, solution).is_some())
            }
            Expression::Regex(text_expr, pattern_expr, flags_expr) => {
                let text = self.evaluate_expression_to_string(text_expr, solution)?;
                let pattern = self.evaluate_expression_to_string(pattern_expr, solution)?;

                let flags = if let Some(flags_expr) = flags_expr {
                    self.evaluate_expression_to_string(flags_expr, solution)
                        .unwrap_or_default()
                } else {
                    String::new()
                };

                // Basic regex implementation (would need full regex crate for production)
                if flags.is_empty() {
                    Some(text.contains(&pattern))
                } else {
                    // For now, just do case-insensitive matching if 'i' flag is present
                    if flags.contains('i') {
                        Some(text.to_lowercase().contains(&pattern.to_lowercase()))
                    } else {
                        Some(text.contains(&pattern))
                    }
                }
            }
            _ => {
                // For unsupported expressions, default to true
                // This is a simplified implementation
                Some(true)
            }
        }
    }

    /// Evaluate an expression to a term value
    #[allow(clippy::only_used_in_recursion)]
    fn evaluate_expression_to_term(&self, expr: &Expression, solution: &Solution) -> Option<Term> {
        match expr {
            Expression::Variable(var) => solution.get(var).cloned(),
            Expression::Term(term) => Some(term.clone()),
            Expression::FunctionCall(Function::Str, args) => {
                if let Some(arg) = args.first() {
                    if let Some(term) = self.evaluate_expression_to_term(arg, solution) {
                        match term {
                            Term::NamedNode(n) => Some(Term::Literal(Literal::new(n.as_str()))),
                            Term::Literal(l) => Some(Term::Literal(Literal::new(l.as_str()))),
                            Term::BlankNode(b) => Some(Term::Literal(Literal::new(b.as_str()))),
                            _ => None,
                        }
                    } else {
                        None
                    }
                } else {
                    None
                }
            }
            _ => None, // Other expressions don't directly evaluate to terms
        }
    }

    /// Evaluate an expression to a string value
    fn evaluate_expression_to_string(
        &self,
        expr: &Expression,
        solution: &Solution,
    ) -> Option<String> {
        if let Some(term) = self.evaluate_expression_to_term(expr, solution) {
            match term {
                Term::NamedNode(n) => Some(n.as_str().to_string()),
                Term::Literal(l) => Some(l.as_str().to_string()),
                Term::BlankNode(b) => Some(b.as_str().to_string()),
                _ => None,
            }
        } else {
            None
        }
    }

    /// Evaluate a numeric comparison
    fn evaluate_numeric_comparison<F>(
        &self,
        left: &Expression,
        right: &Expression,
        solution: &Solution,
        comparator: F,
    ) -> Option<bool>
    where
        F: Fn(f64, f64) -> bool,
    {
        let left_val = self.evaluate_expression_to_numeric(left, solution)?;
        let right_val = self.evaluate_expression_to_numeric(right, solution)?;
        Some(comparator(left_val, right_val))
    }

    /// Evaluate an expression to a numeric value
    fn evaluate_expression_to_numeric(
        &self,
        expr: &Expression,
        solution: &Solution,
    ) -> Option<f64> {
        if let Some(Term::Literal(lit)) = self.evaluate_expression_to_term(expr, solution) {
            let value = lit.as_str();
            match lit.datatype().as_str() {
                "http://www.w3.org/2001/XMLSchema#integer"
                | "http://www.w3.org/2001/XMLSchema#decimal"
                | "http://www.w3.org/2001/XMLSchema#double"
                | "http://www.w3.org/2001/XMLSchema#float" => value.parse::<f64>().ok(),
                _ => None,
            }
        } else {
            None
        }
    }
}

impl Default for Solution {
    fn default() -> Self {
        Self::new()
    }
}