rqw
rqw
SPARQL Endpoint interface, inspired by SPARQLWrapper
- A typed result per query form, and a typed error per SPARQL HTTP status
- t-string queries, checked against the SPARQL 1.1 grammar
httpxonly: one connection pool per client,asynciosupport, no RDF parsing
Install
# pip
pip install rqw
# pipx
pipx install rqw
# mise
mise use -g github:eggplants/rqw
# docker
docker pull ghcr.io/eggplants/rqw
CLI
$ rqw -Q 'SELECT ?s WHERE { ?s a <http://dbpedia.org/ontology/Fish> } LIMIT 3' --table
s
--------------------------------------
http://dbpedia.org/resource/Actinopoda
http://dbpedia.org/resource/Alfonsino
http://dbpedia.org/resource/Amberjack
$ rqw -e https://query.wikidata.org/sparql -f query.rq -F csv
$ echo 'ASK { ?s ?p ?o }' | rqw -f -
{
"head": {},
"boolean": true
}
Use rqw --help for more information.
Library
Overview
# sync
from rqw import SelectResult, SparqlClient
with SparqlClient("https://dbpedia.org/sparql") as sparql:
match sparql.execute("SELECT ?s ?p WHERE { ?s ?p ?o } LIMIT 5"):
case SelectResult() as rows:
for row in rows:
print(row["s"], row["p"])
# async
from rqw import AsyncSparqlClient
async def main() -> None:
async with AsyncSparqlClient("https://dbpedia.org/sparql") as sparql:
a, b = await asyncio.gather(
sparql.execute("SELECT * WHERE { ?s ?p ?o } LIMIT 10"),
sparql.execute("ASK { ?s ?p ?o }"),
)
asyncio.run(main())
execute() is the only entry point. It reads the query form off the query and
returns the matching member of QueryResult:
| query form | result | |
|---|---|---|
SELECT |
SelectResult |
a sequence of rows |
ASK |
AskResult |
.value, and truthy on its own |
CONSTRUCT, DESCRIBE |
GraphResult |
the serialized graph, .text or .data |
INSERT, DELETE, DROP, ... |
UpdateResult |
.status, POSTed to the update endpoint |
Narrowing with expect
expect names the form the query must take. The return type follows, and any
other form is refused before the request goes out:
rows = sparql.execute(query, expect=QueryForm.SELECT) # -> SelectResult
answer = sparql.execute(query, expect=QueryForm.ASK) # -> AskResult
sparql.execute("ASK { ?s ?p ?o }", expect=QueryForm.SELECT)
# QueryFormError: expected a SELECT query, got ASK
Formats and raw bodies
CONSTRUCT and DESCRIBE are the only forms that leave the serialization open;
the rest are read out of the SPARQL JSON results format. raw=True skips
parsing and hands back a RawResult in whatever format you ask for:
sparql.execute("DESCRIBE <http://dbpedia.org/resource/Tuna>", result_format=GraphFormat.NTRIPLES)
csv = sparql.execute(query, result_format=SolutionFormat.CSV, raw=True)
csv.text # 's,n\r\n...'
Asking for a format a form cannot answer in is a QueryFormError, raised before
the request goes out.
Terms
from rqw import Literal, Uri
match row["name"]:
case Literal(value=value, language="en"):
...
case Uri(value=uri):
...
row["count"].as_python() # 42, from an xsd:integer literal
t-strings support
from rqw import Uri
subject, name = Uri("http://example.org/a"), 'O"Brien'
sparql.execute(t"SELECT ?s WHERE {{ {subject} <http://e/name> {name} }}")
# sent as: SELECT ?s WHERE { <http://example.org/a> <http://e/name> "O\"Brien" }
| Python | SPARQL |
|---|---|
Uri, BlankNode, Literal, QuotedTriple |
the term itself |
str |
a quoted literal, "..." |
bool |
true / false |
int, float, Decimal |
a numeric literal |
date, time, datetime |
"..."^^xsd:... |
| a list or tuple | its items, space separated -- what VALUES wants |
a nested t"..." |
spliced in, values and all |
A str becomes a literal, never an IRI. Ask for another reading with a format
spec: {value:iri}, {value:var}.
After rendering, the whole query is tokenized and every spliced value is checked to still line up with a token boundary, so a value that tried to break out of a literal is refused rather than sent:
evil = '" } INSERT DATA { <a> <b> "pwned'
sparql.execute(t"SELECT ?s WHERE {{ ?s ?p {evil} }}")
# one literal, no second operation:
# SELECT ?s WHERE { ?s ?p "\" } INSERT DATA { <a> <b> \"pwned" }
sparql.execute(t'SELECT ?s WHERE {{ ?s ?p "{evil}" }}')
# QuerySyntaxError: an interpolated value cannot appear inside a token
rqw.parse gives the same Query on its own, which execute accepts directly
when you send one query many times.
Endpoint settings
SparqlClient(
"https://example.org/sparql",
update_endpoint="https://example.org/update",
default_graph=["http://example.org/g1"],
method=HttpMethod.POST, # default: GET while the URL is short enough
encoding=RequestEncoding.DIRECT, # application/sparql-query, skips form encoding
params={"timeout": "5000"}, # endpoint-specific knobs
headers={"X-Trace": "1"},
auth=("user", "password"),
timeout=30.0,
)
Passing client=httpx.Client(...) swaps in your own transport; closing it then
stays your job.
Errors
from rqw import BadQueryError
try:
sparql.execute("SELECT ?s WHERE {")
except BadQueryError as error:
print(error.status, error.body) # 400, the endpoint's own parser message
BadQueryError, UnauthorizedError, ForbiddenError, EndpointNotFoundError,
UriTooLongError, UnsupportedMediaTypeError and EndpointError derive from
SparqlHttpError; everything rqw raises derives from RqwError.
License
1""".. include:: ../README.md""" 2 3from __future__ import annotations 4 5import importlib.metadata 6 7try: 8 __version__ = importlib.metadata.version(__name__) 9except importlib.metadata.PackageNotFoundError: # pragma: no cover 10 __version__ = "0.0.0" 11 12from .client import USER_AGENT, AsyncSparqlClient, SparqlClient 13from .exceptions import ( 14 BadQueryError, 15 EndpointError, 16 EndpointNotFoundError, 17 ForbiddenError, 18 QueryFormError, 19 QuerySyntaxError, 20 ResponseError, 21 RqwError, 22 SparqlHttpError, 23 UnauthorizedError, 24 UnsupportedMediaTypeError, 25 UriTooLongError, 26) 27from .lexer import Token, TokenKind, tokenize 28from .parser import Query, QuerySource, detect_form, parse, render_value 29from .protocol import ( 30 EndpointConfig, 31 GraphFormat, 32 HttpMethod, 33 QueryForm, 34 RequestEncoding, 35 ResultFormat, 36 SolutionFormat, 37 parse_format, 38) 39from .results import AskResult, GraphResult, QueryResult, RawResult, Row, SelectResult, UpdateResult 40from .terms import BlankNode, Literal, QuotedTriple, Scalar, Term, Uri 41 42__all__ = [ 43 "USER_AGENT", 44 "AskResult", 45 "AsyncSparqlClient", 46 "BadQueryError", 47 "BlankNode", 48 "EndpointConfig", 49 "EndpointError", 50 "EndpointNotFoundError", 51 "ForbiddenError", 52 "GraphFormat", 53 "GraphResult", 54 "HttpMethod", 55 "Literal", 56 "Query", 57 "QueryForm", 58 "QueryFormError", 59 "QueryResult", 60 "QuerySource", 61 "QuerySyntaxError", 62 "QuotedTriple", 63 "RawResult", 64 "RequestEncoding", 65 "ResponseError", 66 "ResultFormat", 67 "Row", 68 "RqwError", 69 "Scalar", 70 "SelectResult", 71 "SolutionFormat", 72 "SparqlClient", 73 "SparqlHttpError", 74 "Term", 75 "Token", 76 "TokenKind", 77 "UnauthorizedError", 78 "UnsupportedMediaTypeError", 79 "UpdateResult", 80 "Uri", 81 "UriTooLongError", 82 "__version__", 83 "detect_form", 84 "parse", 85 "parse_format", 86 "render_value", 87 "tokenize", 88]
176@dataclass(frozen=True, slots=True) 177class AskResult: 178 """What an `ASK` query answered.""" 179 180 value: bool 181 """The endpoint's answer.""" 182 183 def __bool__(self) -> bool: 184 """Return the answer, so the result can be tested directly.""" 185 return self.value
What an ASK query answered.
296class AsyncSparqlClient(_BaseClient[httpx2.AsyncClient]): 297 """A SPARQL endpoint, queried with `asyncio`. 298 299 Same surface as `SparqlClient`, with `execute` awaitable. Running independent 300 queries through `asyncio.gather` on one client is the fastest way to get a 301 batch of results, since they share the connection pool. 302 303 Example: 304 >>> async with AsyncSparqlClient("https://dbpedia.org/sparql") as sparql: # doctest: +SKIP 305 ... result = await sparql.execute("SELECT ?s WHERE { ?s ?p ?o } LIMIT 10") 306 """ 307 308 _factory = httpx2.AsyncClient 309 310 async def __aenter__(self) -> Self: 311 """Enter a context that closes the client on the way out.""" 312 return self 313 314 async def __aexit__(self, *_: object) -> None: 315 """Close the client unless it was passed in from outside.""" 316 await self.aclose() 317 318 async def aclose(self) -> None: 319 """Close the pooled connections, unless the client was passed in.""" 320 if self._owns_client: 321 await self._client.aclose() 322 323 async def _send(self, spec: RequestSpec) -> httpx2.Response: 324 response = await self._client.send(self._request(spec)) 325 raise_for_status(response.status_code, str(response.url), response.content) 326 return response 327 328 @overload 329 async def execute( 330 self, 331 query: QuerySource, 332 *, 333 expect: Literal[QueryForm.SELECT], 334 result_format: None = None, 335 raw: Literal[False] = False, 336 ) -> SelectResult: ... 337 338 @overload 339 async def execute( 340 self, 341 query: QuerySource, 342 *, 343 expect: Literal[QueryForm.ASK], 344 result_format: None = None, 345 raw: Literal[False] = False, 346 ) -> AskResult: ... 347 348 @overload 349 async def execute( 350 self, 351 query: QuerySource, 352 *, 353 expect: Literal[QueryForm.CONSTRUCT, QueryForm.DESCRIBE], 354 result_format: GraphFormat | None = None, 355 raw: Literal[False] = False, 356 ) -> GraphResult: ... 357 358 @overload 359 async def execute( 360 self, 361 query: QuerySource, 362 *, 363 expect: Literal[ 364 QueryForm.INSERT, 365 QueryForm.DELETE, 366 QueryForm.WITH, 367 QueryForm.LOAD, 368 QueryForm.CLEAR, 369 QueryForm.CREATE, 370 QueryForm.DROP, 371 QueryForm.COPY, 372 QueryForm.MOVE, 373 QueryForm.ADD, 374 ], 375 result_format: None = None, 376 raw: Literal[False] = False, 377 ) -> UpdateResult: ... 378 379 @overload 380 async def execute( 381 self, 382 query: QuerySource, 383 *, 384 expect: QueryForm | None = None, 385 result_format: GraphFormat | None = None, 386 raw: Literal[False] = False, 387 ) -> QueryResult: ... 388 389 @overload 390 async def execute( 391 self, 392 query: QuerySource, 393 *, 394 expect: QueryForm | None = None, 395 result_format: ResultFormat | None = None, 396 raw: Literal[True], 397 ) -> RawResult[ResultFormat]: ... 398 399 async def execute( 400 self, 401 query: QuerySource, 402 *, 403 expect: QueryForm | None = None, 404 result_format: ResultFormat | None = None, 405 raw: bool = False, 406 ) -> QueryResult | RawResult[ResultFormat]: 407 """Run any SPARQL query or update operation. 408 409 The query form decides what comes back, so narrow the result before 410 using it -- `match` on the member you expect: 411 412 match sparql.execute(query): 413 case SelectResult() as rows: 414 ... 415 case AskResult(value=answer): 416 ... 417 case GraphResult() as graph: 418 graph.text 419 case UpdateResult(): 420 ... 421 422 Passing `expect` skips the narrowing: the return type is the one that 423 form calls for, and a query of any other form is refused before the 424 request goes out. With `raw=True` nothing is parsed and a `RawResult` 425 comes back on its own. 426 427 Args: 428 query: A `t"..."` template, plain query text, or a parsed `Query`. 429 Interpolated values are rendered as RDF terms, never as text. 430 Updates are routed to the update endpoint on their own. 431 expect: The form the query must be written in. 432 result_format: The serialization to ask for. Only `CONSTRUCT` and 433 `DESCRIBE` leave a choice unless `raw` is set, since the other 434 forms are parsed out of the SPARQL JSON results format. 435 raw: Hand the body back exactly as the endpoint serialized it. 436 437 Returns: 438 A `RawResult` when `raw` is set, otherwise the result type the 439 query form calls for. 440 441 Raises: 442 QuerySyntaxError: If the query text is not well-formed SPARQL. 443 QueryFormError: If the query form cannot be read, does not match 444 `expect`, or cannot answer in `result_format`. 445 """ 446 parsed, chosen, spec = self._plan(query, expect, result_format, raw=raw) 447 response = await self._send(spec) 448 body = RawResult(chosen, response.headers.get("content-type", ""), response.content) 449 return body if raw else interpret(parsed.form, body, response.status_code)
A SPARQL endpoint, queried with asyncio.
Same surface as SparqlClient, with execute awaitable. Running independent
queries through asyncio.gather on one client is the fastest way to get a
batch of results, since they share the connection pool.
Example:
>>> async with AsyncSparqlClient("https://dbpedia.org/sparql") as sparql: # doctest: +SKIP ... result = await sparql.execute("SELECT ?s WHERE { ?s ?p ?o } LIMIT 10")
318 async def aclose(self) -> None: 319 """Close the pooled connections, unless the client was passed in.""" 320 if self._owns_client: 321 await self._client.aclose()
Close the pooled connections, unless the client was passed in.
399 async def execute( 400 self, 401 query: QuerySource, 402 *, 403 expect: QueryForm | None = None, 404 result_format: ResultFormat | None = None, 405 raw: bool = False, 406 ) -> QueryResult | RawResult[ResultFormat]: 407 """Run any SPARQL query or update operation. 408 409 The query form decides what comes back, so narrow the result before 410 using it -- `match` on the member you expect: 411 412 match sparql.execute(query): 413 case SelectResult() as rows: 414 ... 415 case AskResult(value=answer): 416 ... 417 case GraphResult() as graph: 418 graph.text 419 case UpdateResult(): 420 ... 421 422 Passing `expect` skips the narrowing: the return type is the one that 423 form calls for, and a query of any other form is refused before the 424 request goes out. With `raw=True` nothing is parsed and a `RawResult` 425 comes back on its own. 426 427 Args: 428 query: A `t"..."` template, plain query text, or a parsed `Query`. 429 Interpolated values are rendered as RDF terms, never as text. 430 Updates are routed to the update endpoint on their own. 431 expect: The form the query must be written in. 432 result_format: The serialization to ask for. Only `CONSTRUCT` and 433 `DESCRIBE` leave a choice unless `raw` is set, since the other 434 forms are parsed out of the SPARQL JSON results format. 435 raw: Hand the body back exactly as the endpoint serialized it. 436 437 Returns: 438 A `RawResult` when `raw` is set, otherwise the result type the 439 query form calls for. 440 441 Raises: 442 QuerySyntaxError: If the query text is not well-formed SPARQL. 443 QueryFormError: If the query form cannot be read, does not match 444 `expect`, or cannot answer in `result_format`. 445 """ 446 parsed, chosen, spec = self._plan(query, expect, result_format, raw=raw) 447 response = await self._send(spec) 448 body = RawResult(chosen, response.headers.get("content-type", ""), response.content) 449 return body if raw else interpret(parsed.form, body, response.status_code)
Run any SPARQL query or update operation.
The query form decides what comes back, so narrow the result before
using it -- match on the member you expect:
match sparql.execute(query):
case SelectResult() as rows:
...
case AskResult(value=answer):
...
case GraphResult() as graph:
graph.text
case UpdateResult():
...
Passing expect skips the narrowing: the return type is the one that
form calls for, and a query of any other form is refused before the
request goes out. With raw=True nothing is parsed and a RawResult
comes back on its own.
Arguments:
- query: A
t"..."template, plain query text, or a parsedQuery. Interpolated values are rendered as RDF terms, never as text. Updates are routed to the update endpoint on their own. - expect: The form the query must be written in.
- result_format: The serialization to ask for. Only
CONSTRUCTandDESCRIBEleave a choice unlessrawis set, since the other forms are parsed out of the SPARQL JSON results format. - raw: Hand the body back exactly as the endpoint serialized it.
Returns:
A
RawResultwhenrawis set, otherwise the result type the query form calls for.
Raises:
- QuerySyntaxError: If the query text is not well-formed SPARQL.
- QueryFormError: If the query form cannot be read, does not match
expect, or cannot answer inresult_format.
84class BadQueryError(SparqlHttpError): 85 """`400 Bad Request`, usually a syntax error in the query."""
400 Bad Request, usually a syntax error in the query.
42@dataclass(frozen=True, slots=True) 43class BlankNode: 44 """A blank node, identified by a label that is only stable within one result set.""" 45 46 value: str 47 48 def __str__(self) -> str: 49 """Return the label in Turtle notation.""" 50 return f"_:{self.value}"
A blank node, identified by a label that is only stable within one result set.
145@dataclass(frozen=True, slots=True) 146class EndpointConfig: 147 """Everything about an endpoint that does not change from query to query.""" 148 149 endpoint: str 150 """URL that query operations are sent to.""" 151 update_endpoint: str | None = None 152 """URL that update operations are sent to; defaults to `endpoint`.""" 153 default_graph: tuple[str, ...] = () 154 """Graphs making up the RDF dataset's default graph.""" 155 named_graph: tuple[str, ...] = () 156 """Graphs making up the RDF dataset's named graphs.""" 157 method: HttpMethod | None = None 158 """Verb to use; `None` picks `GET` while the URL stays under `max_get_length`.""" 159 encoding: RequestEncoding = RequestEncoding.URL_ENCODED 160 """How a `POST` carries the query.""" 161 params: tuple[tuple[str, str], ...] = () 162 """Extra query-string parameters, for endpoint-specific knobs.""" 163 max_get_length: int = 2048 164 """URL length above which `method=None` switches to `POST`."""
Everything about an endpoint that does not change from query to query.
108class EndpointError(SparqlHttpError): 109 """The endpoint failed on its side, any `5xx` status."""
The endpoint failed on its side, any 5xx status.
96class EndpointNotFoundError(SparqlHttpError): 97 """`404 Not Found`, most likely a typo in the endpoint URL."""
404 Not Found, most likely a typo in the endpoint URL.
92class ForbiddenError(SparqlHttpError): 93 """`403 Forbidden`, the credentials are not allowed to run this operation."""
403 Forbidden, the credentials are not allowed to run this operation.
81class GraphFormat(StrEnum): 82 """Serializations of the RDF graph a `CONSTRUCT`/`DESCRIBE` answers with.""" 83 84 TURTLE = "turtle" 85 NTRIPLES = "ntriples" 86 RDFXML = "rdfxml" 87 JSONLD = "jsonld" 88 N3 = "n3" 89 TRIG = "trig"
Serializations of the RDF graph a CONSTRUCT/DESCRIBE answers with.
188@dataclass(frozen=True, slots=True) 189class GraphResult(RawResult[GraphFormat]): 190 """The RDF graph a `CONSTRUCT` or `DESCRIBE` answered with, still serialized."""
The RDF graph a CONSTRUCT or DESCRIBE answered with, still serialized.
96class HttpMethod(StrEnum): 97 """The HTTP verb used to carry the query.""" 98 99 GET = "GET" 100 POST = "POST"
The HTTP verb used to carry the query.
53@dataclass(frozen=True, slots=True) 54class Literal: 55 """A literal, with at most one of a language tag or a datatype IRI.""" 56 57 value: str 58 language: str | None = None 59 datatype: str | None = None 60 61 def __str__(self) -> str: 62 """Return the lexical form.""" 63 return self.value 64 65 def as_python(self) -> Scalar: 66 """Decode the lexical form according to the literal's datatype. 67 68 Literals with no datatype, a language tag, or a datatype rqw does not 69 know about are returned unchanged as `str`. 70 71 Returns: 72 The decoded value. 73 74 Raises: 75 ValueError: If the lexical form is not valid for the datatype. 76 """ 77 decode = _DECODERS.get(self.datatype or "") 78 return self.value if decode is None else decode(self.value)
A literal, with at most one of a language tag or a datatype IRI.
65 def as_python(self) -> Scalar: 66 """Decode the lexical form according to the literal's datatype. 67 68 Literals with no datatype, a language tag, or a datatype rqw does not 69 know about are returned unchanged as `str`. 70 71 Returns: 72 The decoded value. 73 74 Raises: 75 ValueError: If the lexical form is not valid for the datatype. 76 """ 77 decode = _DECODERS.get(self.datatype or "") 78 return self.value if decode is None else decode(self.value)
Decode the lexical form according to the literal's datatype.
Literals with no datatype, a language tag, or a datatype rqw does not
know about are returned unchanged as str.
Returns:
The decoded value.
Raises:
- ValueError: If the lexical form is not valid for the datatype.
44@dataclass(frozen=True, slots=True) 45class Query: 46 """A query whose form is known and whose text is ready to send.""" 47 48 form: QueryForm 49 """The form the query text starts with, once its prologue is skipped.""" 50 text: str 51 """The query text, with every interpolation rendered in.""" 52 53 def __str__(self) -> str: 54 """Return the query text.""" 55 return self.text
A query whose form is known and whose text is ready to send.
39class QueryForm(StrEnum): 40 """The keyword a SPARQL query or update operation starts with.""" 41 42 SELECT = "SELECT" 43 ASK = "ASK" 44 CONSTRUCT = "CONSTRUCT" 45 DESCRIBE = "DESCRIBE" 46 INSERT = "INSERT" 47 DELETE = "DELETE" 48 WITH = "WITH" 49 LOAD = "LOAD" 50 CLEAR = "CLEAR" 51 CREATE = "CREATE" 52 DROP = "DROP" 53 COPY = "COPY" 54 MOVE = "MOVE" 55 ADD = "ADD" 56 57 @property 58 def is_update(self) -> bool: 59 """Whether this form mutates the store and must go to the update endpoint.""" 60 return self not in READ_FORMS
The keyword a SPARQL query or update operation starts with.
31class QueryFormError(RqwError, ValueError): 32 """The query form could not be detected, or is not the one that was asked for."""
The query form could not be detected, or is not the one that was asked for.
35class QuerySyntaxError(RqwError, ValueError): 36 """The query text is not well-formed SPARQL. 37 38 Attributes: 39 position: Index into the query text where the problem starts, or `None` 40 when the problem is not tied to one spot. 41 """ 42 43 def __init__(self, message: str, position: int | None = None) -> None: 44 """Build the exception. 45 46 Args: 47 message: What is wrong. 48 position: Index into the query text where the problem starts. 49 """ 50 self.position = position 51 super().__init__(message if position is None else f"{message} at position {position}")
The query text is not well-formed SPARQL.
Attributes:
- position: Index into the query text where the problem starts, or
Nonewhen the problem is not tied to one spot.
43 def __init__(self, message: str, position: int | None = None) -> None: 44 """Build the exception. 45 46 Args: 47 message: What is wrong. 48 position: Index into the query text where the problem starts. 49 """ 50 self.position = position 51 super().__init__(message if position is None else f"{message} at position {position}")
Build the exception.
Arguments:
- message: What is wrong.
- position: Index into the query text where the problem starts.
81@dataclass(frozen=True, slots=True) 82class QuotedTriple: 83 """A quoted triple, the term type SPARQL 1.2 adds for RDF-star.""" 84 85 subject: Term 86 predicate: Uri 87 object: Term 88 89 def __str__(self) -> str: 90 """Return the triple in the `<< s p o >>` notation.""" 91 return f"<< {self.subject} {self.predicate} {self.object} >>"
A quoted triple, the term type SPARQL 1.2 adds for RDF-star.
80@dataclass(frozen=True, slots=True) 81class RawResult[F: ResultFormat]: 82 """A response body handed over exactly as the endpoint serialized it. 83 84 The type parameter records which family of formats was asked for, so 85 `SparqlClient.graph` can promise a `RawResult[GraphFormat]`. 86 """ 87 88 format: F 89 """The format that was requested.""" 90 content_type: str 91 """The `Content-Type` header the endpoint answered with.""" 92 data: bytes 93 """The undecoded body.""" 94 95 @property 96 def charset(self) -> str: 97 """The charset from the `Content-Type` header, `utf-8` when it says nothing.""" 98 _, _, rest = self.content_type.partition("charset=") 99 return rest.partition(";")[0].strip().strip('"') or "utf-8" 100 101 @property 102 def text(self) -> str: 103 """The body decoded with `charset`.""" 104 return self.data.decode(self.charset, "replace") 105 106 def json(self) -> Any: # noqa: ANN401 107 """Parse the body as JSON, for the `json` and `jsonld` formats. 108 109 Returns: 110 Whatever the body decodes to. 111 112 Raises: 113 ResponseError: If the body is not valid JSON. 114 """ 115 try: 116 return json.loads(self.data) 117 except ValueError as exc: 118 msg = f"expected {self.format} but the body is not JSON" 119 raise ResponseError(msg) from exc
A response body handed over exactly as the endpoint serialized it.
The type parameter records which family of formats was asked for, so
SparqlClient.graph can promise a RawResult[GraphFormat].
95 @property 96 def charset(self) -> str: 97 """The charset from the `Content-Type` header, `utf-8` when it says nothing.""" 98 _, _, rest = self.content_type.partition("charset=") 99 return rest.partition(";")[0].strip().strip('"') or "utf-8"
The charset from the Content-Type header, utf-8 when it says nothing.
101 @property 102 def text(self) -> str: 103 """The body decoded with `charset`.""" 104 return self.data.decode(self.charset, "replace")
The body decoded with charset.
106 def json(self) -> Any: # noqa: ANN401 107 """Parse the body as JSON, for the `json` and `jsonld` formats. 108 109 Returns: 110 Whatever the body decodes to. 111 112 Raises: 113 ResponseError: If the body is not valid JSON. 114 """ 115 try: 116 return json.loads(self.data) 117 except ValueError as exc: 118 msg = f"expected {self.format} but the body is not JSON" 119 raise ResponseError(msg) from exc
Parse the body as JSON, for the json and jsonld formats.
Returns:
Whatever the body decodes to.
Raises:
- ResponseError: If the body is not valid JSON.
103class RequestEncoding(StrEnum): 104 """How a `POST` carries the query.""" 105 106 URL_ENCODED = "urlencoded" 107 """`application/x-www-form-urlencoded`; understood by every endpoint.""" 108 DIRECT = "direct" 109 """`application/sparql-query`; skips percent-encoding the whole query."""
How a POST carries the query.
application/x-www-form-urlencoded; understood by every endpoint.
application/sparql-query; skips percent-encoding the whole query.
54class ResponseError(RqwError, ValueError): 55 """The endpoint answered with a body that does not match the requested format."""
The endpoint answered with a body that does not match the requested format.
Base class of every exception raised by this package.
37@dataclass(frozen=True, slots=True) 38class SelectResult(Sequence[Row]): 39 """The solution sequence of a `SELECT` query, as a sequence of `Row`.""" 40 41 variables: tuple[str, ...] 42 """The projected variables, in the order the endpoint reported them.""" 43 rows: tuple[Row, ...] 44 """The solutions.""" 45 46 def __len__(self) -> int: 47 """Return the number of solutions.""" 48 return len(self.rows) 49 50 @overload 51 def __getitem__(self, index: int) -> Row: ... 52 @overload 53 def __getitem__(self, index: slice) -> tuple[Row, ...]: ... 54 55 def __getitem__(self, index: int | slice) -> Row | tuple[Row, ...]: 56 """Return the solution, or the slice of solutions, at `index`.""" 57 return self.rows[index] 58 59 def __iter__(self) -> Iterator[Row]: 60 """Iterate over the solutions.""" 61 return iter(self.rows) 62 63 def column(self, variable: str) -> tuple[Term | None, ...]: 64 """Collect one variable's binding across every solution. 65 66 Args: 67 variable: The variable name, without the leading `?`. 68 69 Returns: 70 One entry per solution, `None` where the variable is unbound. 71 72 Raises: 73 KeyError: If the query did not project `variable`. 74 """ 75 if variable not in self.variables: 76 raise KeyError(variable) 77 return tuple(row.get(variable) for row in self.rows)
The solution sequence of a SELECT query, as a sequence of Row.
63 def column(self, variable: str) -> tuple[Term | None, ...]: 64 """Collect one variable's binding across every solution. 65 66 Args: 67 variable: The variable name, without the leading `?`. 68 69 Returns: 70 One entry per solution, `None` where the variable is unbound. 71 72 Raises: 73 KeyError: If the query did not project `variable`. 74 """ 75 if variable not in self.variables: 76 raise KeyError(variable) 77 return tuple(row.get(variable) for row in self.rows)
Collect one variable's binding across every solution.
Arguments:
- variable: The variable name, without the leading
?.
Returns:
One entry per solution,
Nonewhere the variable is unbound.
Raises:
- KeyError: If the query did not project
variable.
72class SolutionFormat(StrEnum): 73 """Serializations of a `SELECT`/`ASK` solution sequence.""" 74 75 JSON = "json" 76 XML = "xml" 77 CSV = "csv" 78 TSV = "tsv"
Serializations of a SELECT/ASK solution sequence.
135class SparqlClient(_BaseClient[httpx2.Client]): 136 """A SPARQL endpoint, queried synchronously. 137 138 The underlying connection is pooled and kept alive, so reusing one client 139 for many queries is much cheaper than building one per query. 140 141 Every query form goes through `execute`, which reads the form off the query 142 and answers with the result type that form calls for. 143 144 Example: 145 >>> with SparqlClient("https://dbpedia.org/sparql") as sparql: # doctest: +SKIP 146 ... match sparql.execute("SELECT ?s WHERE { ?s ?p ?o } LIMIT 10"): 147 ... case SelectResult() as rows: 148 ... for row in rows: 149 ... print(row["s"]) 150 """ 151 152 _factory = httpx2.Client 153 154 def __enter__(self) -> Self: 155 """Enter a context that closes the client on the way out.""" 156 return self 157 158 def __exit__(self, *_: object) -> None: 159 """Close the client unless it was passed in from outside.""" 160 self.close() 161 162 def close(self) -> None: 163 """Close the pooled connections, unless the client was passed in.""" 164 if self._owns_client: 165 self._client.close() 166 167 def _send(self, spec: RequestSpec) -> httpx2.Response: 168 response = self._client.send(self._request(spec)) 169 raise_for_status(response.status_code, str(response.url), response.content) 170 return response 171 172 @overload 173 def execute( 174 self, 175 query: QuerySource, 176 *, 177 expect: Literal[QueryForm.SELECT], 178 result_format: None = None, 179 raw: Literal[False] = False, 180 ) -> SelectResult: ... 181 182 @overload 183 def execute( 184 self, 185 query: QuerySource, 186 *, 187 expect: Literal[QueryForm.ASK], 188 result_format: None = None, 189 raw: Literal[False] = False, 190 ) -> AskResult: ... 191 192 @overload 193 def execute( 194 self, 195 query: QuerySource, 196 *, 197 expect: Literal[QueryForm.CONSTRUCT, QueryForm.DESCRIBE], 198 result_format: GraphFormat | None = None, 199 raw: Literal[False] = False, 200 ) -> GraphResult: ... 201 202 @overload 203 def execute( 204 self, 205 query: QuerySource, 206 *, 207 expect: Literal[ 208 QueryForm.INSERT, 209 QueryForm.DELETE, 210 QueryForm.WITH, 211 QueryForm.LOAD, 212 QueryForm.CLEAR, 213 QueryForm.CREATE, 214 QueryForm.DROP, 215 QueryForm.COPY, 216 QueryForm.MOVE, 217 QueryForm.ADD, 218 ], 219 result_format: None = None, 220 raw: Literal[False] = False, 221 ) -> UpdateResult: ... 222 223 @overload 224 def execute( 225 self, 226 query: QuerySource, 227 *, 228 expect: QueryForm | None = None, 229 result_format: GraphFormat | None = None, 230 raw: Literal[False] = False, 231 ) -> QueryResult: ... 232 233 @overload 234 def execute( 235 self, 236 query: QuerySource, 237 *, 238 expect: QueryForm | None = None, 239 result_format: ResultFormat | None = None, 240 raw: Literal[True], 241 ) -> RawResult[ResultFormat]: ... 242 243 def execute( 244 self, 245 query: QuerySource, 246 *, 247 expect: QueryForm | None = None, 248 result_format: ResultFormat | None = None, 249 raw: bool = False, 250 ) -> QueryResult | RawResult[ResultFormat]: 251 """Run any SPARQL query or update operation. 252 253 The query form decides what comes back, so narrow the result before 254 using it -- `match` on the member you expect: 255 256 match sparql.execute(query): 257 case SelectResult() as rows: 258 ... 259 case AskResult(value=answer): 260 ... 261 case GraphResult() as graph: 262 graph.text 263 case UpdateResult(): 264 ... 265 266 Passing `expect` skips the narrowing: the return type is the one that 267 form calls for, and a query of any other form is refused before the 268 request goes out. With `raw=True` nothing is parsed and a `RawResult` 269 comes back on its own. 270 271 Args: 272 query: A `t"..."` template, plain query text, or a parsed `Query`. 273 Interpolated values are rendered as RDF terms, never as text. 274 Updates are routed to the update endpoint on their own. 275 expect: The form the query must be written in. 276 result_format: The serialization to ask for. Only `CONSTRUCT` and 277 `DESCRIBE` leave a choice unless `raw` is set, since the other 278 forms are parsed out of the SPARQL JSON results format. 279 raw: Hand the body back exactly as the endpoint serialized it. 280 281 Returns: 282 A `RawResult` when `raw` is set, otherwise the result type the 283 query form calls for. 284 285 Raises: 286 QuerySyntaxError: If the query text is not well-formed SPARQL. 287 QueryFormError: If the query form cannot be read, does not match 288 `expect`, or cannot answer in `result_format`. 289 """ 290 parsed, chosen, spec = self._plan(query, expect, result_format, raw=raw) 291 response = self._send(spec) 292 body = RawResult(chosen, response.headers.get("content-type", ""), response.content) 293 return body if raw else interpret(parsed.form, body, response.status_code)
A SPARQL endpoint, queried synchronously.
The underlying connection is pooled and kept alive, so reusing one client for many queries is much cheaper than building one per query.
Every query form goes through execute, which reads the form off the query
and answers with the result type that form calls for.
Example:
>>> with SparqlClient("https://dbpedia.org/sparql") as sparql: # doctest: +SKIP ... match sparql.execute("SELECT ?s WHERE { ?s ?p ?o } LIMIT 10"): ... case SelectResult() as rows: ... for row in rows: ... print(row["s"])
162 def close(self) -> None: 163 """Close the pooled connections, unless the client was passed in.""" 164 if self._owns_client: 165 self._client.close()
Close the pooled connections, unless the client was passed in.
243 def execute( 244 self, 245 query: QuerySource, 246 *, 247 expect: QueryForm | None = None, 248 result_format: ResultFormat | None = None, 249 raw: bool = False, 250 ) -> QueryResult | RawResult[ResultFormat]: 251 """Run any SPARQL query or update operation. 252 253 The query form decides what comes back, so narrow the result before 254 using it -- `match` on the member you expect: 255 256 match sparql.execute(query): 257 case SelectResult() as rows: 258 ... 259 case AskResult(value=answer): 260 ... 261 case GraphResult() as graph: 262 graph.text 263 case UpdateResult(): 264 ... 265 266 Passing `expect` skips the narrowing: the return type is the one that 267 form calls for, and a query of any other form is refused before the 268 request goes out. With `raw=True` nothing is parsed and a `RawResult` 269 comes back on its own. 270 271 Args: 272 query: A `t"..."` template, plain query text, or a parsed `Query`. 273 Interpolated values are rendered as RDF terms, never as text. 274 Updates are routed to the update endpoint on their own. 275 expect: The form the query must be written in. 276 result_format: The serialization to ask for. Only `CONSTRUCT` and 277 `DESCRIBE` leave a choice unless `raw` is set, since the other 278 forms are parsed out of the SPARQL JSON results format. 279 raw: Hand the body back exactly as the endpoint serialized it. 280 281 Returns: 282 A `RawResult` when `raw` is set, otherwise the result type the 283 query form calls for. 284 285 Raises: 286 QuerySyntaxError: If the query text is not well-formed SPARQL. 287 QueryFormError: If the query form cannot be read, does not match 288 `expect`, or cannot answer in `result_format`. 289 """ 290 parsed, chosen, spec = self._plan(query, expect, result_format, raw=raw) 291 response = self._send(spec) 292 body = RawResult(chosen, response.headers.get("content-type", ""), response.content) 293 return body if raw else interpret(parsed.form, body, response.status_code)
Run any SPARQL query or update operation.
The query form decides what comes back, so narrow the result before
using it -- match on the member you expect:
match sparql.execute(query):
case SelectResult() as rows:
...
case AskResult(value=answer):
...
case GraphResult() as graph:
graph.text
case UpdateResult():
...
Passing expect skips the narrowing: the return type is the one that
form calls for, and a query of any other form is refused before the
request goes out. With raw=True nothing is parsed and a RawResult
comes back on its own.
Arguments:
- query: A
t"..."template, plain query text, or a parsedQuery. Interpolated values are rendered as RDF terms, never as text. Updates are routed to the update endpoint on their own. - expect: The form the query must be written in.
- result_format: The serialization to ask for. Only
CONSTRUCTandDESCRIBEleave a choice unlessrawis set, since the other forms are parsed out of the SPARQL JSON results format. - raw: Hand the body back exactly as the endpoint serialized it.
Returns:
A
RawResultwhenrawis set, otherwise the result type the query form calls for.
Raises:
- QuerySyntaxError: If the query text is not well-formed SPARQL.
- QueryFormError: If the query form cannot be read, does not match
expect, or cannot answer inresult_format.
58class SparqlHttpError(RqwError): 59 """The endpoint answered with an HTTP error status. 60 61 Attributes: 62 status: The HTTP status code. 63 url: The URL that was requested. 64 body: The raw response body, useful because endpoints put the parser 65 error of a malformed query in there. 66 """ 67 68 def __init__(self, status: int, url: str, body: bytes = b"") -> None: 69 """Build the exception from the failed response. 70 71 Args: 72 status: The HTTP status code. 73 url: The URL that was requested. 74 body: The raw response body. 75 """ 76 self.status = status 77 self.url = url 78 self.body = body 79 excerpt = body[:_EXCERPT].decode("utf-8", "replace").strip() 80 detail = f": {excerpt}" if excerpt else "" 81 super().__init__(f"{url} returned HTTP {status}{detail}")
The endpoint answered with an HTTP error status.
Attributes:
- status: The HTTP status code.
- url: The URL that was requested.
- body: The raw response body, useful because endpoints put the parser error of a malformed query in there.
68 def __init__(self, status: int, url: str, body: bytes = b"") -> None: 69 """Build the exception from the failed response. 70 71 Args: 72 status: The HTTP status code. 73 url: The URL that was requested. 74 body: The raw response body. 75 """ 76 self.status = status 77 self.url = url 78 self.body = body 79 excerpt = body[:_EXCERPT].decode("utf-8", "replace").strip() 80 detail = f": {excerpt}" if excerpt else "" 81 super().__init__(f"{url} returned HTTP {status}{detail}")
Build the exception from the failed response.
Arguments:
- status: The HTTP status code.
- url: The URL that was requested.
- body: The raw response body.
108@dataclass(frozen=True, slots=True) 109class Token: 110 """One terminal, with the span it occupies in the query text.""" 111 112 kind: TokenKind 113 text: str 114 start: int 115 end: int 116 117 @property 118 def word(self) -> str: 119 """The token upper-cased, for comparing against a keyword. 120 121 SPARQL matches keywords case-insensitively, with the sole exception of 122 `a`, which the grammar treats as an IRI rather than a keyword. 123 """ 124 return self.text.upper()
One terminal, with the span it occupies in the query text.
117 @property 118 def word(self) -> str: 119 """The token upper-cased, for comparing against a keyword. 120 121 SPARQL matches keywords case-insensitively, with the sole exception of 122 `a`, which the grammar treats as an IRI rather than a keyword. 123 """ 124 return self.text.upper()
The token upper-cased, for comparing against a keyword.
SPARQL matches keywords case-insensitively, with the sole exception of
a, which the grammar treats as an IRI rather than a keyword.
24class TokenKind(StrEnum): 25 """The terminal a token was recognized as.""" 26 27 IRIREF = "IRIREF" 28 """`<http://example.org/>`, production [139].""" 29 PNAME = "PNAME" 30 """A prefixed name, `foaf:name` or the bare `foaf:`, productions [140]-[141].""" 31 BLANK_NODE_LABEL = "BLANK_NODE_LABEL" 32 """`_:b0`, production [142].""" 33 VAR = "VAR" 34 """`?name` or `$name`, productions [143]-[144].""" 35 LANGTAG = "LANGTAG" 36 """`@en-GB`, production [145].""" 37 INTEGER = "INTEGER" 38 """Productions [146], [149] and [152].""" 39 DECIMAL = "DECIMAL" 40 """Productions [147], [150] and [153].""" 41 DOUBLE = "DOUBLE" 42 """Productions [148], [151] and [154].""" 43 STRING = "STRING" 44 """A quoted string in any of its four forms, productions [156]-[159].""" 45 NIL = "NIL" 46 """`()`, production [161].""" 47 ANON = "ANON" 48 """`[]`, production [163].""" 49 WORD = "WORD" 50 """A bare name: a keyword, `a`, `true` or `false`.""" 51 PUNCT = "PUNCT" 52 """Punctuation and operators."""
The terminal a token was recognized as.
A prefixed name, foaf:name or the bare foaf:, productions [140]-[141].
A quoted string in any of its four forms, productions [156]-[159].
104class UnsupportedMediaTypeError(SparqlHttpError): 105 """`415 Unsupported Media Type`; retry with `encoding=RequestEncoding.URL_ENCODED`."""
415 Unsupported Media Type; retry with encoding=RequestEncoding.URL_ENCODED.
193@dataclass(frozen=True, slots=True) 194class UpdateResult: 195 """The endpoint's acknowledgement of an update operation.""" 196 197 status: int 198 """The HTTP status the endpoint accepted the operation with."""
The endpoint's acknowledgement of an update operation.
31@dataclass(frozen=True, slots=True) 32class Uri: 33 """An IRI.""" 34 35 value: str 36 37 def __str__(self) -> str: 38 """Return the IRI itself.""" 39 return self.value
An IRI.
100class UriTooLongError(SparqlHttpError): 101 """`414 URI Too Long`; retry with `method=HttpMethod.POST`."""
414 URI Too Long; retry with method=HttpMethod.POST.
298def detect_form(source: QuerySource) -> QueryForm: 299 """Work out which form a query is written in. 300 301 Args: 302 source: A t-string, plain query text, or an already parsed `Query`. 303 304 Returns: 305 The query form. 306 307 Raises: 308 QuerySyntaxError: If the text is not well-formed SPARQL. 309 QueryFormError: If nothing after the prologue names a query form. 310 """ 311 return parse(source).form
Work out which form a query is written in.
Arguments:
- source: A t-string, plain query text, or an already parsed
Query.
Returns:
The query form.
Raises:
- QuerySyntaxError: If the text is not well-formed SPARQL.
- QueryFormError: If nothing after the prologue names a query form.
269def parse(source: QuerySource) -> Query: 270 """Read a query, rendering any interpolations, and work out its form. 271 272 Args: 273 source: A t-string, plain query text, or an already parsed `Query`. 274 275 Returns: 276 The parsed query. 277 278 Raises: 279 QuerySyntaxError: If the text is not well-formed SPARQL, a value has no 280 SPARQL term, or an interpolation would land inside a token. 281 QueryFormError: If nothing after the prologue names a query form. 282 """ 283 if isinstance(source, Query): 284 return source 285 holes: list[tuple[int, int]] = [] 286 if isinstance(source, Template): 287 segments: list[str | _Hole] = [] 288 _segments(source, segments) 289 text, holes = _assemble(segments) 290 else: 291 text = unescape_codepoints(source) 292 tokens = tokenize(text) 293 _check_holes(tokens, holes) 294 _check_nesting(tokens) 295 return Query(_detect_form(tokens, text), text)
Read a query, rendering any interpolations, and work out its form.
Arguments:
- source: A t-string, plain query text, or an already parsed
Query.
Returns:
The parsed query.
Raises:
- QuerySyntaxError: If the text is not well-formed SPARQL, a value has no SPARQL term, or an interpolation would land inside a token.
- QueryFormError: If nothing after the prologue names a query form.
127def parse_format(name: str) -> ResultFormat: 128 """Look a result format up by its name. 129 130 Args: 131 name: A member value of `SolutionFormat` or `GraphFormat`. 132 133 Returns: 134 The matching format. 135 136 Raises: 137 ValueError: If no format goes by that name. 138 """ 139 try: 140 return SolutionFormat(name) 141 except ValueError: 142 return GraphFormat(name)
Look a result format up by its name.
Arguments:
- name: A member value of
SolutionFormatorGraphFormat.
Returns:
The matching format.
Raises:
- ValueError: If no format goes by that name.
114def render_value(value: object, spec: str = "") -> str: # noqa: PLR0911 115 """Render a Python value as the SPARQL text of one or more terms. 116 117 `str` becomes a quoted literal rather than an IRI, which is the safe way 118 round; ask for an IRI with `{value:iri}` or by passing a `Uri`. A sequence 119 renders as its items separated by spaces, which is what a `VALUES` block 120 wants. 121 122 Args: 123 value: The value to render. 124 spec: The t-string format spec, `iri` or `var`, or empty to go by type. 125 126 Returns: 127 The SPARQL text for the value. 128 129 Raises: 130 QuerySyntaxError: If the value has no SPARQL term, or cannot be written 131 as one without changing what it means. 132 """ 133 if spec: 134 return _render_with_spec(value, spec) 135 match value: 136 case Uri() | BlankNode() | Literal() | QuotedTriple(): 137 return _render_term(value) 138 case bool(): 139 return "true" if value else "false" 140 case str(): 141 return _quote(value) 142 case bytes() | bytearray(): 143 msg = "bytes have no SPARQL term; decode them first" 144 raise QuerySyntaxError(msg) 145 case int(): 146 return str(value) 147 case float() | Decimal(): 148 return _render_number(value) 149 case date() | time(): 150 return _render_temporal(value) 151 case Sequence(): 152 return " ".join(render_value(item) for item in value) 153 case _: 154 msg = f"{type(value).__name__} has no SPARQL term" 155 raise QuerySyntaxError(msg)
Render a Python value as the SPARQL text of one or more terms.
str becomes a quoted literal rather than an IRI, which is the safe way
round; ask for an IRI with {value:iri} or by passing a Uri. A sequence
renders as its items separated by spaces, which is what a VALUES block
wants.
Arguments:
- value: The value to render.
- spec: The t-string format spec,
iriorvar, or empty to go by type.
Returns:
The SPARQL text for the value.
Raises:
- QuerySyntaxError: If the value has no SPARQL term, or cannot be written as one without changing what it means.
158def tokenize(text: str) -> list[Token]: 159 """Split SPARQL text into terminals. 160 161 Args: 162 text: The query text, with codepoint escapes already resolved. 163 164 Returns: 165 The tokens, with whitespace and comments dropped. 166 167 Raises: 168 QuerySyntaxError: At the first character that starts no terminal, which 169 is also how an unterminated string or IRI is reported. 170 """ 171 tokens: list[Token] = [] 172 position = 0 173 length = len(text) 174 while position < length: 175 match = _TOKEN.match(text, position) 176 if match is None: 177 msg = f"unexpected {text[position]!r}" 178 raise QuerySyntaxError(msg, position) 179 position = match.end() 180 kind = match.lastgroup 181 if kind != "skip": 182 tokens.append(Token(TokenKind(kind), match.group(), match.start(), match.end())) 183 return tokens
Split SPARQL text into terminals.
Arguments:
- text: The query text, with codepoint escapes already resolved.
Returns:
The tokens, with whitespace and comments dropped.
Raises:
- QuerySyntaxError: At the first character that starts no terminal, which is also how an unterminated string or IRI is reported.