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
//! SPARQL 1.1 Query Algebra representation
//!
//! Based on the W3C SPARQL 1.1 Query specification:
//! <https://www.w3.org/TR/sparql11-query/#sparqlQuery>

use crate::model::*;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fmt;

// Re-export TriplePattern from model for public access
pub use crate::model::pattern::TriplePattern;

/// A property path expression for navigating RDF graphs
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum PropertyPath {
    /// A simple predicate path
    Predicate(NamedNode),
    /// Inverse path: ^path
    Inverse(Box<PropertyPath>),
    /// Sequence path: path1 / path2
    Sequence(Box<PropertyPath>, Box<PropertyPath>),
    /// Alternative path: path1 | path2
    Alternative(Box<PropertyPath>, Box<PropertyPath>),
    /// Zero or more: path*
    ZeroOrMore(Box<PropertyPath>),
    /// One or more: path+
    OneOrMore(Box<PropertyPath>),
    /// Zero or one: path?
    ZeroOrOne(Box<PropertyPath>),
    /// Negated property set: !(p1 | p2 | ...)
    NegatedPropertySet(Vec<NamedNode>),
}

impl fmt::Display for PropertyPath {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            PropertyPath::Predicate(p) => write!(f, "{p}"),
            PropertyPath::Inverse(p) => write!(f, "^{p}"),
            PropertyPath::Sequence(a, b) => write!(f, "({a} / {b})"),
            PropertyPath::Alternative(a, b) => write!(f, "({a} | {b})"),
            PropertyPath::ZeroOrMore(p) => write!(f, "({p})*"),
            PropertyPath::OneOrMore(p) => write!(f, "({p})+"),
            PropertyPath::ZeroOrOne(p) => write!(f, "({p})?"),
            PropertyPath::NegatedPropertySet(ps) => {
                write!(f, "!(")?;
                for (i, p) in ps.iter().enumerate() {
                    if i > 0 {
                        write!(f, " | ")?;
                    }
                    write!(f, "{p}")?;
                }
                write!(f, ")")
            }
        }
    }
}

/// A SPARQL expression
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum Expression {
    /// A constant term
    Term(Term),
    /// A variable
    Variable(Variable),
    /// Logical AND
    And(Box<Expression>, Box<Expression>),
    /// Logical OR
    Or(Box<Expression>, Box<Expression>),
    /// Logical NOT
    Not(Box<Expression>),
    /// Equality: =
    Equal(Box<Expression>, Box<Expression>),
    /// Inequality: !=
    NotEqual(Box<Expression>, Box<Expression>),
    /// Less than: <
    Less(Box<Expression>, Box<Expression>),
    /// Less than or equal: <=
    LessOrEqual(Box<Expression>, Box<Expression>),
    /// Greater than: >
    Greater(Box<Expression>, Box<Expression>),
    /// Greater than or equal: >=
    GreaterOrEqual(Box<Expression>, Box<Expression>),
    /// Addition: +
    Add(Box<Expression>, Box<Expression>),
    /// Subtraction: -
    Subtract(Box<Expression>, Box<Expression>),
    /// Multiplication: *
    Multiply(Box<Expression>, Box<Expression>),
    /// Division: /
    Divide(Box<Expression>, Box<Expression>),
    /// Unary plus: +expr
    UnaryPlus(Box<Expression>),
    /// Unary minus: -expr
    UnaryMinus(Box<Expression>),
    /// IN expression
    In(Box<Expression>, Vec<Expression>),
    /// NOT IN expression
    NotIn(Box<Expression>, Vec<Expression>),
    /// EXISTS pattern
    Exists(Box<GraphPattern>),
    /// NOT EXISTS pattern
    NotExists(Box<GraphPattern>),
    /// Function call
    FunctionCall(Function, Vec<Expression>),
    /// Bound variable test
    Bound(Variable),
    /// IF expression
    If(Box<Expression>, Box<Expression>, Box<Expression>),
    /// COALESCE expression
    Coalesce(Vec<Expression>),
    /// Literal value
    Literal(crate::model::Literal),
    /// Test if term is IRI
    IsIri(Box<Expression>),
    /// Test if term is blank node
    IsBlank(Box<Expression>),
    /// Test if term is literal
    IsLiteral(Box<Expression>),
    /// Test if term is numeric
    IsNumeric(Box<Expression>),
    /// String value of term
    Str(Box<Expression>),
    /// Regular expression matching
    Regex(Box<Expression>, Box<Expression>, Option<Box<Expression>>),
}

/// Built-in SPARQL functions
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Function {
    // String functions
    Str,
    Lang,
    LangMatches,
    Datatype,
    Iri,
    Bnode,
    StrDt,
    StrLang,
    StrLen,
    SubStr,
    UCase,
    LCase,
    StrStarts,
    StrEnds,
    Contains,
    StrBefore,
    StrAfter,
    Encode,
    Concat,
    Replace,
    Regex,

    // Numeric functions
    Abs,
    Round,
    Ceil,
    Floor,
    Rand,

    // Date/Time functions
    Now,
    Year,
    Month,
    Day,
    Hours,
    Minutes,
    Seconds,
    Timezone,
    Tz,

    // Hash functions
    Md5,
    Sha1,
    Sha256,
    Sha384,
    Sha512,

    // Type checking
    IsIri,
    IsBlank,
    IsLiteral,
    IsNumeric,

    // Custom function
    Custom(NamedNode),
}

/// A triple pattern in SPARQL algebra (all positions must be specified)
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct AlgebraTriplePattern {
    pub subject: TermPattern,
    pub predicate: TermPattern,
    pub object: TermPattern,
}

impl AlgebraTriplePattern {
    /// Create a new algebra triple pattern
    pub fn new(subject: TermPattern, predicate: TermPattern, object: TermPattern) -> Self {
        Self {
            subject,
            predicate,
            object,
        }
    }

    /// Formats using the SPARQL S-Expression syntax
    pub fn fmt_sse(&self, f: &mut impl fmt::Write) -> fmt::Result {
        f.write_str("(triple ")?;
        self.subject.fmt_sse(f)?;
        f.write_str(" ")?;
        self.predicate.fmt_sse(f)?;
        f.write_str(" ")?;
        self.object.fmt_sse(f)?;
        f.write_str(")")
    }
}

impl fmt::Display for AlgebraTriplePattern {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} {} {}", self.subject, self.predicate, self.object)
    }
}

impl From<crate::model::pattern::TriplePattern> for Option<AlgebraTriplePattern> {
    fn from(pattern: crate::model::pattern::TriplePattern) -> Self {
        use crate::model::pattern::{ObjectPattern, PredicatePattern, SubjectPattern};

        let subject = match pattern.subject? {
            SubjectPattern::NamedNode(n) => TermPattern::NamedNode(n),
            SubjectPattern::BlankNode(b) => TermPattern::BlankNode(b),
            SubjectPattern::Variable(v) => TermPattern::Variable(v),
        };

        let predicate = match pattern.predicate? {
            PredicatePattern::NamedNode(n) => TermPattern::NamedNode(n),
            PredicatePattern::Variable(v) => TermPattern::Variable(v),
        };

        let object = match pattern.object? {
            ObjectPattern::NamedNode(n) => TermPattern::NamedNode(n),
            ObjectPattern::BlankNode(b) => TermPattern::BlankNode(b),
            ObjectPattern::Literal(l) => TermPattern::Literal(l),
            ObjectPattern::Variable(v) => TermPattern::Variable(v),
        };

        Some(AlgebraTriplePattern::new(subject, predicate, object))
    }
}

/// A term pattern (can be a concrete term or variable)
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum TermPattern {
    NamedNode(NamedNode),
    BlankNode(BlankNode),
    Literal(Literal),
    Variable(Variable),
    /// Quoted triple pattern for RDF-star support
    QuotedTriple(Box<AlgebraTriplePattern>),
}

impl From<Variable> for TermPattern {
    fn from(v: Variable) -> Self {
        TermPattern::Variable(v)
    }
}

impl From<NamedNode> for TermPattern {
    fn from(n: NamedNode) -> Self {
        TermPattern::NamedNode(n)
    }
}

impl From<BlankNode> for TermPattern {
    fn from(b: BlankNode) -> Self {
        TermPattern::BlankNode(b)
    }
}

impl From<Literal> for TermPattern {
    fn from(l: Literal) -> Self {
        TermPattern::Literal(l)
    }
}

impl TermPattern {
    /// Check if this pattern is a variable
    pub fn is_variable(&self) -> bool {
        matches!(self, TermPattern::Variable(_))
    }

    /// Formats using the SPARQL S-Expression syntax
    pub fn fmt_sse(&self, f: &mut impl fmt::Write) -> fmt::Result {
        match self {
            TermPattern::NamedNode(node) => write!(f, "{node}"),
            TermPattern::BlankNode(node) => write!(f, "{node}"),
            TermPattern::Literal(literal) => write!(f, "{literal}"),
            TermPattern::Variable(var) => write!(f, "{var}"),
            TermPattern::QuotedTriple(triple) => {
                write!(f, "<<")?;
                triple.subject.fmt_sse(f)?;
                write!(f, " ")?;
                triple.predicate.fmt_sse(f)?;
                write!(f, " ")?;
                triple.object.fmt_sse(f)?;
                write!(f, ">>")
            }
        }
    }
}

impl fmt::Display for TermPattern {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            TermPattern::NamedNode(n) => write!(f, "{n}"),
            TermPattern::BlankNode(b) => write!(f, "{b}"),
            TermPattern::Literal(l) => write!(f, "{l}"),
            TermPattern::Variable(v) => write!(f, "{v}"),
            TermPattern::QuotedTriple(triple) => {
                write!(
                    f,
                    "<<{} {} {}>>",
                    triple.subject, triple.predicate, triple.object
                )
            }
        }
    }
}

/// A graph pattern
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum GraphPattern {
    /// Basic graph pattern (set of triple patterns)
    Bgp(Vec<AlgebraTriplePattern>),
    /// Path pattern
    Path {
        subject: TermPattern,
        path: PropertyPath,
        object: TermPattern,
    },
    /// Join of two patterns
    Join(Box<GraphPattern>, Box<GraphPattern>),
    /// Left join (OPTIONAL)
    LeftJoin {
        left: Box<GraphPattern>,
        right: Box<GraphPattern>,
        condition: Option<Expression>,
    },
    /// Filter pattern
    Filter {
        expr: Expression,
        inner: Box<GraphPattern>,
    },
    /// Union of patterns
    Union(Box<GraphPattern>, Box<GraphPattern>),
    /// Graph pattern (GRAPH)
    Graph {
        graph_name: TermPattern,
        inner: Box<GraphPattern>,
    },
    /// Service pattern (federated query)
    Service {
        service: TermPattern,
        inner: Box<GraphPattern>,
        silent: bool,
    },
    /// Group pattern
    Group {
        inner: Box<GraphPattern>,
        variables: Vec<Variable>,
        aggregates: Vec<(Variable, AggregateExpression)>,
    },
    /// Extend pattern (BIND)
    Extend {
        inner: Box<GraphPattern>,
        variable: Variable,
        expression: Expression,
    },
    /// Minus pattern
    Minus(Box<GraphPattern>, Box<GraphPattern>),
    /// Values pattern
    Values {
        variables: Vec<Variable>,
        bindings: Vec<Vec<Option<Term>>>,
    },
    /// Order by pattern
    OrderBy {
        inner: Box<GraphPattern>,
        order_by: Vec<OrderExpression>,
    },
    /// Project pattern
    Project {
        inner: Box<GraphPattern>,
        variables: Vec<Variable>,
    },
    /// Distinct pattern
    Distinct(Box<GraphPattern>),
    /// Reduced pattern
    Reduced(Box<GraphPattern>),
    /// Slice pattern (LIMIT/OFFSET)
    Slice {
        inner: Box<GraphPattern>,
        offset: usize,
        limit: Option<usize>,
    },
}

/// Aggregate expressions
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum AggregateExpression {
    Count {
        expr: Option<Box<Expression>>,
        distinct: bool,
    },
    Sum {
        expr: Box<Expression>,
        distinct: bool,
    },
    Avg {
        expr: Box<Expression>,
        distinct: bool,
    },
    Min {
        expr: Box<Expression>,
        distinct: bool,
    },
    Max {
        expr: Box<Expression>,
        distinct: bool,
    },
    GroupConcat {
        expr: Box<Expression>,
        distinct: bool,
        separator: Option<String>,
    },
    Sample {
        expr: Box<Expression>,
        distinct: bool,
    },
}

/// Order expression for ORDER BY
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum OrderExpression {
    Asc(Expression),
    Desc(Expression),
}

/// SPARQL query forms
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum QueryForm {
    /// SELECT query
    Select {
        /// SELECT * or specific variables
        variables: SelectVariables,
        /// WHERE clause pattern
        where_clause: GraphPattern,
        /// Solution modifiers
        distinct: bool,
        reduced: bool,
        order_by: Vec<OrderExpression>,
        offset: usize,
        limit: Option<usize>,
    },
    /// CONSTRUCT query
    Construct {
        /// Template for constructing triples
        template: Vec<AlgebraTriplePattern>,
        /// WHERE clause pattern
        where_clause: GraphPattern,
        /// Solution modifiers
        order_by: Vec<OrderExpression>,
        offset: usize,
        limit: Option<usize>,
    },
    /// DESCRIBE query
    Describe {
        /// Resources to describe
        resources: Vec<TermPattern>,
        /// Optional WHERE clause
        where_clause: Option<GraphPattern>,
        /// Solution modifiers
        order_by: Vec<OrderExpression>,
        offset: usize,
        limit: Option<usize>,
    },
    /// ASK query
    Ask {
        /// Pattern to check
        where_clause: GraphPattern,
    },
}

/// Variables selection in SELECT
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum SelectVariables {
    /// SELECT *
    All,
    /// SELECT ?var1 ?var2 ...
    Specific(Vec<Variable>),
}

/// A complete SPARQL query
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Query {
    /// Base IRI for relative IRI resolution
    pub base: Option<NamedNode>,
    /// Namespace prefixes
    pub prefixes: HashMap<String, NamedNode>,
    /// Query form
    pub form: QueryForm,
    /// Dataset specification
    pub dataset: Dataset,
}

/// Dataset specification for a query
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct Dataset {
    /// Default graph IRIs (FROM)
    pub default: Vec<NamedNode>,
    /// Named graph IRIs (FROM NAMED)
    pub named: Vec<NamedNode>,
}

/// SPARQL Update operations
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum UpdateOperation {
    /// INSERT DATA
    InsertData { data: Vec<Quad> },
    /// DELETE DATA
    DeleteData { data: Vec<Quad> },
    /// DELETE WHERE
    DeleteWhere { pattern: Vec<QuadPattern> },
    /// INSERT/DELETE with WHERE
    Modify {
        delete: Option<Vec<QuadPattern>>,
        insert: Option<Vec<QuadPattern>>,
        where_clause: Box<GraphPattern>,
        using: Dataset,
    },
    /// LOAD
    Load {
        source: NamedNode,
        destination: Option<NamedNode>,
        silent: bool,
    },
    /// CLEAR
    Clear { graph: GraphTarget, silent: bool },
    /// CREATE
    Create { graph: NamedNode, silent: bool },
    /// DROP
    Drop { graph: GraphTarget, silent: bool },
    /// COPY
    Copy {
        source: GraphTarget,
        destination: GraphTarget,
        silent: bool,
    },
    /// MOVE
    Move {
        source: GraphTarget,
        destination: GraphTarget,
        silent: bool,
    },
    /// ADD
    Add {
        source: GraphTarget,
        destination: GraphTarget,
        silent: bool,
    },
}

/// Graph targets for update operations
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum GraphTarget {
    Default,
    Named(NamedNode),
    All,
}

/// Quad pattern for updates
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct QuadPattern {
    pub subject: TermPattern,
    pub predicate: TermPattern,
    pub object: TermPattern,
    pub graph: Option<TermPattern>,
}

/// A SPARQL Update request
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Update {
    /// Base IRI for relative IRI resolution
    pub base: Option<NamedNode>,
    /// Namespace prefixes
    pub prefixes: HashMap<String, NamedNode>,
    /// Update operations
    pub operations: Vec<UpdateOperation>,
}