pub struct QueryEvaluator { /* private fields */ }Expand description
Evaluates a query against a given RDF dataset
To adapt this software to work on your own RDF dataset, you need to implement the QueryableDataset trait.
use oxrdf::{Dataset, GraphName, NamedNode, Quad};
use spareval::{QueryEvaluator, QueryResults};
use spargebra::SparqlParser;
let ex = NamedNode::new("http://example.com")?;
let dataset = Dataset::from_iter([Quad::new(
ex.clone(),
ex.clone(),
ex.clone(),
GraphName::DefaultGraph,
)]);
let query = SparqlParser::new().parse_query("SELECT * WHERE { ?s ?p ?o }")?;
let evaluator = QueryEvaluator::new();
let results = evaluator.prepare(&query).execute(&dataset)?;
if let QueryResults::Solutions(solutions) = results {
let solutions = solutions.collect::<Result<Vec<_>, _>>()?;
assert_eq!(solutions.len(), 1);
assert_eq!(solutions[0]["s"], ex.into());
}Implementations§
Source§impl QueryEvaluator
impl QueryEvaluator
pub fn new() -> Self
Sourcepub fn prepare<'a>(&'a self, query: &'a Query) -> PreparedQuery<'a>
pub fn prepare<'a>(&'a self, query: &'a Query) -> PreparedQuery<'a>
Prepare the SPARQL query to be executed.
Sourcepub fn execute<'a>(
&self,
dataset: impl QueryableDataset<'a>,
query: &Query,
) -> Result<QueryResults<'a>, QueryEvaluationError>
👎Deprecated since 0.2.1: Use prepare instead
pub fn execute<'a>( &self, dataset: impl QueryableDataset<'a>, query: &Query, ) -> Result<QueryResults<'a>, QueryEvaluationError>
Execute the SPARQL query against the given dataset.
Note that this evaluator does not handle the FROM and FROM NAMED part of the query.
You must select the proper dataset before using this struct.
Sourcepub fn execute_with_substituted_variables<'a>(
&self,
dataset: impl QueryableDataset<'a>,
query: &Query,
substitutions: impl IntoIterator<Item = (Variable, Term)>,
) -> Result<QueryResults<'a>, QueryEvaluationError>
👎Deprecated since 0.2.1: Use prepare instead
pub fn execute_with_substituted_variables<'a>( &self, dataset: impl QueryableDataset<'a>, query: &Query, substitutions: impl IntoIterator<Item = (Variable, Term)>, ) -> Result<QueryResults<'a>, QueryEvaluationError>
Executes a SPARQL query while substituting some variables with the given values.
Substitution follows RDF-dev SEP-0007.
use oxrdf::{Dataset, GraphName, NamedNode, Quad, Variable};
use spareval::{QueryEvaluator, QueryResults};
use spargebra::SparqlParser;
let ex = NamedNode::new("http://example.com")?;
let dataset = Dataset::from_iter([Quad::new(
ex.clone(),
ex.clone(),
ex.clone(),
GraphName::DefaultGraph,
)]);
let query = SparqlParser::new().parse_query("SELECT * WHERE { ?s ?p ?o }")?;
let results = QueryEvaluator::new().execute_with_substituted_variables(
&dataset,
&query,
[(Variable::new("s")?, ex.clone().into())],
);
if let QueryResults::Solutions(solutions) = results? {
let solutions = solutions.collect::<Result<Vec<_>, _>>()?;
assert_eq!(solutions.len(), 1);
assert_eq!(solutions[0]["s"], ex.into());
}pub fn explain<'a>( &self, dataset: impl QueryableDataset<'a>, query: &Query, ) -> (Result<QueryResults<'a>, QueryEvaluationError>, QueryExplanation)
pub fn explain_with_substituted_variables<'a>( &self, dataset: impl QueryableDataset<'a>, query: &Query, substitutions: impl IntoIterator<Item = (Variable, Term)>, ) -> (Result<QueryResults<'a>, QueryEvaluationError>, QueryExplanation)
Sourcepub fn with_service_handler(
self,
service_name: impl Into<NamedNode>,
handler: impl ServiceHandler + 'static,
) -> Self
pub fn with_service_handler( self, service_name: impl Into<NamedNode>, handler: impl ServiceHandler + 'static, ) -> Self
Use a given ServiceHandler to execute SPARQL 1.1 Federated Query SERVICE calls.
See ServiceHandler for an example.
Sourcepub fn with_default_service_handler(
self,
handler: impl DefaultServiceHandler + 'static,
) -> Self
pub fn with_default_service_handler( self, handler: impl DefaultServiceHandler + 'static, ) -> Self
Use a given DefaultServiceHandler to execute SPARQL 1.1 Federated Query SERVICE calls if no explicit service handler is defined for the service.
See DefaultServiceHandler for an example.
pub fn has_default_service_handler(&self) -> bool
Sourcepub fn with_custom_function(
self,
name: NamedNode,
evaluator: impl Fn(&[Term]) -> Option<Term> + Send + Sync + 'static,
) -> Self
pub fn with_custom_function( self, name: NamedNode, evaluator: impl Fn(&[Term]) -> Option<Term> + Send + Sync + 'static, ) -> Self
Adds a custom SPARQL evaluation function.
Example with a function serializing terms to N-Triples:
use oxrdf::{Dataset, Literal, NamedNode};
use spareval::{QueryEvaluator, QueryResults};
use spargebra::SparqlParser;
let evaluator = QueryEvaluator::new().with_custom_function(
NamedNode::new("http://www.w3.org/ns/formats/N-Triples")?,
|args| args.get(0).map(|t| Literal::from(t.to_string()).into()),
);
let query = SparqlParser::new()
.parse_query("SELECT (<http://www.w3.org/ns/formats/N-Triples>(1) AS ?nt) WHERE {}")?;
if let QueryResults::Solutions(mut solutions) =
evaluator.prepare(&query).execute(&Dataset::new())?
{
assert_eq!(
solutions.next().unwrap()?.get("nt"),
Some(&Literal::from("\"1\"^^<http://www.w3.org/2001/XMLSchema#integer>").into())
);
}Sourcepub fn with_custom_aggregate_function(
self,
name: NamedNode,
evaluator: impl Fn() -> Box<dyn AggregateFunctionAccumulator + Send + Sync> + Send + Sync + 'static,
) -> Self
pub fn with_custom_aggregate_function( self, name: NamedNode, evaluator: impl Fn() -> Box<dyn AggregateFunctionAccumulator + Send + Sync> + Send + Sync + 'static, ) -> Self
Adds a custom SPARQL evaluation aggregate function.
Note that it must also be given to the SPARQL parser using SparqlParser::with_custom_aggregate_function.
Example with a function doing concatenation:
use oxrdf::{Dataset, Literal, NamedNode, Term};
use spareval::{AggregateFunctionAccumulator, QueryEvaluator, QueryResults};
use spargebra::SparqlParser;
use std::mem::take;
struct ConcatAccumulator {
value: String,
}
impl AggregateFunctionAccumulator for ConcatAccumulator {
fn accumulate(&mut self, element: Term) {
if let Term::Literal(v) = element {
if !self.value.is_empty() {
self.value.push(' ');
}
self.value.push_str(v.value());
}
}
fn finish(&mut self) -> Option<Term> {
Some(Literal::new_simple_literal(take(&mut self.value)).into())
}
}
let evaluator = QueryEvaluator::new().with_custom_aggregate_function(
NamedNode::new("http://example.com/concat")?,
|| {
Box::new(ConcatAccumulator {
value: String::new(),
})
},
);
let query = SparqlParser::new()
.with_custom_aggregate_function(NamedNode::new("http://example.com/concat")?)
.parse_query(
"SELECT (<http://example.com/concat>(?v) AS ?r) WHERE { VALUES ?v { 1 2 3 } }",
)?;
if let QueryResults::Solutions(mut solutions) =
evaluator.prepare(&query).execute(&Dataset::new())?
{
assert_eq!(
solutions.next().unwrap()?.get("r"),
Some(&Literal::new_simple_literal("1 2 3").into())
);
}Sourcepub fn without_optimizations(self) -> Self
pub fn without_optimizations(self) -> Self
Disables query optimizations and runs the query as it is.
Sourcepub fn compute_statistics(self) -> Self
pub fn compute_statistics(self) -> Self
Compute statistics during evaluation and fills them in the explanation tree.
Sourcepub fn with_cancellation_token(
self,
cancellation_token: CancellationToken,
) -> Self
pub fn with_cancellation_token( self, cancellation_token: CancellationToken, ) -> Self
Inject a cancellation token to the SPARQL evaluation.
Might be used to abort a query cleanly.
use oxrdf::{Dataset, GraphName, NamedNode, Quad};
use spareval::{CancellationToken, QueryEvaluationError, QueryEvaluator, QueryResults};
use spargebra::SparqlParser;
let ex = NamedNode::new("http://example.com")?;
let dataset = Dataset::from_iter([Quad::new(
ex.clone(),
ex.clone(),
ex.clone(),
GraphName::DefaultGraph,
)]);
let query = SparqlParser::new().parse_query("SELECT * WHERE { ?s ?p ?o }")?;
let cancellation_token = CancellationToken::new();
let evaluator = QueryEvaluator::new().with_cancellation_token(cancellation_token.clone());
let results = evaluator.prepare(&query).execute(&dataset)?;
if let QueryResults::Solutions(mut solutions) = results {
cancellation_token.cancel(); // We cancel
assert!(matches!(
solutions.next().unwrap().unwrap_err(), // It's cancelled
QueryEvaluationError::Cancelled
));
}Sourcepub fn evaluate_expression<'a>(
&self,
expression: &Expression,
substitutions: impl IntoIterator<Item = (&'a Variable, Term)>,
) -> Option<Term>
pub fn evaluate_expression<'a>( &self, expression: &Expression, substitutions: impl IntoIterator<Item = (&'a Variable, Term)>, ) -> Option<Term>
Evaluates a SPARQL expression against an empty dataset with optional variable substitutions.
Returns the computed term or None if an error occurs or the expression is invalid.
Sourcepub fn evaluate_effective_boolean_value_expression<'a>(
&self,
expression: &Expression,
substitutions: impl IntoIterator<Item = (&'a Variable, Term)>,
) -> Option<bool>
pub fn evaluate_effective_boolean_value_expression<'a>( &self, expression: &Expression, substitutions: impl IntoIterator<Item = (&'a Variable, Term)>, ) -> Option<bool>
Evaluates a SPARQL expression effective boolean value (EBV) against an empty dataset with optional variable substitutions.
Returns the EBV or None if an error occurs or EBV is undefined for the result type.
Sourcepub fn prepare_delete_insert<'a>(
&'a self,
delete: Vec<GroundQuadPattern>,
insert: Vec<QuadPattern>,
base_iri: Option<Iri<String>>,
using: Option<QueryDataset>,
pattern: &'a GraphPattern,
) -> PreparedDeleteInsertUpdate<'a>
pub fn prepare_delete_insert<'a>( &'a self, delete: Vec<GroundQuadPattern>, insert: Vec<QuadPattern>, base_iri: Option<Iri<String>>, using: Option<QueryDataset>, pattern: &'a GraphPattern, ) -> PreparedDeleteInsertUpdate<'a>
Evaluates a SPARQL UPDATE DELETE/INSERT operation.
Returns the list of quads to delete or insert.
use oxrdf::{Dataset, GraphName, Literal, NamedNode, Quad};
use spareval::{DeleteInsertQuad, QueryEvaluator};
use spargebra::{GraphUpdateOperation, SparqlParser};
let ex = NamedNode::new("http://example.com")?;
let dataset = Dataset::from_iter([Quad::new(
ex.clone(),
ex.clone(),
Literal::from(0),
GraphName::DefaultGraph,
)]);
let update = SparqlParser::new().parse_update(
"DELETE { ?s ?p ?o } INSERT { ?s ?p ?o2 } WHERE { ?s ?p ?o BIND(?o +1 AS ?o2) }",
)?;
let GraphUpdateOperation::DeleteInsert {
delete,
insert,
using: _,
pattern,
} = &update.operations[0]
else {
unreachable!()
};
let results = QueryEvaluator::new()
.prepare_delete_insert(delete.clone(), insert.clone(), None, None, pattern)
.execute(&dataset)?
.collect::<Result<Vec<_>, _>>()?;
assert_eq!(
results,
vec![
DeleteInsertQuad::Delete(Quad::new(
ex.clone(),
ex.clone(),
Literal::from(0),
GraphName::DefaultGraph,
)),
DeleteInsertQuad::Insert(Quad::new(
ex.clone(),
ex.clone(),
Literal::from(1),
GraphName::DefaultGraph,
))
]
);Trait Implementations§
Source§impl Clone for QueryEvaluator
impl Clone for QueryEvaluator
Source§fn clone(&self) -> QueryEvaluator
fn clone(&self) -> QueryEvaluator
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read more