QueryEvaluator

Struct QueryEvaluator 

Source
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

Source

pub fn new() -> Self

Source

pub fn prepare<'a>(&'a self, query: &'a Query) -> PreparedQuery<'a>

Prepare the SPARQL query to be executed.

Source

pub fn execute<'a>( &self, dataset: impl QueryableDataset<'a>, query: &Query, ) -> Result<QueryResults<'a>, QueryEvaluationError>

👎Deprecated since 0.2.1: Use prepare instead

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.

Source

pub 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

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());
}
Source

pub fn explain<'a>( &self, dataset: impl QueryableDataset<'a>, query: &Query, ) -> (Result<QueryResults<'a>, QueryEvaluationError>, QueryExplanation)

👎Deprecated since 0.2.1: Use prepare instead
Source

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)

👎Deprecated since 0.2.1: Use prepare instead
Source

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.

Source

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.

Source

pub fn has_default_service_handler(&self) -> bool

Source

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())
    );
}
Source

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())
    );
}
Source

pub fn without_optimizations(self) -> Self

Disables query optimizations and runs the query as it is.

Source

pub fn compute_statistics(self) -> Self

Compute statistics during evaluation and fills them in the explanation tree.

Source

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
    ));
}
Source

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.

Source

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.

Source

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

Source§

fn clone(&self) -> QueryEvaluator

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Default for QueryEvaluator

Source§

fn default() -> QueryEvaluator

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V