SparqlEvaluator

Struct SparqlEvaluator 

pub struct SparqlEvaluator {
    parser: SparqlParser,
    inner: QueryEvaluator,
}
Available on crate feature rdf only.
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()?;

Fieldsยง

ยงparser: SparqlParserยงinner: QueryEvaluator

Implementationsยง

ยง

impl SparqlEvaluator

pub fn new() -> SparqlEvaluator

pub fn with_base_iri( self, base_iri: impl Into<String>, ) -> Result<SparqlEvaluator, 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())
    );
}

pub fn with_prefix( self, prefix_name: impl Into<String>, prefix_iri: impl Into<String>, ) -> Result<SparqlEvaluator, 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())
    );
}

pub fn with_service_handler( self, service_name: impl Into<NamedNode>, handler: impl ServiceHandler + 'static, ) -> SparqlEvaluator

Use a given ServiceHandler to execute SPARQL 1.1 Federated Query SERVICE calls.

See ServiceHandler for an example.

pub fn with_default_service_handler( self, handler: impl DefaultServiceHandler + 'static, ) -> SparqlEvaluator

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.

pub fn with_custom_function( self, name: NamedNode, evaluator: impl Fn(&[Term]) -> Option<Term> + Send + Sync + 'static, ) -> SparqlEvaluator

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

pub fn with_custom_aggregate_function( self, name: NamedNode, evaluator: impl Fn() -> Box<dyn AggregateFunctionAccumulator + Send + Sync> + Send + Sync + 'static, ) -> SparqlEvaluator

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

pub fn with_cancellation_token( self, cancellation_token: CancellationToken, ) -> SparqlEvaluator

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

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

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

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()?;

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ยง

ยง

impl Clone for SparqlEvaluator

ยง

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
ยง

impl Default for SparqlEvaluator

ยง

fn default() -> SparqlEvaluator

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
ยง

impl<T> Downcast for T
where T: Any,

ยง

fn into_any(self: Box<T>) -> Box<dyn Any>

Converts Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>, which can then be downcast into Box<dyn ConcreteType> where ConcreteType implements Trait.
ยง

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Converts Rc<Trait> (where Trait: Downcast) to Rc<Any>, which can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
ยง

fn as_any(&self) -> &(dyn Any + 'static)

Converts &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Anyโ€™s vtable from &Traitโ€™s.
ยง

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Converts &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Anyโ€™s vtable from &mut Traitโ€™s.
ยง

impl<T> DowncastSend for T
where T: Any + Send,

ยง

fn into_any_send(self: Box<T>) -> Box<dyn Any + Send>

Converts Box<Trait> (where Trait: DowncastSend) to Box<dyn Any + Send>, which can then be downcast into Box<ConcreteType> where ConcreteType implements Trait.
ยง

impl<T> DowncastSync for T
where T: Any + Send + Sync,

ยง

fn into_any_sync(self: Box<T>) -> Box<dyn Any + Send + Sync>

Converts Box<Trait> (where Trait: DowncastSync) to Box<dyn Any + Send + Sync>, which can then be downcast into Box<ConcreteType> where ConcreteType implements Trait.
ยง

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Send + Sync>

Converts Arc<Trait> (where Trait: DowncastSync) to Arc<Any>, which can then be downcast into Arc<ConcreteType> where ConcreteType implements Trait.
Sourceยง

impl<T> From<T> for T

Sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

ยง

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

ยง

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
ยง

impl<E, T, Request, Encoding> FromReq<Patch<Encoding>, Request, E> for T
where Request: Req<E> + Send + 'static, Encoding: Decodes<T>, E: FromServerFnError,

ยง

async fn from_req(req: Request) -> Result<T, E>

Attempts to deserialize the arguments from a request.
ยง

impl<E, T, Request, Encoding> FromReq<Post<Encoding>, Request, E> for T
where Request: Req<E> + Send + 'static, Encoding: Decodes<T>, E: FromServerFnError,

ยง

async fn from_req(req: Request) -> Result<T, E>

Attempts to deserialize the arguments from a request.
ยง

impl<E, T, Request, Encoding> FromReq<Put<Encoding>, Request, E> for T
where Request: Req<E> + Send + 'static, Encoding: Decodes<T>, E: FromServerFnError,

ยง

async fn from_req(req: Request) -> Result<T, E>

Attempts to deserialize the arguments from a request.
ยง

impl<E, Encoding, Response, T> FromRes<Patch<Encoding>, Response, E> for T
where Response: ClientRes<E> + Send, Encoding: Decodes<T>, E: FromServerFnError,

ยง

async fn from_res(res: Response) -> Result<T, E>

Attempts to deserialize the outputs from a response.
ยง

impl<E, Encoding, Response, T> FromRes<Post<Encoding>, Response, E> for T
where Response: ClientRes<E> + Send, Encoding: Decodes<T>, E: FromServerFnError,

ยง

async fn from_res(res: Response) -> Result<T, E>

Attempts to deserialize the outputs from a response.
ยง

impl<E, Encoding, Response, T> FromRes<Put<Encoding>, Response, E> for T
where Response: ClientRes<E> + Send, Encoding: Decodes<T>, E: FromServerFnError,

ยง

async fn from_res(res: Response) -> Result<T, E>

Attempts to deserialize the outputs from a response.
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self> โ“˜

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self> โ“˜

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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> IntoEither for T

Sourceยง

fn into_either(self, into_left: bool) -> Either<Self, Self> โ“˜

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Sourceยง

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> โ“˜
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
ยง

impl<E, T, Encoding, Request> IntoReq<Patch<Encoding>, Request, E> for T
where Request: ClientReq<E>, Encoding: Encodes<T>, E: FromServerFnError,

ยง

fn into_req(self, path: &str, accepts: &str) -> Result<Request, E>

Attempts to serialize the arguments into an HTTP request.
ยง

impl<E, T, Encoding, Request> IntoReq<Post<Encoding>, Request, E> for T
where Request: ClientReq<E>, Encoding: Encodes<T>, E: FromServerFnError,

ยง

fn into_req(self, path: &str, accepts: &str) -> Result<Request, E>

Attempts to serialize the arguments into an HTTP request.
ยง

impl<E, T, Encoding, Request> IntoReq<Put<Encoding>, Request, E> for T
where Request: ClientReq<E>, Encoding: Encodes<T>, E: FromServerFnError,

ยง

fn into_req(self, path: &str, accepts: &str) -> Result<Request, E>

Attempts to serialize the arguments into an HTTP request.
ยง

impl<E, Response, Encoding, T> IntoRes<Patch<Encoding>, Response, E> for T
where Response: TryRes<E>, Encoding: Encodes<T>, E: FromServerFnError + Send, T: Send,

ยง

async fn into_res(self) -> Result<Response, E>

Attempts to serialize the output into an HTTP response.
ยง

impl<E, Response, Encoding, T> IntoRes<Post<Encoding>, Response, E> for T
where Response: TryRes<E>, Encoding: Encodes<T>, E: FromServerFnError + Send, T: Send,

ยง

async fn into_res(self) -> Result<Response, E>

Attempts to serialize the output into an HTTP response.
ยง

impl<E, Response, Encoding, T> IntoRes<Put<Encoding>, Response, E> for T
where Response: TryRes<E>, Encoding: Encodes<T>, E: FromServerFnError + Send, T: Send,

ยง

async fn into_res(self) -> Result<Response, E>

Attempts to serialize the output into an HTTP response.
ยง

impl<T> Pointable for T

ยง

const ALIGN: usize

The alignment of pointer.
ยง

type Init = T

The type for initializers.
ยง

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
ยง

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
ยง

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
ยง

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
ยง

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

ยง

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns [Action::Follow] only if self and other return Action::Follow. Read more
ยง

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns [Action::Follow] if either self or other returns Action::Follow. Read more
Sourceยง

impl<T> Same for T

Sourceยง

type Output = T

Should always be Self
ยง

impl<T> SerializableKey for T

ยง

fn ser_key(&self) -> String

Serializes the key to a unique string. Read more
ยง

impl<T> StorageAccess<T> for T

ยง

fn as_borrowed(&self) -> &T

Borrows the value.
ยง

fn into_taken(self) -> T

Takes the value.
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.
ยง

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

ยง

fn vzip(self) -> V

ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> โ“˜
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self> โ“˜

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more
ยง

impl<T> Fruit for T
where T: Send + Downcast,