ng_oxigraph/oxigraph/sparql/model.rs
1use crate::oxigraph::io::{RdfFormat, RdfSerializer};
2use crate::oxigraph::model::*;
3use crate::oxigraph::sparql::error::EvaluationError;
4use crate::oxigraph::sparql::results::{
5 FromReadQueryResultsReader, FromReadSolutionsReader, QueryResultsFormat,
6 QueryResultsParseError, QueryResultsParser, QueryResultsSerializer,
7};
8pub use crate::sparesults::QuerySolution;
9use std::io::{Read, Write};
10use std::sync::Arc;
11
12/// Results of a [SPARQL query](https://www.w3.org/TR/sparql11-query/).
13pub enum QueryResults {
14 /// Results of a [SELECT](https://www.w3.org/TR/sparql11-query/#select) query.
15 Solutions(QuerySolutionIter),
16 /// Result of a [ASK](https://www.w3.org/TR/sparql11-query/#ask) query.
17 Boolean(bool),
18 /// Results of a [CONSTRUCT](https://www.w3.org/TR/sparql11-query/#construct) or [DESCRIBE](https://www.w3.org/TR/sparql11-query/#describe) query.
19 Graph(QueryTripleIter),
20}
21
22impl QueryResults {
23 /// Reads a SPARQL query results serialization.
24 pub fn read(
25 read: impl Read + 'static,
26 format: QueryResultsFormat,
27 ) -> Result<Self, QueryResultsParseError> {
28 Ok(QueryResultsParser::from_format(format)
29 .parse_read(read)?
30 .into())
31 }
32
33 /// Writes the query results (solutions or boolean).
34 ///
35 /// This method fails if it is called on the `Graph` results.
36 ///
37 /// ```
38 /// use oxigraph::store::Store;
39 /// use oxigraph::model::*;
40 /// use oxigraph::sparql::results::QueryResultsFormat;
41 ///
42 /// let store = Store::new()?;
43 /// let ex = NamedNodeRef::new("http://example.com")?;
44 /// store.insert(QuadRef::new(ex, ex, ex, GraphNameRef::DefaultGraph))?;
45 ///
46 /// let results = store.query("SELECT ?s WHERE { ?s ?p ?o }")?;
47 /// assert_eq!(
48 /// results.write(Vec::new(), QueryResultsFormat::Json)?,
49 /// r#"{"head":{"vars":["s"]},"results":{"bindings":[{"s":{"type":"uri","value":"http://example.com"}}]}}"#.as_bytes()
50 /// );
51 /// # Result::<_,Box<dyn std::error::Error>>::Ok(())
52 /// ```
53 pub fn write<W: Write>(
54 self,
55 write: W,
56 format: QueryResultsFormat,
57 ) -> Result<W, EvaluationError> {
58 let serializer = QueryResultsSerializer::from_format(format);
59 match self {
60 Self::Boolean(value) => serializer.serialize_boolean_to_write(write, value),
61 Self::Solutions(solutions) => {
62 let mut writer = serializer
63 .serialize_solutions_to_write(write, solutions.variables().to_vec())
64 .map_err(EvaluationError::ResultsSerialization)?;
65 for solution in solutions {
66 writer
67 .write(&solution?)
68 .map_err(EvaluationError::ResultsSerialization)?;
69 }
70 writer.finish()
71 }
72 Self::Graph(triples) => {
73 let s = VariableRef::new_unchecked("subject");
74 let p = VariableRef::new_unchecked("predicate");
75 let o = VariableRef::new_unchecked("object");
76 let mut writer = serializer
77 .serialize_solutions_to_write(
78 write,
79 vec![s.into_owned(), p.into_owned(), o.into_owned()],
80 )
81 .map_err(EvaluationError::ResultsSerialization)?;
82 for triple in triples {
83 let triple = triple?;
84 writer
85 .write([
86 (s, &triple.subject.into()),
87 (p, &triple.predicate.into()),
88 (o, &triple.object),
89 ])
90 .map_err(EvaluationError::ResultsSerialization)?;
91 }
92 writer.finish()
93 }
94 }
95 .map_err(EvaluationError::ResultsSerialization)
96 }
97
98 /// Writes the graph query results.
99 ///
100 /// This method fails if it is called on the `Solution` or `Boolean` results.
101 ///
102 /// ```
103 /// use oxigraph::io::RdfFormat;
104 /// use oxigraph::model::*;
105 /// use oxigraph::store::Store;
106 ///
107 /// let graph = "<http://example.com> <http://example.com> <http://example.com> .\n";
108 ///
109 /// let store = Store::new()?;
110 /// store.load_graph(
111 /// graph.as_bytes(),
112 /// RdfFormat::NTriples,
113 /// GraphName::DefaultGraph,
114 /// None,
115 /// )?;
116 ///
117 /// let results = store.query("CONSTRUCT WHERE { ?s ?p ?o }")?;
118 /// assert_eq!(
119 /// results.write_graph(Vec::new(), RdfFormat::NTriples)?,
120 /// graph.as_bytes()
121 /// );
122 /// # Result::<_,Box<dyn std::error::Error>>::Ok(())
123 /// ```
124 pub fn write_graph<W: Write>(
125 self,
126 write: W,
127 format: impl Into<RdfFormat>,
128 ) -> Result<W, EvaluationError> {
129 if let Self::Graph(triples) = self {
130 let mut writer = RdfSerializer::from_format(format.into()).serialize_to_write(write);
131 for triple in triples {
132 writer
133 .write_triple(&triple?)
134 .map_err(EvaluationError::ResultsSerialization)?;
135 }
136 writer
137 .finish()
138 .map_err(EvaluationError::ResultsSerialization)
139 } else {
140 Err(EvaluationError::NotAGraph)
141 }
142 }
143}
144
145impl From<QuerySolutionIter> for QueryResults {
146 #[inline]
147 fn from(value: QuerySolutionIter) -> Self {
148 Self::Solutions(value)
149 }
150}
151
152impl<R: Read + 'static> From<FromReadQueryResultsReader<R>> for QueryResults {
153 fn from(reader: FromReadQueryResultsReader<R>) -> Self {
154 match reader {
155 FromReadQueryResultsReader::Solutions(s) => Self::Solutions(s.into()),
156 FromReadQueryResultsReader::Boolean(v) => Self::Boolean(v),
157 }
158 }
159}
160
161/// An iterator over [`QuerySolution`]s.
162///
163/// ```
164/// use oxigraph::sparql::QueryResults;
165/// use oxigraph::store::Store;
166///
167/// let store = Store::new()?;
168/// if let QueryResults::Solutions(solutions) = store.query("SELECT ?s WHERE { ?s ?p ?o }")? {
169/// for solution in solutions {
170/// println!("{:?}", solution?.get("s"));
171/// }
172/// }
173/// # Result::<_,Box<dyn std::error::Error>>::Ok(())
174/// ```
175pub struct QuerySolutionIter {
176 variables: Arc<[Variable]>,
177 iter: Box<dyn Iterator<Item = Result<QuerySolution, EvaluationError>>>,
178}
179
180impl QuerySolutionIter {
181 /// Construct a new iterator of solution from an ordered list of solution variables and an iterator of solution tuples
182 /// (each tuple using the same ordering as the variable list such that tuple element 0 is the value for the variable 0...)
183 pub fn new(
184 variables: Arc<[Variable]>,
185 iter: impl Iterator<Item = Result<Vec<Option<Term>>, EvaluationError>> + 'static,
186 ) -> Self {
187 Self {
188 variables: Arc::clone(&variables),
189 iter: Box::new(
190 iter.map(move |t| t.map(|values| (Arc::clone(&variables), values).into())),
191 ),
192 }
193 }
194
195 /// The variables used in the solutions.
196 ///
197 /// ```
198 /// use oxigraph::sparql::{QueryResults, Variable};
199 /// use oxigraph::store::Store;
200 ///
201 /// let store = Store::new()?;
202 /// if let QueryResults::Solutions(solutions) = store.query("SELECT ?s ?o WHERE { ?s ?p ?o }")? {
203 /// assert_eq!(
204 /// solutions.variables(),
205 /// &[Variable::new("s")?, Variable::new("o")?]
206 /// );
207 /// }
208 /// # Result::<_,Box<dyn std::error::Error>>::Ok(())
209 /// ```
210 #[inline]
211 pub fn variables(&self) -> &[Variable] {
212 &self.variables
213 }
214}
215
216impl<R: Read + 'static> From<FromReadSolutionsReader<R>> for QuerySolutionIter {
217 fn from(reader: FromReadSolutionsReader<R>) -> Self {
218 Self {
219 variables: reader.variables().into(),
220 iter: Box::new(reader.map(|t| t.map_err(EvaluationError::from))),
221 }
222 }
223}
224
225impl Iterator for QuerySolutionIter {
226 type Item = Result<QuerySolution, EvaluationError>;
227
228 #[inline]
229 fn next(&mut self) -> Option<Self::Item> {
230 self.iter.next()
231 }
232
233 #[inline]
234 fn size_hint(&self) -> (usize, Option<usize>) {
235 self.iter.size_hint()
236 }
237}
238
239/// An iterator over the triples that compose a graph solution.
240///
241/// ```
242/// use oxigraph::sparql::QueryResults;
243/// use oxigraph::store::Store;
244///
245/// let store = Store::new()?;
246/// if let QueryResults::Graph(triples) = store.query("CONSTRUCT WHERE { ?s ?p ?o }")? {
247/// for triple in triples {
248/// println!("{}", triple?);
249/// }
250/// }
251/// # Result::<_,Box<dyn std::error::Error>>::Ok(())
252/// ```
253pub struct QueryTripleIter {
254 pub(crate) iter: Box<dyn Iterator<Item = Result<Triple, EvaluationError>>>,
255}
256
257impl Iterator for QueryTripleIter {
258 type Item = Result<Triple, EvaluationError>;
259
260 #[inline]
261 fn next(&mut self) -> Option<Self::Item> {
262 self.iter.next()
263 }
264
265 #[inline]
266 fn size_hint(&self) -> (usize, Option<usize>) {
267 self.iter.size_hint()
268 }
269
270 #[inline]
271 fn fold<Acc, G>(self, init: Acc, g: G) -> Acc
272 where
273 G: FnMut(Acc, Self::Item) -> Acc,
274 {
275 self.iter.fold(init, g)
276 }
277}
278
279#[cfg(feature = "rdf-star")]
280#[cfg(test)]
281#[allow(clippy::panic_in_result_fn)]
282mod tests {
283 use super::*;
284 use std::io::Cursor;
285
286 #[test]
287 fn test_serialization_roundtrip() -> Result<(), EvaluationError> {
288 use std::str;
289
290 for format in [
291 QueryResultsFormat::Json,
292 QueryResultsFormat::Xml,
293 QueryResultsFormat::Tsv,
294 ] {
295 let results = vec![
296 QueryResults::Boolean(true),
297 QueryResults::Boolean(false),
298 QueryResults::Solutions(QuerySolutionIter::new(
299 [
300 Variable::new_unchecked("foo"),
301 Variable::new_unchecked("bar"),
302 ]
303 .as_ref()
304 .into(),
305 Box::new(
306 vec![
307 Ok(vec![None, None]),
308 Ok(vec![
309 Some(NamedNode::new_unchecked("http://example.com").into()),
310 None,
311 ]),
312 Ok(vec![
313 None,
314 Some(NamedNode::new_unchecked("http://example.com").into()),
315 ]),
316 Ok(vec![
317 Some(BlankNode::new_unchecked("foo").into()),
318 Some(BlankNode::new_unchecked("bar").into()),
319 ]),
320 Ok(vec![Some(Literal::new_simple_literal("foo").into()), None]),
321 Ok(vec![
322 Some(
323 Literal::new_language_tagged_literal_unchecked("foo", "fr")
324 .into(),
325 ),
326 None,
327 ]),
328 Ok(vec![
329 Some(Literal::from(1).into()),
330 Some(Literal::from(true).into()),
331 ]),
332 Ok(vec![
333 Some(Literal::from(1.33).into()),
334 Some(Literal::from(false).into()),
335 ]),
336 Ok(vec![
337 Some(
338 Triple::new(
339 NamedNode::new_unchecked("http://example.com/s"),
340 NamedNode::new_unchecked("http://example.com/p"),
341 Triple::new(
342 NamedNode::new_unchecked("http://example.com/os"),
343 NamedNode::new_unchecked("http://example.com/op"),
344 NamedNode::new_unchecked("http://example.com/oo"),
345 ),
346 )
347 .into(),
348 ),
349 None,
350 ]),
351 ]
352 .into_iter(),
353 ),
354 )),
355 ];
356
357 for ex in results {
358 let mut buffer = Vec::new();
359 ex.write(&mut buffer, format)?;
360 let ex2 = QueryResults::read(Cursor::new(buffer.clone()), format)?;
361 let mut buffer2 = Vec::new();
362 ex2.write(&mut buffer2, format)?;
363 assert_eq!(
364 str::from_utf8(&buffer).unwrap(),
365 str::from_utf8(&buffer2).unwrap()
366 );
367 }
368 }
369
370 Ok(())
371 }
372}