Skip to main content

SparqlEvaluator

Struct SparqlEvaluator 

Source
pub struct SparqlEvaluator { /* private fields */ }
Expand description

SPARQL evaluator.

It supports SPARQL 1.1 query and SPARQL 1.1 update.

If the "http-client" optional feature is enabled, a simple HTTP 1.1 client is used to execute SPARQL 1.1 Federated Query SERVICE calls.

Usage example disabling the federated query support:

use oxigraph::model::NamedNode;
use oxigraph::sparql::SparqlEvaluator;
use oxigraph::store::Store;

SparqlEvaluator::new()
    .with_custom_function(NamedNode::new("http://example.com/identity")?, |args| {
        args.get(0).cloned()
    })
    .parse_query("SELECT (<http://example.com/identity>('foo') AS ?r) WHERE {}")?
    .on_store(&Store::new()?)
    .execute()?;

Implementations§

Source§

impl SparqlEvaluator

Source

pub fn new() -> Self

Source

pub fn with_base_iri( self, base_iri: impl Into<String>, ) -> Result<Self, IriParseError>

Provides an IRI that could be used to resolve the operation relative IRIs.

use oxigraph::model::*;
use oxigraph::sparql::{QueryResults, SparqlEvaluator};
use oxigraph::store::Store;

if let QueryResults::Solutions(mut solutions) = SparqlEvaluator::new()
    .with_base_iri("http://example.com/")?
    .parse_query("SELECT (<> AS ?r) WHERE {}")?
    .on_store(&Store::new()?)
    .execute()?
{
    assert_eq!(
        solutions.next().unwrap()?.get("r"),
        Some(&NamedNode::new("http://example.com/")?.into())
    );
}
Source

pub fn with_prefix( self, prefix_name: impl Into<String>, prefix_iri: impl Into<String>, ) -> Result<Self, IriParseError>

Set a default IRI prefix used during parsing.

use oxigraph::model::*;
use oxigraph::sparql::{QueryResults, SparqlEvaluator};
use oxigraph::store::Store;

if let QueryResults::Solutions(mut solutions) = SparqlEvaluator::new()
    .with_prefix("ex", "http://example.com/")?
    .parse_query("SELECT (ex: AS ?r) WHERE {}")?
    .on_store(&Store::new()?)
    .execute()?
{
    assert_eq!(
        solutions.next().unwrap()?.get("r"),
        Some(&NamedNode::new("http://example.com/")?.into())
    );
}
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.

This replaces the default service handler that does HTTP requests to remote endpoints.

See DefaultServiceHandler for an example.

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 oxigraph::model::*;
use oxigraph::sparql::{QueryResults, SparqlEvaluator};
use oxigraph::store::Store;

if let QueryResults::Solutions(mut solutions) = SparqlEvaluator::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()),
    )
    .parse_query("SELECT (<http://www.w3.org/ns/formats/N-Triples>(1) AS ?nt) WHERE {}")?
    .on_store(&Store::new()?)
    .execute()?
{
    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.

Example with a function doing concatenation:

use oxigraph::model::{Literal, NamedNode, Term};
use oxigraph::sparql::{AggregateFunctionAccumulator, QueryResults, SparqlEvaluator};
use oxigraph::store::Store;
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())
    }
}

if let QueryResults::Solutions(mut solutions) = SparqlEvaluator::new()
    .with_custom_aggregate_function(NamedNode::new("http://example.com/concat")?, || {
        Box::new(ConcatAccumulator {
            value: String::new(),
        })
    })
    .parse_query(
        "SELECT (<http://example.com/concat>(?v) AS ?r) WHERE { VALUES ?v { 1 2 3 } }",
    )?
    .on_store(&Store::new()?)
    .execute()?
{
    assert_eq!(
        solutions.next().unwrap()?.get("r"),
        Some(&Literal::new_simple_literal("1 2 3").into())
    );
}
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 oxigraph::model::*;
use oxigraph::sparql::{
    CancellationToken, QueryEvaluationError, QueryResults, SparqlEvaluator,
};
use oxigraph::store::Store;

let store = Store::new()?;
store.insert(QuadRef::new(
    NamedNodeRef::new("http://example.com/s")?,
    NamedNodeRef::new("http://example.com/p")?,
    NamedNodeRef::new("http://example.com/o")?,
    GraphNameRef::DefaultGraph,
))?;
let cancellation_token = CancellationToken::new();
if let QueryResults::Solutions(mut solutions) = SparqlEvaluator::new()
    .with_cancellation_token(cancellation_token.clone())
    .parse_query("SELECT * WHERE { ?s ?p ?o }")?
    .on_store(&store)
    .execute()?
{
    cancellation_token.cancel(); // We cancel
    assert!(matches!(
        solutions.next().unwrap().unwrap_err(),
        QueryEvaluationError::Cancelled
    ));
}
Source

pub fn parse_query( self, query: &(impl AsRef<str> + ?Sized), ) -> Result<PreparedSparqlQuery, SparqlSyntaxError>

Parse a query and returns a PreparedSparqlQuery for the current evaluator.

Usage example:

use oxigraph::model::*;
use oxigraph::sparql::{QueryResults, SparqlEvaluator};
use oxigraph::store::Store;

let store = Store::new()?;
let ex = NamedNodeRef::new("http://example.com")?;
store.insert(QuadRef::new(ex, ex, ex, GraphNameRef::DefaultGraph))?;

let prepared_query = SparqlEvaluator::new().parse_query("SELECT ?s WHERE { ?s ?p ?o }")?;

if let QueryResults::Solutions(mut solutions) = prepared_query.on_store(&store).execute()? {
    assert_eq!(
        solutions.next().unwrap()?.get("s"),
        Some(&ex.into_owned().into())
    );
}
Source

pub fn for_query(self, query: impl Into<Query>) -> PreparedSparqlQuery

Returns a PreparedSparqlQuery for the current evaluator and SPARQL query.

Usage example:

use oxigraph::model::*;
use oxigraph::sparql::{QueryResults, SparqlEvaluator};
use oxigraph::store::Store;
use spargebra::SparqlParser;

let store = Store::new()?;
let ex = NamedNodeRef::new("http://example.com")?;
store.insert(QuadRef::new(ex, ex, ex, GraphNameRef::DefaultGraph))?;

let query = SparqlParser::new().parse_query("SELECT ?s WHERE { ?s ?p ?o }")?;

let prepared_query = SparqlEvaluator::new().for_query(query);

if let QueryResults::Solutions(mut solutions) = prepared_query.on_store(&store).execute()? {
    assert_eq!(
        solutions.next().unwrap()?.get("s"),
        Some(&ex.into_owned().into())
    );
}
Source

pub fn parse_update( self, query: &(impl AsRef<str> + ?Sized), ) -> Result<PreparedSparqlUpdate, SparqlSyntaxError>

Parse an update and returns a PreparedSparqlUpdate for the current evaluator.

Usage example:

use oxigraph::sparql::SparqlEvaluator;
use oxigraph::store::Store;

SparqlEvaluator::new()
    .parse_update(
        "INSERT DATA { <http://example.com> <http://example.com> <http://example.com> }",
    )?
    .on_store(&Store::new()?)
    .execute()?;
Source

pub fn for_update(self, update: impl Into<Update>) -> PreparedSparqlUpdate

Returns a PreparedSparqlUpdate for the current evaluator and SPARQL update.

Usage example:

use oxigraph::sparql::SparqlEvaluator;
use oxigraph::store::Store;
use spargebra::SparqlParser;

let update = SparqlParser::new().parse_update(
    "INSERT DATA { <http://example.com> <http://example.com> <http://example.com> }",
)?;
SparqlEvaluator::new()
    .for_update(update)
    .on_store(&Store::new()?)
    .execute()?;

Trait Implementations§

Source§

impl Clone for SparqlEvaluator

Source§

fn clone(&self) -> SparqlEvaluator

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 SparqlEvaluator

Source§

fn default() -> Self

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