Skip to main content

Crate sparql_results

Crate sparql_results 

Source
Expand description

§sparql-results

Crates.io Documentation CI License Downloads

Async-first, bounded-memory parsers and incremental serializers for the W3C SPARQL Query Results interchange formats:

The crate is deliberately independent of any RDF store, query engine, wire protocol, or application data model. It represents one binding row at a time with ResultRow and ResultValue; callers translate their own RDF terms at the boundary.

Streaming parsers consume tokio::io::AsyncRead sources and await the async row sink before reading the next row. Incremental writers and SRX canonicalization await every write to a tokio::io::AsyncWrite. Memory is independent of the number of solution rows: parser state, the current token/event and row, and downstream buffers remain live. A single token, value, or row must still fit in memory.

§Streaming serialization

Create a writer once, write each row as it becomes available, and finish the document explicitly. No result-set-sized buffer is required.

use sparql_results::{ResultHead, ResultRow, ResultValue, SrjWriter};
use std::collections::HashMap;

#[tokio::main]
async fn main() -> sparql_results::Result<()> {
    let head = ResultHead::select(vec!["name".to_owned()])?;
    let mut writer = SrjWriter::start_select(tokio::io::sink(), &head).await?;

    let mut bindings = HashMap::new();
    bindings.insert(
        "name".to_owned(),
        ResultValue::Literal {
            value: "Ada".to_owned(),
            lang: None,
            datatype: None,
            dir: None,
        },
    );
    writer.write_row(&ResultRow { bindings: bindings.into_iter().collect() }).await?;
    let _sink = writer.finish().await?;
    Ok(())
}

SrxWriter provides the equivalent incremental XML serializer. Both writers await every downstream write, preserving backpressure.

A ResultHead holds the projected variables and any link IRIs. It is valid by construction: every variable is a SPARQL VARNAME, declared once (HeaderError). Writers check before they write, so a refusal emits zero bytes: write_row refuses a row that binds an undeclared variable, holds an invalid literal, or has a triple term whose subject is not an IRI or blank node or whose predicate is not an IRI (RowError); write_srj / write_srx check the whole bounded result first, including that an ASK header declares no variables. Output is deterministic: SRJ bindings are written in variable name order, SRX bindings in row order.

§Streaming parsing

Parsers emit the header (variables and link IRIs), each row, or the ASK result to an async sink before reading more input. A sink can forward rows to a database, another encoder, or an application stream without collecting the document.

use sparql_results::{ResultHead, ResultRow, ResultValue, SrjStreamSink, parse_srj_streaming};

struct RowSink;

#[async_trait::async_trait]
impl SrjStreamSink for RowSink {
    async fn select_header(&mut self, _head: ResultHead) -> sparql_results::Result<()> {
        Ok(())
    }

    async fn select_row(&mut self, row: ResultRow) -> sparql_results::Result<()> {
        let _ = row.bindings.get("name").map(|value| match value {
            ResultValue::Literal { value, .. } => value,
            _ => "",
        });
        Ok(())
    }

    async fn ask(&mut self, _head: ResultHead, _result: bool) -> sparql_results::Result<()> {
        Ok(())
    }
}

Use parse_srj_streaming or parse_srx_streaming with a sink such as RowSink. The sink is awaited before the parser advances, so a slow consumer creates backpressure instead of an unbounded in-memory queue.

Complete-document parsing and writing is isolated in the explicit bounded module. Those adapters materialize every solution row in SparqlResult and must only be used when the caller enforces a finite input/result limit. They are not used by the streaming APIs.

§Literal validation

Both readers check every literal’s annotations and stop with SparqlResultsError::InvalidLiteral(LiteralError) when they are invalid:

InputLiteralError
A bare "dir" key in SRJ, or an unprefixed dir attribute in SRX. The base direction is written only as its:dir.BareDirKey
its:dir without a language tagDirectionWithoutLanguage
A language tag whose datatype is not rdf:langString (or rdf:dirLangString when its:dir is present)DatatypeContradictsLanguage
A datatype of rdf:langString / rdf:dirLangString with no language tagDatatypeRequiresLanguage
A language tag that is not well-formed BCP 47 (RFC 5646, syntax only; the IANA registry is not consulted)InvalidLanguageTag

The checks run on each value as it is read, so streaming and bounded memory are unchanged.

§License

Licensed under either of:

This crate owns two formats:

  • SPARQL Query Results XML Format (quick-xml).
  • SPARQL Query Results JSON Format (serde_json).

The public API is async-first: readers consume Tokio async readers, sinks are awaited before the next row is read, and serializers write directly to Tokio async writers. Complete-document materialization is isolated in the explicit bounded module.

Modules§

bounded
Explicitly bounded, complete-document adapters.

Structs§

ParseBaseDirectionError
Error returned when a string is not a valid BaseDirection token.
ResultHead
The header of a SPARQL results document: the projected variables, in declaration order, and any link IRIs.
ResultRow
A single row in a SELECT result.
SrjStreamSummary
Summary returned after a streaming SRJ parse completes.
SrjWriter
Incremental SRJ SELECT serializer.
SrxStreamSummary
Summary returned after a streaming SRX parse completes.
SrxWriter
Incremental SRX SELECT serializer.

Enums§

BaseDirection
The base direction of an RDF 1.2 directional language-tagged literal (rdf:dirLangString).
HeaderError
Why a result header (head in SRJ, <head> in SRX) was refused.
LiteralError
Why a literal’s annotations were refused while reading or writing a results document.
ResultValue
A value bound to a variable inside a row binding.
RowError
Why a row was refused before any of it was written.
SparqlResultsError
Errors raised while parsing or serializing SPARQL query result documents in SRX or SRJ form.
SrjStreamKind
Shape observed by parse_srj_streaming.
SrxStreamKind
Streaming SRX result shape.

Traits§

SrjStreamSink
Async sink for streaming SRJ events.
SrxStreamSink
Async sink for streaming SRX events.

Functions§

canonicalize_srx
Re-emit an SRX document in canonical form so semantically equivalent documents have identical bytes.
parse_srj_streaming
Parse SRJ directly from an async reader, awaiting each sink operation before reading the next event or row.
parse_srx_streaming
Parse SRX directly from an async reader, awaiting each sink operation before reading the next XML event.

Type Aliases§

Result
Result type used by all public parser and serializer operations.