Expand description
§sparql-results
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:
| Input | LiteralError |
|---|---|
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 tag | DirectionWithoutLanguage |
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 tag | DatatypeRequiresLanguage |
| 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:
- Apache License, Version 2.0 (
LICENSE-APACHEor https://www.apache.org/licenses/LICENSE-2.0). - MIT License (
LICENSE-MITor https://opensource.org/licenses/MIT). Standalone parsers and serializers for the W3C SPARQL Query Results interchange formats.
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§
- Parse
Base Direction Error - Error returned when a string is not a valid
BaseDirectiontoken. - Result
Head - The header of a SPARQL results document: the projected variables, in
declaration order, and any
linkIRIs. - Result
Row - A single row in a SELECT result.
- SrjStream
Summary - Summary returned after a streaming SRJ parse completes.
- SrjWriter
- Incremental SRJ SELECT serializer.
- SrxStream
Summary - Summary returned after a streaming SRX parse completes.
- SrxWriter
- Incremental SRX SELECT serializer.
Enums§
- Base
Direction - The base direction of an RDF 1.2 directional language-tagged literal
(
rdf:dirLangString). - Header
Error - Why a result header (
headin SRJ,<head>in SRX) was refused. - Literal
Error - Why a literal’s annotations were refused while reading or writing a results document.
- Result
Value - A value bound to a variable inside a row binding.
- RowError
- Why a row was refused before any of it was written.
- Sparql
Results Error - Errors raised while parsing or serializing SPARQL query result documents in SRX or SRJ form.
- SrjStream
Kind - Shape observed by
parse_srj_streaming. - SrxStream
Kind - Streaming SRX result shape.
Traits§
- SrjStream
Sink - Async sink for streaming SRJ events.
- SrxStream
Sink - 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.