oxilite_validate/
graph.rs1use oxilite::sparql::QueryOptions;
4use oxilite::store::Store;
5use oxilite_core::{QueryOutput, SyncBackend};
6use oxrdf::{
7 BlankNode, GraphNameRef, Literal, NamedNode, NamedNodeRef, NamedOrBlankNode,
8 NamedOrBlankNodeRef, Term, TermRef, Triple,
9};
10use prefixmap::{PrefixMap, PrefixMapError};
11use rudof_iri::IriS;
12use rudof_rdf::rdf_core::query::{
13 QueryRDF, QueryResultFormat, QuerySolution, QuerySolutions, VarName,
14};
15use rudof_rdf::rdf_core::{Matcher, NeighsRDF, Rdf};
16use std::collections::HashSet;
17use std::fmt::{self, Debug, Display};
18use std::str::FromStr;
19
20pub struct StoreGraph<B: SyncBackend + Send + Sync + 'static> {
22 store: Store<B>,
23 union: bool,
24 pm: PrefixMap,
25}
26
27impl<B: SyncBackend + Send + Sync + 'static> StoreGraph<B> {
28 pub fn new(store: Store<B>) -> Self {
30 Self {
31 store,
32 union: false,
33 pm: PrefixMap::new(),
34 }
35 }
36
37 pub fn with_union(mut self, union: bool) -> Self {
39 self.union = union;
40 self
41 }
42
43 pub fn with_prefixmap(mut self, pm: PrefixMap) -> Self {
45 self.pm = pm;
46 self
47 }
48
49 fn options(&self) -> QueryOptions {
50 QueryOptions {
51 union_default_graph: self.union,
52 ..QueryOptions::default()
53 }
54 }
55}
56
57impl<B: SyncBackend + Send + Sync + 'static> Debug for StoreGraph<B> {
58 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59 f.debug_struct("StoreGraph")
60 .field("union", &self.union)
61 .finish()
62 }
63}
64
65#[derive(Debug)]
67pub struct GraphError(pub String);
68
69impl Display for GraphError {
70 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
71 f.write_str(&self.0)
72 }
73}
74
75impl std::error::Error for GraphError {}
76
77impl From<oxilite_core::Error> for GraphError {
78 fn from(e: oxilite_core::Error) -> Self {
79 Self(e.to_string())
80 }
81}
82
83impl<B: SyncBackend + Send + Sync + 'static> Rdf for StoreGraph<B> {
84 type IRI = NamedNode;
85 type BNode = BlankNode;
86 type Literal = Literal;
87 type Subject = NamedOrBlankNode;
88 type Term = Term;
89 type Triple = Triple;
90 type Err = GraphError;
91
92 fn resolve_prefix_local(&self, prefix: &str, local: &str) -> Result<IriS, PrefixMapError> {
93 self.pm.resolve_prefix_local(prefix, local)
94 }
95
96 fn qualify_iri(&self, node: &NamedNode) -> String {
97 match IriS::from_str(node.as_str()) {
98 Ok(iri) => self.pm.qualify(&iri),
99 Err(_) => node.to_string(),
100 }
101 }
102
103 fn qualify_subject(&self, subj: &NamedOrBlankNode) -> String {
104 match subj {
105 NamedOrBlankNode::NamedNode(n) => self.qualify_iri(n),
106 NamedOrBlankNode::BlankNode(b) => b.to_string(),
107 }
108 }
109
110 fn qualify_term(&self, term: &Term) -> String {
111 match term {
112 Term::NamedNode(n) => self.qualify_iri(n),
113 t => t.to_string(),
114 }
115 }
116
117 fn prefixmap(&self) -> Option<PrefixMap> {
118 Some(self.pm.clone())
119 }
120}
121
122impl<B: SyncBackend + Send + Sync + 'static> NeighsRDF for StoreGraph<B> {
123 fn triples(&self) -> Result<impl Iterator<Item = Triple>, GraphError> {
124 self.scan(None, None, None)
125 }
126
127 fn triples_matching<S, P, O>(
128 &self,
129 subject: &S,
130 predicate: &P,
131 object: &O,
132 ) -> Result<impl Iterator<Item = Triple> + '_, GraphError>
133 where
134 S: Matcher<NamedOrBlankNode>,
135 P: Matcher<NamedNode>,
136 O: Matcher<Term>,
137 {
138 self.scan(
139 subject.value().map(NamedOrBlankNode::as_ref),
140 predicate.value().map(NamedNode::as_ref),
141 object.value().map(Term::as_ref),
142 )
143 }
144}
145
146impl<B: SyncBackend + Send + Sync + 'static> StoreGraph<B> {
147 fn scan(
148 &self,
149 s: Option<NamedOrBlankNodeRef<'_>>,
150 p: Option<NamedNodeRef<'_>>,
151 o: Option<TermRef<'_>>,
152 ) -> Result<std::vec::IntoIter<Triple>, GraphError> {
153 let graph = (!self.union).then_some(GraphNameRef::DefaultGraph);
154 let mut triples = Vec::new();
155 let mut seen = HashSet::new();
156 for q in self.store.quads_for_pattern(s, p, o, graph) {
157 let t = Triple::from(q?);
158 if !self.union || seen.insert(t.clone()) {
159 triples.push(t);
160 }
161 }
162 Ok(triples.into_iter())
163 }
164
165 fn output(&self, query: &str) -> Result<QueryOutput, GraphError> {
166 Ok(self.store.query_output(query, &self.options())?)
167 }
168}
169
170impl<B: SyncBackend + Send + Sync + 'static> QueryRDF for StoreGraph<B> {
171 fn query_select(&self, query: &str) -> Result<QuerySolutions<Self>, GraphError> {
172 let QueryOutput::Solutions { variables, rows } = self.output(query)? else {
173 return Ok(QuerySolutions::empty());
174 };
175 let names: Vec<VarName> = variables.iter().map(|v| VarName::new(v.as_str())).collect();
176 let solutions = rows
177 .into_iter()
178 .map(|row| QuerySolution::new(names.clone(), row))
179 .collect();
180 Ok(QuerySolutions::new(solutions, self.pm.clone()))
181 }
182
183 fn query_construct(
184 &self,
185 query: &str,
186 _format: &QueryResultFormat,
187 ) -> Result<String, GraphError> {
188 let QueryOutput::Graph(triples) = self.output(query)? else {
189 return Ok(String::new());
190 };
191 let mut s =
192 oxrdfio::RdfSerializer::from_format(oxrdfio::RdfFormat::Turtle).for_writer(Vec::new());
193 for t in &triples {
194 s.serialize_triple(t)
195 .map_err(|e| GraphError(e.to_string()))?;
196 }
197 let bytes = s.finish().map_err(|e| GraphError(e.to_string()))?;
198 Ok(String::from_utf8_lossy(&bytes).into_owned())
199 }
200
201 fn query_ask(&self, query: &str) -> Result<bool, GraphError> {
202 Ok(matches!(self.output(query)?, QueryOutput::Boolean(true)))
203 }
204}