src/rdflib/plugins/sparql/results/rdfresults.py
1from __future__ import annotations
2
3from typing import IO, Any, MutableMapping, Optional, Union
4
5from rdflib.graph import Graph
6from rdflib.namespace import RDF, Namespace
7from rdflib.query import Result, ResultParser
8from rdflib.term import Node, Variable
9
10RS = Namespace("http://www.w3.org/2001/sw/DataAccess/tests/result-set#")
11
12
13class RDFResultParser(ResultParser):
14 def parse(self, source: Union[IO, Graph], **kwargs: Any) -> Result:
15 return RDFResult(source, **kwargs)
16
17
18class RDFResult(Result):
19 def __init__(self, source: Union[IO, Graph], **kwargs: Any):
20 if not isinstance(source, Graph):
21 graph = Graph()
22 graph.parse(source, **kwargs)
23 else:
24 graph = source
25
26 rs = graph.value(predicate=RDF.type, object=RS.ResultSet)
27 # there better be only one :)
28
29 if rs is None:
30 type_ = "CONSTRUCT"
31
32 # use a new graph
33 g = Graph()
34 g += graph
35
36 else:
37 askAnswer = graph.value(rs, RS.boolean)
38
39 if askAnswer is not None:
40 type_ = "ASK"
41 else:
42 type_ = "SELECT"
43
44 Result.__init__(self, type_)
45
46 if type_ == "SELECT":
47 # type error: Argument 1 to "Variable" has incompatible type "Node"; expected "str"
48 self.vars = [Variable(v) for v in graph.objects(rs, RS.resultVariable)] # type: ignore[arg-type]
49
50 self.bindings = []
51
52 for s in graph.objects(rs, RS.solution):
53 sol: MutableMapping[Variable, Optional[Node]] = {}
54 for b in graph.objects(s, RS.binding):
55 # type error: Argument 1 to "Variable" has incompatible type "Optional[Node]"; expected "str"
56 sol[Variable(graph.value(b, RS.variable))] = graph.value( # type: ignore[arg-type]
57 b, RS.value
58 )
59 # error: Argument 1 to "append" of "list" has incompatible type "MutableMapping[Variable, Optional[Node]]"; expected "Mapping[Variable, Identifier]"
60 self.bindings.append(sol) # type: ignore[arg-type]
61 elif type_ == "ASK":
62 # type error: Item "Node" of "Optional[Node]" has no attribute "value"
63 # type error: Item "None" of "Optional[Node]" has no attribute "value"
64 self.askAnswer = askAnswer.value # type: ignore[union-attr]
65 # type error: Item "Node" of "Optional[Node]" has no attribute "value"
66 # type error: Item "None" of "Optional[Node]" has no attribute "value"
67 if askAnswer.value is None: # type: ignore[union-attr]
68 raise Exception("Malformed boolean in ask answer!")
69 elif type_ == "CONSTRUCT":
70 self.graph = g