Skip to main content

ng_oxigraph/spargebra/
term.rs

1// partial Copyright (c) 2022-2025 Niko Bonnieure, Par le Peuple, NextGraph.org developers
2// All rights reserved.
3// partial Copyright (c) 2018 Oxigraph developers
4// All work licensed under the Apache License, Version 2.0
5// <LICENSE-APACHE2 or http://www.apache.org/licenses/LICENSE-2.0>
6// or the MIT license <LICENSE-MIT or http://opensource.org/licenses/MIT>,
7// at your option. All files in the project carrying such
8// notice or not, may not be copied, modified, or distributed except
9// according to those terms.
10
11//! Data structures for [RDF 1.1 Concepts](https://www.w3.org/TR/rdf11-concepts/) like IRI, literal or triples.
12
13pub use crate::oxrdf::{BlankNode, Literal, NamedNode, Subject, Term, Triple, Variable};
14use std::fmt;
15use std::fmt::Write;
16
17/// The union of [IRIs](https://www.w3.org/TR/rdf11-concepts/#dfn-iri) and [triples](https://www.w3.org/TR/rdf11-concepts/#dfn-rdf-triple).
18///
19/// The default string formatter is returning an N-Triples, Turtle, and SPARQL compatible representation.
20#[derive(Eq, PartialEq, Debug, Clone, Hash)]
21pub enum GroundSubject {
22    NamedNode(NamedNode),
23    #[cfg(feature = "rdf-star")]
24    Triple(Box<GroundTriple>),
25}
26
27impl fmt::Display for GroundSubject {
28    #[inline]
29    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
30        match self {
31            Self::NamedNode(node) => node.fmt(f),
32            #[cfg(feature = "rdf-star")]
33            Self::Triple(triple) => write!(
34                f,
35                "<<{} {} {}>>",
36                triple.subject, triple.predicate, triple.object
37            ),
38        }
39    }
40}
41
42impl From<NamedNode> for GroundSubject {
43    #[inline]
44    fn from(node: NamedNode) -> Self {
45        Self::NamedNode(node)
46    }
47}
48
49#[cfg(feature = "rdf-star")]
50impl From<GroundTriple> for GroundSubject {
51    #[inline]
52    fn from(triple: GroundTriple) -> Self {
53        Self::Triple(Box::new(triple))
54    }
55}
56
57impl TryFrom<Subject> for GroundSubject {
58    type Error = ();
59
60    #[inline]
61    fn try_from(subject: Subject) -> Result<Self, Self::Error> {
62        match subject {
63            Subject::NamedNode(t) => Ok(t.into()),
64            Subject::BlankNode(_) => Err(()),
65            #[cfg(feature = "rdf-star")]
66            Subject::Triple(t) => Ok(GroundTriple::try_from(*t)?.into()),
67        }
68    }
69}
70
71impl TryFrom<GroundTerm> for GroundSubject {
72    type Error = ();
73
74    #[inline]
75    fn try_from(term: GroundTerm) -> Result<Self, Self::Error> {
76        match term {
77            GroundTerm::NamedNode(t) => Ok(t.into()),
78            GroundTerm::Literal(_) => Err(()),
79            #[cfg(feature = "rdf-star")]
80            GroundTerm::Triple(t) => Ok((*t).into()),
81        }
82    }
83}
84
85/// The union of [IRIs](https://www.w3.org/TR/rdf11-concepts/#dfn-iri), [literals](https://www.w3.org/TR/rdf11-concepts/#dfn-literal) and [triples](https://www.w3.org/TR/rdf11-concepts/#dfn-rdf-triple).
86///
87/// The default string formatter is returning an N-Triples, Turtle, and SPARQL compatible representation.
88#[derive(Eq, PartialEq, Debug, Clone, Hash)]
89pub enum GroundTerm {
90    NamedNode(NamedNode),
91    Literal(Literal),
92    #[cfg(feature = "rdf-star")]
93    Triple(Box<GroundTriple>),
94}
95
96impl fmt::Display for GroundTerm {
97    #[inline]
98    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99        match self {
100            Self::NamedNode(node) => node.fmt(f),
101            Self::Literal(literal) => literal.fmt(f),
102            #[cfg(feature = "rdf-star")]
103            Self::Triple(triple) => write!(
104                f,
105                "<<{} {} {}>>",
106                triple.subject, triple.predicate, triple.object
107            ),
108        }
109    }
110}
111
112impl From<NamedNode> for GroundTerm {
113    #[inline]
114    fn from(node: NamedNode) -> Self {
115        Self::NamedNode(node)
116    }
117}
118
119impl From<Literal> for GroundTerm {
120    #[inline]
121    fn from(literal: Literal) -> Self {
122        Self::Literal(literal)
123    }
124}
125
126#[cfg(feature = "rdf-star")]
127impl From<GroundTriple> for GroundTerm {
128    #[inline]
129    fn from(triple: GroundTriple) -> Self {
130        Self::Triple(Box::new(triple))
131    }
132}
133
134impl TryFrom<Term> for GroundTerm {
135    type Error = ();
136
137    #[inline]
138    fn try_from(term: Term) -> Result<Self, Self::Error> {
139        match term {
140            Term::NamedNode(t) => Ok(t.into()),
141            Term::BlankNode(_) => Err(()),
142            Term::Literal(t) => Ok(t.into()),
143            #[cfg(feature = "rdf-star")]
144            Term::Triple(t) => Ok(GroundTriple::try_from(*t)?.into()),
145        }
146    }
147}
148
149/// A [RDF triple](https://www.w3.org/TR/rdf11-concepts/#dfn-rdf-triple) without blank nodes.
150///
151/// The default string formatter is returning a N-Quads representation.
152///
153/// ```
154/// use spargebra::term::{GroundTriple, NamedNode};
155///
156/// assert_eq!(
157///     "<http://example.com/s> <http://example.com/p> <http://example.com/o>",
158///     GroundTriple {
159///         subject: NamedNode::new("http://example.com/s")?.into(),
160///         predicate: NamedNode::new("http://example.com/p")?,
161///         object: NamedNode::new("http://example.com/o")?.into(),
162///     }
163///     .to_string()
164/// );
165/// # Result::<_,oxrdf::IriParseError>::Ok(())
166/// ```
167#[derive(Eq, PartialEq, Debug, Clone, Hash)]
168pub struct GroundTriple {
169    pub subject: GroundSubject,
170    pub predicate: NamedNode,
171    pub object: GroundTerm,
172}
173
174impl fmt::Display for GroundTriple {
175    #[inline]
176    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
177        write!(f, "{} {} {}", self.subject, self.predicate, self.object)
178    }
179}
180
181impl TryFrom<Triple> for GroundTriple {
182    type Error = ();
183
184    #[inline]
185    fn try_from(triple: Triple) -> Result<Self, Self::Error> {
186        Ok(Self {
187            subject: triple.subject.try_into()?,
188            predicate: triple.predicate,
189            object: triple.object.try_into()?,
190        })
191    }
192}
193
194/// A possible graph name.
195///
196/// It is the union of [IRIs](https://www.w3.org/TR/rdf11-concepts/#dfn-iri) and the [default graph name](https://www.w3.org/TR/rdf11-concepts/#dfn-default-graph).
197#[derive(Eq, PartialEq, Debug, Clone, Hash, Default)]
198pub enum GraphName {
199    NamedNode(NamedNode),
200    #[default]
201    DefaultGraph,
202}
203
204impl GraphName {
205    // pub(crate) fn is_default_graph(&self) -> bool {
206    //     match self {
207    //         GraphName::DefaultGraph => true,
208    //         _ => false,
209    //     }
210    // }
211    /// Formats using the [SPARQL S-Expression syntax](https://jena.apache.org/documentation/notes/sse.html).
212    pub(crate) fn fmt_sse(&self, f: &mut impl Write) -> fmt::Result {
213        match self {
214            Self::NamedNode(node) => write!(f, "{node}"),
215            Self::DefaultGraph => f.write_str("default"),
216        }
217    }
218}
219
220impl fmt::Display for GraphName {
221    #[inline]
222    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
223        match self {
224            Self::NamedNode(node) => node.fmt(f),
225            Self::DefaultGraph => f.write_str("DEFAULT"),
226        }
227    }
228}
229
230impl From<NamedNode> for GraphName {
231    #[inline]
232    fn from(node: NamedNode) -> Self {
233        Self::NamedNode(node)
234    }
235}
236
237impl TryFrom<GraphNamePattern> for GraphName {
238    type Error = ();
239
240    #[inline]
241    fn try_from(pattern: GraphNamePattern) -> Result<Self, Self::Error> {
242        match pattern {
243            GraphNamePattern::NamedNode(t) => Ok(t.into()),
244            GraphNamePattern::DefaultGraph => Ok(Self::DefaultGraph),
245            GraphNamePattern::Variable(_) => Err(()),
246        }
247    }
248}
249
250/// A [RDF triple](https://www.w3.org/TR/rdf11-concepts/#dfn-rdf-triple) in an [RDF dataset](https://www.w3.org/TR/rdf11-concepts/#dfn-rdf-dataset).
251///
252/// The default string formatter is returning a N-Quads representation.
253///
254/// ```
255/// use spargebra::term::{NamedNode, Quad};
256///
257/// assert_eq!(
258///     "<http://example.com/s> <http://example.com/p> <http://example.com/o> <http://example.com/g>",
259///     Quad {
260///         subject: NamedNode::new("http://example.com/s")?.into(),
261///         predicate: NamedNode::new("http://example.com/p")?,
262///         object: NamedNode::new("http://example.com/o")?.into(),
263///         graph_name: NamedNode::new("http://example.com/g")?.into(),
264///     }.to_string()
265/// );
266/// # Result::<_,oxrdf::IriParseError>::Ok(())
267/// ```
268#[derive(Eq, PartialEq, Debug, Clone, Hash)]
269pub struct Quad {
270    pub subject: Subject,
271    pub predicate: NamedNode,
272    pub object: Term,
273    pub graph_name: GraphName,
274}
275
276impl Quad {
277    /// Formats using the [SPARQL S-Expression syntax](https://jena.apache.org/documentation/notes/sse.html).
278    pub(crate) fn fmt_sse(&self, f: &mut impl Write) -> fmt::Result {
279        if self.graph_name != GraphName::DefaultGraph {
280            f.write_str("(graph ")?;
281            self.graph_name.fmt_sse(f)?;
282            f.write_str(" (")?;
283        }
284        write!(
285            f,
286            "(triple {} {} {})",
287            self.subject, self.predicate, self.object
288        )?;
289        if self.graph_name != GraphName::DefaultGraph {
290            f.write_str("))")?;
291        }
292        Ok(())
293    }
294}
295
296impl fmt::Display for Quad {
297    #[inline]
298    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
299        if self.graph_name == GraphName::DefaultGraph {
300            write!(f, "{} {} {}", self.subject, self.predicate, self.object)
301        } else {
302            write!(
303                f,
304                "{} {} {} {}",
305                self.subject, self.predicate, self.object, self.graph_name
306            )
307        }
308    }
309}
310
311impl TryFrom<QuadPattern> for Quad {
312    type Error = ();
313
314    #[inline]
315    fn try_from(quad: QuadPattern) -> Result<Self, Self::Error> {
316        Ok(Self {
317            subject: quad.subject.try_into()?,
318            predicate: quad.predicate.try_into()?,
319            object: quad.object.try_into()?,
320            graph_name: quad.graph_name.try_into()?,
321        })
322    }
323}
324
325/// A [RDF triple](https://www.w3.org/TR/rdf11-concepts/#dfn-rdf-triple) in an [RDF dataset](https://www.w3.org/TR/rdf11-concepts/#dfn-rdf-dataset) without blank nodes.
326///
327/// The default string formatter is returning a N-Quads representation.
328///
329/// ```
330/// use spargebra::term::{NamedNode, GroundQuad};
331///
332/// assert_eq!(
333///     "<http://example.com/s> <http://example.com/p> <http://example.com/o> <http://example.com/g>",
334///     GroundQuad {
335///         subject: NamedNode::new("http://example.com/s")?.into(),
336///         predicate: NamedNode::new("http://example.com/p")?,
337///         object: NamedNode::new("http://example.com/o")?.into(),
338///         graph_name: NamedNode::new("http://example.com/g")?.into(),
339///     }.to_string()
340/// );
341/// # Result::<_,oxrdf::IriParseError>::Ok(())
342/// ```
343#[derive(Eq, PartialEq, Debug, Clone, Hash)]
344pub struct GroundQuad {
345    pub subject: GroundSubject,
346    pub predicate: NamedNode,
347    pub object: GroundTerm,
348    pub graph_name: GraphName,
349}
350
351impl GroundQuad {
352    /// Formats using the [SPARQL S-Expression syntax](https://jena.apache.org/documentation/notes/sse.html).
353    pub(crate) fn fmt_sse(&self, f: &mut impl Write) -> fmt::Result {
354        if self.graph_name != GraphName::DefaultGraph {
355            f.write_str("(graph ")?;
356            self.graph_name.fmt_sse(f)?;
357            f.write_str(" (")?;
358        }
359        write!(
360            f,
361            "(triple {} {} {})",
362            self.subject, self.predicate, self.object
363        )?;
364        if self.graph_name != GraphName::DefaultGraph {
365            f.write_str("))")?;
366        }
367        Ok(())
368    }
369}
370
371impl fmt::Display for GroundQuad {
372    #[inline]
373    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
374        if self.graph_name == GraphName::DefaultGraph {
375            write!(f, "{} {} {}", self.subject, self.predicate, self.object)
376        } else {
377            write!(
378                f,
379                "{} {} {} {}",
380                self.subject, self.predicate, self.object, self.graph_name
381            )
382        }
383    }
384}
385
386impl TryFrom<Quad> for GroundQuad {
387    type Error = ();
388
389    #[inline]
390    fn try_from(quad: Quad) -> Result<Self, Self::Error> {
391        Ok(Self {
392            subject: quad.subject.try_into()?,
393            predicate: quad.predicate,
394            object: quad.object.try_into()?,
395            graph_name: quad.graph_name,
396        })
397    }
398}
399
400/// The union of [IRIs](https://www.w3.org/TR/rdf11-concepts/#dfn-iri) and [variables](https://www.w3.org/TR/sparql11-query/#sparqlQueryVariables).
401#[derive(Eq, PartialEq, Debug, Clone, Hash)]
402pub enum NamedNodePattern {
403    NamedNode(NamedNode),
404    Variable(Variable),
405}
406
407impl NamedNodePattern {
408    /// Formats using the [SPARQL S-Expression syntax](https://jena.apache.org/documentation/notes/sse.html).
409    pub(crate) fn fmt_sse(&self, f: &mut impl Write) -> fmt::Result {
410        match self {
411            Self::NamedNode(node) => write!(f, "{node}"),
412            Self::Variable(var) => write!(f, "{var}"),
413        }
414    }
415}
416
417impl fmt::Display for NamedNodePattern {
418    #[inline]
419    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
420        match self {
421            Self::NamedNode(node) => node.fmt(f),
422            Self::Variable(var) => var.fmt(f),
423        }
424    }
425}
426
427impl From<NamedNode> for NamedNodePattern {
428    #[inline]
429    fn from(node: NamedNode) -> Self {
430        Self::NamedNode(node)
431    }
432}
433
434impl From<Variable> for NamedNodePattern {
435    #[inline]
436    fn from(var: Variable) -> Self {
437        Self::Variable(var)
438    }
439}
440
441impl TryFrom<NamedNodePattern> for NamedNode {
442    type Error = ();
443
444    #[inline]
445    fn try_from(pattern: NamedNodePattern) -> Result<Self, Self::Error> {
446        match pattern {
447            NamedNodePattern::NamedNode(t) => Ok(t),
448            NamedNodePattern::Variable(_) => Err(()),
449        }
450    }
451}
452
453/// The union of [terms](https://www.w3.org/TR/rdf11-concepts/#dfn-rdf-term) and [variables](https://www.w3.org/TR/sparql11-query/#sparqlQueryVariables).
454#[derive(Eq, PartialEq, Debug, Clone, Hash)]
455pub enum TermPattern {
456    NamedNode(NamedNode),
457    BlankNode(BlankNode),
458    Literal(Literal),
459    #[cfg(feature = "rdf-star")]
460    Triple(Box<TriplePattern>),
461    Variable(Variable),
462}
463
464impl TermPattern {
465    /// Formats using the [SPARQL S-Expression syntax](https://jena.apache.org/documentation/notes/sse.html).
466    pub(crate) fn fmt_sse(&self, f: &mut impl Write) -> fmt::Result {
467        match self {
468            Self::NamedNode(term) => write!(f, "{term}"),
469            Self::BlankNode(term) => write!(f, "{term}"),
470            Self::Literal(term) => write!(f, "{term}"),
471            #[cfg(feature = "rdf-star")]
472            Self::Triple(triple) => triple.fmt_sse(f),
473            Self::Variable(var) => write!(f, "{var}"),
474        }
475    }
476}
477
478impl fmt::Display for TermPattern {
479    #[inline]
480    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
481        match self {
482            Self::NamedNode(term) => term.fmt(f),
483            Self::BlankNode(term) => term.fmt(f),
484            Self::Literal(term) => term.fmt(f),
485            #[cfg(feature = "rdf-star")]
486            Self::Triple(triple) => write!(f, "<<{triple}>>"),
487            Self::Variable(var) => var.fmt(f),
488        }
489    }
490}
491
492impl From<NamedNode> for TermPattern {
493    #[inline]
494    fn from(node: NamedNode) -> Self {
495        Self::NamedNode(node)
496    }
497}
498
499impl From<BlankNode> for TermPattern {
500    #[inline]
501    fn from(node: BlankNode) -> Self {
502        Self::BlankNode(node)
503    }
504}
505
506impl From<Literal> for TermPattern {
507    #[inline]
508    fn from(literal: Literal) -> Self {
509        Self::Literal(literal)
510    }
511}
512
513#[cfg(feature = "rdf-star")]
514impl From<TriplePattern> for TermPattern {
515    #[inline]
516    fn from(triple: TriplePattern) -> Self {
517        Self::Triple(Box::new(triple))
518    }
519}
520
521impl From<Variable> for TermPattern {
522    fn from(var: Variable) -> Self {
523        Self::Variable(var)
524    }
525}
526
527impl From<Subject> for TermPattern {
528    #[inline]
529    fn from(subject: Subject) -> Self {
530        match subject {
531            Subject::NamedNode(node) => node.into(),
532            Subject::BlankNode(node) => node.into(),
533            #[cfg(feature = "rdf-star")]
534            Subject::Triple(t) => TriplePattern::from(*t).into(),
535        }
536    }
537}
538
539impl From<Term> for TermPattern {
540    #[inline]
541    fn from(term: Term) -> Self {
542        match term {
543            Term::NamedNode(node) => node.into(),
544            Term::BlankNode(node) => node.into(),
545            Term::Literal(literal) => literal.into(),
546            #[cfg(feature = "rdf-star")]
547            Term::Triple(t) => TriplePattern::from(*t).into(),
548        }
549    }
550}
551
552impl From<NamedNodePattern> for TermPattern {
553    #[inline]
554    fn from(element: NamedNodePattern) -> Self {
555        match element {
556            NamedNodePattern::NamedNode(node) => node.into(),
557            NamedNodePattern::Variable(var) => var.into(),
558        }
559    }
560}
561
562impl From<GroundTermPattern> for TermPattern {
563    #[inline]
564    fn from(element: GroundTermPattern) -> Self {
565        match element {
566            GroundTermPattern::NamedNode(node) => node.into(),
567            GroundTermPattern::Literal(literal) => literal.into(),
568            #[cfg(feature = "rdf-star")]
569            GroundTermPattern::Triple(t) => TriplePattern::from(*t).into(),
570            GroundTermPattern::Variable(variable) => variable.into(),
571        }
572    }
573}
574
575impl TryFrom<TermPattern> for Subject {
576    type Error = ();
577
578    #[inline]
579    fn try_from(term: TermPattern) -> Result<Self, Self::Error> {
580        match term {
581            TermPattern::NamedNode(t) => Ok(t.into()),
582            TermPattern::BlankNode(t) => Ok(t.into()),
583            #[cfg(feature = "rdf-star")]
584            TermPattern::Triple(t) => Ok(Triple::try_from(*t)?.into()),
585            TermPattern::Literal(_) | TermPattern::Variable(_) => Err(()),
586        }
587    }
588}
589
590impl TryFrom<TermPattern> for Term {
591    type Error = ();
592
593    #[inline]
594    fn try_from(pattern: TermPattern) -> Result<Self, Self::Error> {
595        match pattern {
596            TermPattern::NamedNode(t) => Ok(t.into()),
597            TermPattern::BlankNode(t) => Ok(t.into()),
598            TermPattern::Literal(t) => Ok(t.into()),
599            #[cfg(feature = "rdf-star")]
600            TermPattern::Triple(t) => Ok(Triple::try_from(*t)?.into()),
601            TermPattern::Variable(_) => Err(()),
602        }
603    }
604}
605/// The union of [terms](https://www.w3.org/TR/rdf11-concepts/#dfn-rdf-term) and [variables](https://www.w3.org/TR/sparql11-query/#sparqlQueryVariables) without blank nodes.
606#[derive(Eq, PartialEq, Debug, Clone, Hash)]
607pub enum GroundTermPattern {
608    NamedNode(NamedNode),
609    Literal(Literal),
610    Variable(Variable),
611    #[cfg(feature = "rdf-star")]
612    Triple(Box<GroundTriplePattern>),
613}
614
615impl GroundTermPattern {
616    /// Formats using the [SPARQL S-Expression syntax](https://jena.apache.org/documentation/notes/sse.html).
617    pub(crate) fn fmt_sse(&self, f: &mut impl Write) -> fmt::Result {
618        match self {
619            Self::NamedNode(term) => write!(f, "{term}"),
620            Self::Literal(term) => write!(f, "{term}"),
621            Self::Variable(var) => write!(f, "{var}"),
622            #[cfg(feature = "rdf-star")]
623            Self::Triple(triple) => triple.fmt_sse(f),
624        }
625    }
626}
627
628impl fmt::Display for GroundTermPattern {
629    #[inline]
630    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
631        match self {
632            Self::NamedNode(term) => term.fmt(f),
633            Self::Literal(term) => term.fmt(f),
634            Self::Variable(var) => var.fmt(f),
635            #[cfg(feature = "rdf-star")]
636            Self::Triple(triple) => write!(f, "<<{triple}>>"),
637        }
638    }
639}
640
641impl From<NamedNode> for GroundTermPattern {
642    #[inline]
643    fn from(node: NamedNode) -> Self {
644        Self::NamedNode(node)
645    }
646}
647
648impl From<Literal> for GroundTermPattern {
649    #[inline]
650    fn from(literal: Literal) -> Self {
651        Self::Literal(literal)
652    }
653}
654
655#[cfg(feature = "rdf-star")]
656impl From<GroundTriplePattern> for GroundTermPattern {
657    #[inline]
658    fn from(triple: GroundTriplePattern) -> Self {
659        Self::Triple(Box::new(triple))
660    }
661}
662
663impl From<Variable> for GroundTermPattern {
664    #[inline]
665    fn from(var: Variable) -> Self {
666        Self::Variable(var)
667    }
668}
669
670impl From<GroundSubject> for GroundTermPattern {
671    #[inline]
672    fn from(term: GroundSubject) -> Self {
673        match term {
674            GroundSubject::NamedNode(node) => node.into(),
675            #[cfg(feature = "rdf-star")]
676            GroundSubject::Triple(triple) => GroundTriplePattern::from(*triple).into(),
677        }
678    }
679}
680impl From<GroundTerm> for GroundTermPattern {
681    #[inline]
682    fn from(term: GroundTerm) -> Self {
683        match term {
684            GroundTerm::NamedNode(node) => node.into(),
685            GroundTerm::Literal(literal) => literal.into(),
686            #[cfg(feature = "rdf-star")]
687            GroundTerm::Triple(triple) => GroundTriplePattern::from(*triple).into(),
688        }
689    }
690}
691
692impl From<NamedNodePattern> for GroundTermPattern {
693    #[inline]
694    fn from(element: NamedNodePattern) -> Self {
695        match element {
696            NamedNodePattern::NamedNode(node) => node.into(),
697            NamedNodePattern::Variable(var) => var.into(),
698        }
699    }
700}
701
702impl TryFrom<TermPattern> for GroundTermPattern {
703    type Error = ();
704
705    #[inline]
706    fn try_from(pattern: TermPattern) -> Result<Self, Self::Error> {
707        Ok(match pattern {
708            TermPattern::NamedNode(named_node) => named_node.into(),
709            TermPattern::BlankNode(_) => return Err(()),
710            TermPattern::Literal(literal) => literal.into(),
711            #[cfg(feature = "rdf-star")]
712            TermPattern::Triple(triple) => GroundTriplePattern::try_from(*triple)?.into(),
713            TermPattern::Variable(variable) => variable.into(),
714        })
715    }
716}
717
718/// The union of [IRIs](https://www.w3.org/TR/rdf11-concepts/#dfn-iri), [default graph name](https://www.w3.org/TR/rdf11-concepts/#dfn-default-graph) and [variables](https://www.w3.org/TR/sparql11-query/#sparqlQueryVariables).
719#[derive(Eq, PartialEq, Debug, Clone, Hash)]
720pub enum GraphNamePattern {
721    NamedNode(NamedNode),
722    DefaultGraph,
723    Variable(Variable),
724}
725
726impl GraphNamePattern {
727    /// Formats using the [SPARQL S-Expression syntax](https://jena.apache.org/documentation/notes/sse.html).
728    pub(crate) fn fmt_sse(&self, f: &mut impl Write) -> fmt::Result {
729        match self {
730            Self::NamedNode(node) => write!(f, "{node}"),
731            Self::DefaultGraph => f.write_str("default"),
732            Self::Variable(var) => write!(f, "{var}"),
733        }
734    }
735}
736
737impl fmt::Display for GraphNamePattern {
738    #[inline]
739    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
740        match self {
741            Self::NamedNode(node) => node.fmt(f),
742            Self::DefaultGraph => f.write_str("DEFAULT"),
743            Self::Variable(var) => var.fmt(f),
744        }
745    }
746}
747
748impl From<NamedNode> for GraphNamePattern {
749    #[inline]
750    fn from(node: NamedNode) -> Self {
751        Self::NamedNode(node)
752    }
753}
754
755impl From<Variable> for GraphNamePattern {
756    #[inline]
757    fn from(var: Variable) -> Self {
758        Self::Variable(var)
759    }
760}
761
762impl From<GraphName> for GraphNamePattern {
763    #[inline]
764    fn from(graph_name: GraphName) -> Self {
765        match graph_name {
766            GraphName::NamedNode(node) => node.into(),
767            GraphName::DefaultGraph => Self::DefaultGraph,
768        }
769    }
770}
771
772impl From<NamedNodePattern> for GraphNamePattern {
773    #[inline]
774    fn from(graph_name: NamedNodePattern) -> Self {
775        match graph_name {
776            NamedNodePattern::NamedNode(node) => node.into(),
777            NamedNodePattern::Variable(var) => var.into(),
778        }
779    }
780}
781
782/// A [triple pattern](https://www.w3.org/TR/sparql11-query/#defn_TriplePattern)
783#[derive(Eq, PartialEq, Debug, Clone, Hash)]
784pub struct TriplePattern {
785    pub subject: TermPattern,
786    pub predicate: NamedNodePattern,
787    pub object: TermPattern,
788}
789
790impl TriplePattern {
791    pub(crate) fn new(
792        subject: impl Into<TermPattern>,
793        predicate: impl Into<NamedNodePattern>,
794        object: impl Into<TermPattern>,
795    ) -> Self {
796        Self {
797            subject: subject.into(),
798            predicate: predicate.into(),
799            object: object.into(),
800        }
801    }
802
803    /// Formats using the [SPARQL S-Expression syntax](https://jena.apache.org/documentation/notes/sse.html).
804    pub(crate) fn fmt_sse(&self, f: &mut impl Write) -> fmt::Result {
805        f.write_str("(triple ")?;
806        self.subject.fmt_sse(f)?;
807        f.write_str(" ")?;
808        self.predicate.fmt_sse(f)?;
809        f.write_str(" ")?;
810        self.object.fmt_sse(f)?;
811        f.write_str(")")
812    }
813}
814
815impl fmt::Display for TriplePattern {
816    #[inline]
817    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
818        write!(f, "{} {} {}", self.subject, self.predicate, self.object)
819    }
820}
821
822impl From<Triple> for TriplePattern {
823    #[inline]
824    fn from(triple: Triple) -> Self {
825        Self {
826            subject: triple.subject.into(),
827            predicate: triple.predicate.into(),
828            object: triple.object.into(),
829        }
830    }
831}
832
833impl From<GroundTriplePattern> for TriplePattern {
834    #[inline]
835    fn from(triple: GroundTriplePattern) -> Self {
836        Self {
837            subject: triple.subject.into(),
838            predicate: triple.predicate,
839            object: triple.object.into(),
840        }
841    }
842}
843
844impl TryFrom<TriplePattern> for Triple {
845    type Error = ();
846
847    #[inline]
848    fn try_from(triple: TriplePattern) -> Result<Self, Self::Error> {
849        Ok(Self {
850            subject: triple.subject.try_into()?,
851            predicate: triple.predicate.try_into()?,
852            object: triple.object.try_into()?,
853        })
854    }
855}
856
857/// A [triple pattern](https://www.w3.org/TR/sparql11-query/#defn_TriplePattern) without blank nodes.
858#[derive(Eq, PartialEq, Debug, Clone, Hash)]
859pub struct GroundTriplePattern {
860    pub subject: GroundTermPattern,
861    pub predicate: NamedNodePattern,
862    pub object: GroundTermPattern,
863}
864
865impl GroundTriplePattern {
866    /// Formats using the [SPARQL S-Expression syntax](https://jena.apache.org/documentation/notes/sse.html).
867    #[allow(dead_code)]
868    pub(crate) fn fmt_sse(&self, f: &mut impl Write) -> fmt::Result {
869        f.write_str("(triple ")?;
870        self.subject.fmt_sse(f)?;
871        f.write_str(" ")?;
872        self.predicate.fmt_sse(f)?;
873        f.write_str(" ")?;
874        self.object.fmt_sse(f)?;
875        f.write_str(")")
876    }
877}
878
879impl fmt::Display for GroundTriplePattern {
880    #[inline]
881    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
882        write!(f, "{} {} {}", self.subject, self.predicate, self.object)
883    }
884}
885
886impl From<GroundTriple> for GroundTriplePattern {
887    #[inline]
888    fn from(triple: GroundTriple) -> Self {
889        Self {
890            subject: triple.subject.into(),
891            predicate: triple.predicate.into(),
892            object: triple.object.into(),
893        }
894    }
895}
896
897impl TryFrom<TriplePattern> for GroundTriplePattern {
898    type Error = ();
899
900    #[inline]
901    fn try_from(triple: TriplePattern) -> Result<Self, Self::Error> {
902        Ok(Self {
903            subject: triple.subject.try_into()?,
904            predicate: triple.predicate,
905            object: triple.object.try_into()?,
906        })
907    }
908}
909
910/// A [triple pattern](https://www.w3.org/TR/sparql11-query/#defn_TriplePattern) in a specific graph
911#[derive(Eq, PartialEq, Debug, Clone, Hash)]
912pub struct QuadPattern {
913    pub subject: TermPattern,
914    pub predicate: NamedNodePattern,
915    pub object: TermPattern,
916    pub graph_name: GraphNamePattern,
917}
918
919impl QuadPattern {
920    pub(crate) fn new(
921        subject: impl Into<TermPattern>,
922        predicate: impl Into<NamedNodePattern>,
923        object: impl Into<TermPattern>,
924        graph_name: impl Into<GraphNamePattern>,
925    ) -> Self {
926        Self {
927            subject: subject.into(),
928            predicate: predicate.into(),
929            object: object.into(),
930            graph_name: graph_name.into(),
931        }
932    }
933
934    /// Formats using the [SPARQL S-Expression syntax](https://jena.apache.org/documentation/notes/sse.html).
935    pub(crate) fn fmt_sse(&self, f: &mut impl Write) -> fmt::Result {
936        if self.graph_name != GraphNamePattern::DefaultGraph {
937            f.write_str("(graph ")?;
938            self.graph_name.fmt_sse(f)?;
939            f.write_str(" (")?;
940        }
941        f.write_str("(triple ")?;
942        self.subject.fmt_sse(f)?;
943        f.write_str(" ")?;
944        self.predicate.fmt_sse(f)?;
945        f.write_str(" ")?;
946        self.object.fmt_sse(f)?;
947        f.write_str(")")?;
948        if self.graph_name != GraphNamePattern::DefaultGraph {
949            f.write_str("))")?;
950        }
951        Ok(())
952    }
953}
954
955impl fmt::Display for QuadPattern {
956    #[inline]
957    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
958        if self.graph_name == GraphNamePattern::DefaultGraph {
959            write!(f, "{} {} {}", self.subject, self.predicate, self.object)
960        } else {
961            write!(
962                f,
963                "GRAPH {} {{ {} {} {} }}",
964                self.graph_name, self.subject, self.predicate, self.object
965            )
966        }
967    }
968}
969
970/// A [triple pattern](https://www.w3.org/TR/sparql11-query/#defn_TriplePattern) in a specific graph without blank nodes.
971#[derive(Eq, PartialEq, Debug, Clone, Hash)]
972pub struct GroundQuadPattern {
973    pub subject: GroundTermPattern,
974    pub predicate: NamedNodePattern,
975    pub object: GroundTermPattern,
976    pub graph_name: GraphNamePattern,
977}
978
979impl GroundQuadPattern {
980    /// Formats using the [SPARQL S-Expression syntax](https://jena.apache.org/documentation/notes/sse.html).
981    pub(crate) fn fmt_sse(&self, f: &mut impl Write) -> fmt::Result {
982        if self.graph_name != GraphNamePattern::DefaultGraph {
983            f.write_str("(graph ")?;
984            self.graph_name.fmt_sse(f)?;
985            f.write_str(" (")?;
986        }
987        f.write_str("(triple ")?;
988        self.subject.fmt_sse(f)?;
989        f.write_str(" ")?;
990        self.predicate.fmt_sse(f)?;
991        f.write_str(" ")?;
992        self.object.fmt_sse(f)?;
993        f.write_str(")")?;
994        if self.graph_name != GraphNamePattern::DefaultGraph {
995            f.write_str("))")?;
996        }
997        Ok(())
998    }
999}
1000
1001impl fmt::Display for GroundQuadPattern {
1002    #[inline]
1003    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1004        if self.graph_name == GraphNamePattern::DefaultGraph {
1005            write!(f, "{} {} {}", self.subject, self.predicate, self.object)
1006        } else {
1007            write!(
1008                f,
1009                "GRAPH {} {{ {} {} {} }}",
1010                self.graph_name, self.subject, self.predicate, self.object
1011            )
1012        }
1013    }
1014}
1015
1016impl TryFrom<QuadPattern> for GroundQuadPattern {
1017    type Error = ();
1018
1019    #[inline]
1020    fn try_from(pattern: QuadPattern) -> Result<Self, Self::Error> {
1021        Ok(Self {
1022            subject: pattern.subject.try_into()?,
1023            predicate: pattern.predicate,
1024            object: pattern.object.try_into()?,
1025            graph_name: pattern.graph_name,
1026        })
1027    }
1028}