sparql.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. from __future__ import annotations
  2. import collections
  3. import datetime
  4. import itertools
  5. import typing as t
  6. from collections.abc import Mapping, MutableMapping
  7. from typing import (
  8. TYPE_CHECKING,
  9. Any,
  10. Container,
  11. Dict,
  12. Generator,
  13. Iterable,
  14. List,
  15. Optional,
  16. Tuple,
  17. TypeVar,
  18. Union,
  19. )
  20. import rdflib.plugins.sparql
  21. from rdflib.graph import ConjunctiveGraph, Dataset, Graph
  22. from rdflib.namespace import NamespaceManager
  23. from rdflib.plugins.sparql.parserutils import CompValue
  24. from rdflib.term import BNode, Identifier, Literal, Node, URIRef, Variable
  25. if TYPE_CHECKING:
  26. from rdflib.paths import Path
  27. _AnyT = TypeVar("_AnyT")
  28. class SPARQLError(Exception):
  29. def __init__(self, msg: Optional[str] = None):
  30. Exception.__init__(self, msg)
  31. class NotBoundError(SPARQLError):
  32. def __init__(self, msg: Optional[str] = None):
  33. SPARQLError.__init__(self, msg)
  34. class AlreadyBound(SPARQLError): # noqa: N818
  35. """Raised when trying to bind a variable that is already bound!"""
  36. def __init__(self):
  37. SPARQLError.__init__(self)
  38. class SPARQLTypeError(SPARQLError):
  39. def __init__(self, msg: Optional[str]):
  40. SPARQLError.__init__(self, msg)
  41. class Bindings(MutableMapping):
  42. """
  43. A single level of a stack of variable-value bindings.
  44. Each dict keeps a reference to the dict below it,
  45. any failed lookup is propegated back
  46. In python 3.3 this could be a collections.ChainMap
  47. """
  48. def __init__(self, outer: Optional[Bindings] = None, d=[]):
  49. self._d: Dict[str, str] = dict(d)
  50. self.outer = outer
  51. def __getitem__(self, key: str) -> str:
  52. if key in self._d:
  53. return self._d[key]
  54. if not self.outer:
  55. raise KeyError()
  56. return self.outer[key]
  57. def __contains__(self, key: Any) -> bool:
  58. try:
  59. self[key]
  60. return True
  61. except KeyError:
  62. return False
  63. def __setitem__(self, key: str, value: Any) -> None:
  64. self._d[key] = value
  65. def __delitem__(self, key: str) -> None:
  66. raise Exception("DelItem is not implemented!")
  67. def __len__(self) -> int:
  68. i = 0
  69. d: Optional[Bindings] = self
  70. while d is not None:
  71. i += len(d._d)
  72. d = d.outer
  73. return i
  74. def __iter__(self) -> Generator[str, None, None]:
  75. d: Optional[Bindings] = self
  76. while d is not None:
  77. yield from d._d
  78. d = d.outer
  79. def __str__(self) -> str:
  80. # type error: Generator has incompatible item type "Tuple[Any, str]"; expected "str"
  81. return "Bindings({" + ", ".join((k, self[k]) for k in self) + "})" # type: ignore[misc]
  82. def __repr__(self) -> str:
  83. return str(self)
  84. class FrozenDict(Mapping):
  85. """
  86. An immutable hashable dict
  87. Taken from http://stackoverflow.com/a/2704866/81121
  88. """
  89. def __init__(self, *args: Any, **kwargs: Any):
  90. self._d: Dict[Identifier, Identifier] = dict(*args, **kwargs)
  91. self._hash: Optional[int] = None
  92. def __iter__(self):
  93. return iter(self._d)
  94. def __len__(self) -> int:
  95. return len(self._d)
  96. def __getitem__(self, key: Identifier) -> Identifier:
  97. return self._d[key]
  98. def __hash__(self) -> int:
  99. # It would have been simpler and maybe more obvious to
  100. # use hash(tuple(sorted(self._d.items()))) from this discussion
  101. # so far, but this solution is O(n). I don't know what kind of
  102. # n we are going to run into, but sometimes it's hard to resist the
  103. # urge to optimize when it will gain improved algorithmic performance.
  104. if self._hash is None:
  105. self._hash = 0
  106. for key, value in self.items():
  107. self._hash ^= hash(key)
  108. self._hash ^= hash(value)
  109. return self._hash
  110. def project(self, vars: Container[Variable]) -> FrozenDict:
  111. return FrozenDict(x for x in self.items() if x[0] in vars)
  112. def disjointDomain(self, other: t.Mapping[Identifier, Identifier]) -> bool:
  113. return not bool(set(self).intersection(other))
  114. def compatible(self, other: t.Mapping[Identifier, Identifier]) -> bool:
  115. for k in self:
  116. try:
  117. if self[k] != other[k]:
  118. return False
  119. except KeyError:
  120. pass
  121. return True
  122. def merge(self, other: t.Mapping[Identifier, Identifier]) -> FrozenDict:
  123. res = FrozenDict(itertools.chain(self.items(), other.items()))
  124. return res
  125. def __str__(self) -> str:
  126. return str(self._d)
  127. def __repr__(self) -> str:
  128. return repr(self._d)
  129. class FrozenBindings(FrozenDict):
  130. def __init__(self, ctx: QueryContext, *args, **kwargs):
  131. FrozenDict.__init__(self, *args, **kwargs)
  132. self.ctx = ctx
  133. def __getitem__(self, key: Union[Identifier, str]) -> Identifier:
  134. if not isinstance(key, Node):
  135. key = Variable(key)
  136. if not isinstance(key, (BNode, Variable)):
  137. return key
  138. if key not in self._d:
  139. # type error: Value of type "Optional[Dict[Variable, Identifier]]" is not indexable
  140. # type error: Invalid index type "Union[BNode, Variable]" for "Optional[Dict[Variable, Identifier]]"; expected type "Variable"
  141. return self.ctx.initBindings[key] # type: ignore[index]
  142. else:
  143. return self._d[key]
  144. def project(self, vars: Container[Variable]) -> FrozenBindings:
  145. return FrozenBindings(self.ctx, (x for x in self.items() if x[0] in vars))
  146. def merge(self, other: t.Mapping[Identifier, Identifier]) -> FrozenBindings:
  147. res = FrozenBindings(self.ctx, itertools.chain(self.items(), other.items()))
  148. return res
  149. @property
  150. def now(self) -> datetime.datetime:
  151. return self.ctx.now
  152. @property
  153. def bnodes(self) -> t.Mapping[Identifier, BNode]:
  154. return self.ctx.bnodes
  155. @property
  156. def prologue(self) -> Optional[Prologue]:
  157. return self.ctx.prologue
  158. def forget(
  159. self, before: QueryContext, _except: Optional[Container[Variable]] = None
  160. ) -> FrozenBindings:
  161. """
  162. return a frozen dict only of bindings made in self
  163. since before
  164. """
  165. if not _except:
  166. _except = []
  167. # bindings from initBindings are newer forgotten
  168. return FrozenBindings(
  169. self.ctx,
  170. (
  171. x
  172. for x in self.items()
  173. if (
  174. x[0] in _except
  175. # type error: Unsupported right operand type for in ("Optional[Dict[Variable, Identifier]]")
  176. or x[0] in self.ctx.initBindings # type: ignore[operator]
  177. or before[x[0]] is None
  178. )
  179. ),
  180. )
  181. def remember(self, these) -> FrozenBindings:
  182. """
  183. return a frozen dict only of bindings in these
  184. """
  185. return FrozenBindings(self.ctx, (x for x in self.items() if x[0] in these))
  186. class QueryContext:
  187. """
  188. Query context - passed along when evaluating the query
  189. """
  190. def __init__(
  191. self,
  192. graph: Optional[Graph] = None,
  193. bindings: Optional[Union[Bindings, FrozenBindings, List[Any]]] = None,
  194. initBindings: Optional[Mapping[str, Identifier]] = None,
  195. datasetClause=None,
  196. ):
  197. self.initBindings = initBindings
  198. self.bindings = Bindings(d=bindings or [])
  199. if initBindings:
  200. self.bindings.update(initBindings)
  201. self.graph: Optional[Graph]
  202. self._dataset: Optional[Union[Dataset, ConjunctiveGraph]]
  203. if isinstance(graph, (Dataset, ConjunctiveGraph)):
  204. if datasetClause:
  205. self._dataset = Dataset()
  206. self.graph = Graph()
  207. for d in datasetClause:
  208. if d.default:
  209. from_graph = graph.get_context(d.default)
  210. self.graph += from_graph
  211. if not from_graph:
  212. self.load(d.default, default=True)
  213. elif d.named:
  214. namedGraphs = Graph(
  215. store=self.dataset.store, identifier=d.named
  216. )
  217. from_named_graphs = graph.get_context(d.named)
  218. namedGraphs += from_named_graphs
  219. if not from_named_graphs:
  220. self.load(d.named, default=False)
  221. else:
  222. self._dataset = graph
  223. if rdflib.plugins.sparql.SPARQL_DEFAULT_GRAPH_UNION:
  224. self.graph = self.dataset
  225. else:
  226. self.graph = self.dataset.default_context
  227. else:
  228. self._dataset = None
  229. self.graph = graph
  230. self.prologue: Optional[Prologue] = None
  231. self._now: Optional[datetime.datetime] = None
  232. self.bnodes: t.MutableMapping[Identifier, BNode] = collections.defaultdict(
  233. BNode
  234. )
  235. @property
  236. def now(self) -> datetime.datetime:
  237. if self._now is None:
  238. self._now = datetime.datetime.now(datetime.timezone.utc)
  239. return self._now
  240. def clone(
  241. self, bindings: Optional[Union[FrozenBindings, Bindings, List[Any]]] = None
  242. ) -> QueryContext:
  243. r = QueryContext(
  244. self._dataset if self._dataset is not None else self.graph,
  245. bindings or self.bindings,
  246. initBindings=self.initBindings,
  247. )
  248. r.prologue = self.prologue
  249. r.graph = self.graph
  250. r.bnodes = self.bnodes
  251. return r
  252. @property
  253. def dataset(self) -> ConjunctiveGraph:
  254. """ "current dataset"""
  255. if self._dataset is None:
  256. raise Exception(
  257. "You performed a query operation requiring "
  258. + "a dataset (i.e. ConjunctiveGraph), but "
  259. + "operating currently on a single graph."
  260. )
  261. return self._dataset
  262. def load(
  263. self,
  264. source: URIRef,
  265. default: bool = False,
  266. into: Optional[Identifier] = None,
  267. **kwargs: Any,
  268. ) -> None:
  269. """
  270. Load data from the source into the query context's.
  271. Args:
  272. source: The source to load from.
  273. default: If `True`, triples from the source will be added
  274. to the default graph, otherwise it will be loaded into a
  275. graph with `source` URI as its name.
  276. into: The name of the graph to load the data into. If
  277. `None`, the source URI will be used as as the name of the
  278. graph.
  279. **kwargs: Keyword arguments to pass to
  280. [`parse`][rdflib.graph.Graph.parse].
  281. """
  282. def _load(graph, source):
  283. try:
  284. return graph.parse(source, format="turtle", **kwargs)
  285. except Exception:
  286. pass
  287. try:
  288. return graph.parse(source, format="xml", **kwargs)
  289. except Exception:
  290. pass
  291. try:
  292. return graph.parse(source, format="n3", **kwargs)
  293. except Exception:
  294. pass
  295. try:
  296. return graph.parse(source, format="nt", **kwargs)
  297. except Exception:
  298. raise Exception(
  299. "Could not load %s as either RDF/XML, N3 or NTriples" % source
  300. )
  301. if not rdflib.plugins.sparql.SPARQL_LOAD_GRAPHS:
  302. # we are not loading - if we already know the graph
  303. # being "loaded", just add it to the default-graph
  304. if default:
  305. # Unsupported left operand type for + ("None")
  306. self.graph += self.dataset.get_context(source) # type: ignore[operator]
  307. else:
  308. if default:
  309. _load(self.graph, source)
  310. else:
  311. if into is None:
  312. into = source
  313. _load(self.dataset.get_context(into), source)
  314. def __getitem__(self, key: Union[str, Path]) -> Optional[Union[str, Path]]:
  315. # in SPARQL BNodes are just labels
  316. if not isinstance(key, (BNode, Variable)):
  317. return key
  318. try:
  319. return self.bindings[key]
  320. except KeyError:
  321. return None
  322. def get(self, key: str, default: Optional[Any] = None) -> Any:
  323. try:
  324. return self[key]
  325. except KeyError:
  326. return default
  327. def solution(self, vars: Optional[Iterable[Variable]] = None) -> FrozenBindings:
  328. """
  329. Return a static copy of the current variable bindings as dict
  330. """
  331. if vars:
  332. return FrozenBindings(
  333. self, ((k, v) for k, v in self.bindings.items() if k in vars)
  334. )
  335. else:
  336. return FrozenBindings(self, self.bindings.items())
  337. def __setitem__(self, key: str, value: str) -> None:
  338. if key in self.bindings and self.bindings[key] != value:
  339. raise AlreadyBound()
  340. self.bindings[key] = value
  341. def pushGraph(self, graph: Optional[Graph]) -> QueryContext:
  342. r = self.clone()
  343. r.graph = graph
  344. return r
  345. def push(self) -> QueryContext:
  346. r = self.clone(Bindings(self.bindings))
  347. return r
  348. def clean(self) -> QueryContext:
  349. return self.clone([])
  350. def thaw(self, frozenbindings: FrozenBindings) -> QueryContext:
  351. """
  352. Create a new read/write query context from the given solution
  353. """
  354. c = self.clone(frozenbindings)
  355. return c
  356. class Prologue:
  357. """
  358. A class for holding prefixing bindings and base URI information
  359. """
  360. def __init__(self) -> None:
  361. self.base: Optional[str] = None
  362. self.namespace_manager = NamespaceManager(Graph()) # ns man needs a store
  363. def resolvePName(self, prefix: Optional[str], localname: Optional[str]) -> URIRef:
  364. ns = self.namespace_manager.store.namespace(prefix or "")
  365. if ns is None:
  366. raise Exception("Unknown namespace prefix : %s" % prefix)
  367. return URIRef(ns + (localname or ""))
  368. def bind(self, prefix: Optional[str], uri: Any) -> None:
  369. self.namespace_manager.bind(prefix, uri, replace=True)
  370. def absolutize(
  371. self, iri: Optional[Union[CompValue, str]]
  372. ) -> Optional[Union[CompValue, str]]:
  373. """
  374. Apply BASE / PREFIXes to URIs
  375. (and to datatypes in Literals)
  376. TODO: Move resolving URIs to pre-processing
  377. """
  378. if isinstance(iri, CompValue):
  379. if iri.name == "pname":
  380. return self.resolvePName(iri.prefix, iri.localname)
  381. if iri.name == "literal":
  382. # type error: Argument "datatype" to "Literal" has incompatible type "Union[CompValue, Identifier, None]"; expected "Optional[str]"
  383. return Literal(
  384. iri.string, lang=iri.lang, datatype=self.absolutize(iri.datatype) # type: ignore[arg-type]
  385. )
  386. elif isinstance(iri, URIRef) and not ":" in iri: # noqa: E713
  387. return URIRef(iri, base=self.base)
  388. return iri
  389. class Query:
  390. """
  391. A parsed and translated query
  392. """
  393. def __init__(self, prologue: Prologue, algebra: CompValue):
  394. self.prologue = prologue
  395. self.algebra = algebra
  396. self._original_args: Tuple[str, Mapping[str, str], Optional[str]]
  397. class Update:
  398. """
  399. A parsed and translated update
  400. """
  401. def __init__(self, prologue: Prologue, algebra: List[CompValue]):
  402. self.prologue = prologue
  403. self.algebra = algebra
  404. self._original_args: Tuple[str, Mapping[str, str], Optional[str]]