evaluate.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  1. """
  2. These method recursively evaluate the SPARQL Algebra
  3. evalQuery is the entry-point, it will setup context and
  4. return the SPARQLResult object
  5. evalPart is called on each level and will delegate to the right method
  6. A `rdflib.plugins.sparql.sparql.QueryContext` is passed along, keeping
  7. information needed for evaluation
  8. A list of dicts (solution mappings) is returned, apart from GroupBy which may
  9. also return a dict of list of dicts
  10. """
  11. from __future__ import annotations
  12. import collections
  13. import itertools
  14. import re
  15. from typing import (
  16. TYPE_CHECKING,
  17. Any,
  18. Deque,
  19. Dict,
  20. Generator,
  21. Iterable,
  22. List,
  23. Mapping,
  24. Optional,
  25. Tuple,
  26. Union,
  27. )
  28. from urllib.parse import urlencode
  29. from urllib.request import Request, urlopen
  30. from pyparsing import ParseException
  31. from rdflib.graph import Graph
  32. from rdflib.plugins.sparql import CUSTOM_EVALS, parser
  33. from rdflib.plugins.sparql.aggregates import Aggregator
  34. from rdflib.plugins.sparql.evalutils import (
  35. _ebv,
  36. _eval,
  37. _fillTemplate,
  38. _join,
  39. _minus,
  40. _val,
  41. )
  42. from rdflib.plugins.sparql.parserutils import CompValue, value
  43. from rdflib.plugins.sparql.sparql import (
  44. AlreadyBound,
  45. FrozenBindings,
  46. FrozenDict,
  47. Query,
  48. QueryContext,
  49. SPARQLError,
  50. )
  51. from rdflib.term import BNode, Identifier, Literal, URIRef, Variable
  52. if TYPE_CHECKING:
  53. from rdflib.paths import Path
  54. import json
  55. try:
  56. import orjson
  57. _HAS_ORJSON = True
  58. except ImportError:
  59. orjson = None # type: ignore[assignment, unused-ignore]
  60. _HAS_ORJSON = False
  61. _Triple = Tuple[Identifier, Identifier, Identifier]
  62. def evalBGP(
  63. ctx: QueryContext, bgp: List[_Triple]
  64. ) -> Generator[FrozenBindings, None, None]:
  65. """
  66. A basic graph pattern
  67. """
  68. if not bgp:
  69. yield ctx.solution()
  70. return
  71. s, p, o = bgp[0]
  72. _s = ctx[s]
  73. _p = ctx[p]
  74. _o = ctx[o]
  75. # type error: Item "None" of "Optional[Graph]" has no attribute "triples"
  76. # type Argument 1 to "triples" of "Graph" has incompatible type "Tuple[Union[str, Path, None], Union[str, Path, None], Union[str, Path, None]]"; expected "Tuple[Optional[Node], Optional[Node], Optional[Node]]"
  77. for ss, sp, so in ctx.graph.triples((_s, _p, _o)): # type: ignore[union-attr, arg-type]
  78. if None in (_s, _p, _o):
  79. c = ctx.push()
  80. else:
  81. c = ctx
  82. if _s is None:
  83. # type error: Incompatible types in assignment (expression has type "Union[Node, Any]", target has type "Identifier")
  84. c[s] = ss # type: ignore[assignment]
  85. try:
  86. if _p is None:
  87. # type error: Incompatible types in assignment (expression has type "Union[Node, Any]", target has type "Identifier")
  88. c[p] = sp # type: ignore[assignment]
  89. except AlreadyBound:
  90. continue
  91. try:
  92. if _o is None:
  93. # type error: Incompatible types in assignment (expression has type "Union[Node, Any]", target has type "Identifier")
  94. c[o] = so # type: ignore[assignment]
  95. except AlreadyBound:
  96. continue
  97. for x in evalBGP(c, bgp[1:]):
  98. yield x
  99. def evalExtend(
  100. ctx: QueryContext, extend: CompValue
  101. ) -> Generator[FrozenBindings, None, None]:
  102. # TODO: Deal with dict returned from evalPart from GROUP BY
  103. for c in evalPart(ctx, extend.p):
  104. try:
  105. e = _eval(extend.expr, c.forget(ctx, _except=extend._vars))
  106. if isinstance(e, SPARQLError):
  107. raise e
  108. yield c.merge({extend.var: e})
  109. except SPARQLError:
  110. yield c
  111. def evalLazyJoin(
  112. ctx: QueryContext, join: CompValue
  113. ) -> Generator[FrozenBindings, None, None]:
  114. """
  115. A lazy join will push the variables bound
  116. in the first part to the second part,
  117. essentially doing the join implicitly
  118. hopefully evaluating much fewer triples
  119. """
  120. for a in evalPart(ctx, join.p1):
  121. c = ctx.thaw(a)
  122. for b in evalPart(c, join.p2):
  123. yield b.merge(a) # merge, as some bindings may have been forgotten
  124. def evalJoin(ctx: QueryContext, join: CompValue) -> Generator[FrozenDict, None, None]:
  125. # TODO: Deal with dict returned from evalPart from GROUP BY
  126. # only ever for join.p1
  127. if join.lazy:
  128. return evalLazyJoin(ctx, join)
  129. else:
  130. a = evalPart(ctx, join.p1)
  131. b = set(evalPart(ctx, join.p2))
  132. return _join(a, b)
  133. def evalUnion(ctx: QueryContext, union: CompValue) -> List[Any]:
  134. branch1_branch2 = []
  135. for x in evalPart(ctx, union.p1):
  136. branch1_branch2.append(x)
  137. for x in evalPart(ctx, union.p2):
  138. branch1_branch2.append(x)
  139. return branch1_branch2
  140. def evalMinus(ctx: QueryContext, minus: CompValue) -> Generator[FrozenDict, None, None]:
  141. a = evalPart(ctx, minus.p1)
  142. b = set(evalPart(ctx, minus.p2))
  143. return _minus(a, b)
  144. def evalLeftJoin(
  145. ctx: QueryContext, join: CompValue
  146. ) -> Generator[FrozenBindings, None, None]:
  147. # import pdb; pdb.set_trace()
  148. for a in evalPart(ctx, join.p1):
  149. ok = False
  150. c = ctx.thaw(a)
  151. for b in evalPart(c, join.p2):
  152. if _ebv(join.expr, b.forget(ctx)):
  153. ok = True
  154. yield b.merge(a)
  155. if not ok:
  156. # we've cheated, the ctx above may contain
  157. # vars bound outside our scope
  158. # before we yield a solution without the OPTIONAL part
  159. # check that we would have had no OPTIONAL matches
  160. # even without prior bindings...
  161. p1_vars = join.p1._vars
  162. if p1_vars is None or not any(
  163. _ebv(join.expr, b)
  164. for b in evalPart(ctx.thaw(a.remember(p1_vars)), join.p2)
  165. ):
  166. yield a
  167. def evalFilter(
  168. ctx: QueryContext, part: CompValue
  169. ) -> Generator[FrozenBindings, None, None]:
  170. # TODO: Deal with dict returned from evalPart!
  171. for c in evalPart(ctx, part.p):
  172. if _ebv(
  173. part.expr,
  174. c.forget(ctx, _except=part._vars) if not part.no_isolated_scope else c,
  175. ):
  176. yield c
  177. def evalGraph(
  178. ctx: QueryContext, part: CompValue
  179. ) -> Generator[FrozenBindings, None, None]:
  180. if ctx.dataset is None:
  181. raise Exception(
  182. "Non-conjunctive-graph doesn't know about "
  183. + "graphs. Try a query without GRAPH."
  184. )
  185. ctx = ctx.clone()
  186. graph: Union[str, Path, None, Graph] = ctx[part.term]
  187. prev_graph = ctx.graph
  188. if graph is None:
  189. for graph in ctx.dataset.contexts():
  190. # in SPARQL the default graph is NOT a named graph
  191. if graph == ctx.dataset.default_context:
  192. continue
  193. c = ctx.pushGraph(graph)
  194. c = c.push()
  195. graphSolution = [{part.term: graph.identifier}]
  196. for x in _join(evalPart(c, part.p), graphSolution):
  197. x.ctx.graph = prev_graph
  198. yield x
  199. else:
  200. if TYPE_CHECKING:
  201. assert not isinstance(graph, Graph)
  202. # type error: Argument 1 to "get_context" of "ConjunctiveGraph" has incompatible type "Union[str, Path]"; expected "Union[Node, str, None]"
  203. c = ctx.pushGraph(ctx.dataset.get_context(graph)) # type: ignore[arg-type]
  204. for x in evalPart(c, part.p):
  205. x.ctx.graph = prev_graph
  206. yield x
  207. def evalValues(
  208. ctx: QueryContext, part: CompValue
  209. ) -> Generator[FrozenBindings, None, None]:
  210. for r in part.p.res:
  211. c = ctx.push()
  212. try:
  213. for k, v in r.items():
  214. if v != "UNDEF":
  215. c[k] = v
  216. except AlreadyBound:
  217. continue
  218. yield c.solution()
  219. def evalMultiset(ctx: QueryContext, part: CompValue):
  220. if part.p.name == "values":
  221. return evalValues(ctx, part)
  222. return evalPart(ctx, part.p)
  223. def evalPart(ctx: QueryContext, part: CompValue) -> Any:
  224. # try custom evaluation functions
  225. for name, c in CUSTOM_EVALS.items():
  226. try:
  227. return c(ctx, part)
  228. except NotImplementedError:
  229. pass # the given custome-function did not handle this part
  230. if part.name == "BGP":
  231. # Reorder triples patterns by number of bound nodes in the current ctx
  232. # Do patterns with more bound nodes first
  233. triples = sorted(
  234. part.triples, key=lambda t: len([n for n in t if ctx[n] is None])
  235. )
  236. return evalBGP(ctx, triples)
  237. elif part.name == "Filter":
  238. return evalFilter(ctx, part)
  239. elif part.name == "Join":
  240. return evalJoin(ctx, part)
  241. elif part.name == "LeftJoin":
  242. return evalLeftJoin(ctx, part)
  243. elif part.name == "Graph":
  244. return evalGraph(ctx, part)
  245. elif part.name == "Union":
  246. return evalUnion(ctx, part)
  247. elif part.name == "ToMultiSet":
  248. return evalMultiset(ctx, part)
  249. elif part.name == "Extend":
  250. return evalExtend(ctx, part)
  251. elif part.name == "Minus":
  252. return evalMinus(ctx, part)
  253. elif part.name == "Project":
  254. return evalProject(ctx, part)
  255. elif part.name == "Slice":
  256. return evalSlice(ctx, part)
  257. elif part.name == "Distinct":
  258. return evalDistinct(ctx, part)
  259. elif part.name == "Reduced":
  260. return evalReduced(ctx, part)
  261. elif part.name == "OrderBy":
  262. return evalOrderBy(ctx, part)
  263. elif part.name == "Group":
  264. return evalGroup(ctx, part)
  265. elif part.name == "AggregateJoin":
  266. return evalAggregateJoin(ctx, part)
  267. elif part.name == "SelectQuery":
  268. return evalSelectQuery(ctx, part)
  269. elif part.name == "AskQuery":
  270. return evalAskQuery(ctx, part)
  271. elif part.name == "ConstructQuery":
  272. return evalConstructQuery(ctx, part)
  273. elif part.name == "ServiceGraphPattern":
  274. return evalServiceQuery(ctx, part)
  275. elif part.name == "DescribeQuery":
  276. return evalDescribeQuery(ctx, part)
  277. else:
  278. raise Exception("I dont know: %s" % part.name)
  279. def evalServiceQuery(ctx: QueryContext, part: CompValue):
  280. res = {}
  281. match = re.match(
  282. "^service <(.*)>[ \n]*{(.*)}[ \n]*$",
  283. # type error: Argument 2 to "get" of "CompValue" has incompatible type "str"; expected "bool" [arg-type]
  284. part.get("service_string", ""), # type: ignore[arg-type]
  285. re.DOTALL | re.I,
  286. )
  287. if match:
  288. service_url = match.group(1)
  289. service_query = _buildQueryStringForServiceCall(ctx, match.group(2))
  290. query_settings = {"query": service_query, "output": "json"}
  291. headers = {
  292. "accept": "application/sparql-results+json",
  293. "user-agent": "rdflibForAnUser",
  294. }
  295. # GET is easier to cache so prefer that if the query is not to long
  296. if len(service_query) < 600:
  297. response = urlopen(
  298. Request(service_url + "?" + urlencode(query_settings), headers=headers)
  299. )
  300. else:
  301. response = urlopen(
  302. Request(
  303. service_url,
  304. data=urlencode(query_settings).encode(),
  305. headers=headers,
  306. )
  307. )
  308. if response.status == 200:
  309. if _HAS_ORJSON:
  310. json_dict = orjson.loads(response.read())
  311. else:
  312. json_dict = json.loads(response.read())
  313. variables = res["vars_"] = json_dict["head"]["vars"]
  314. # or just return the bindings?
  315. res = json_dict["results"]["bindings"]
  316. if len(res) > 0:
  317. for r in res:
  318. # type error: Argument 2 to "_yieldBindingsFromServiceCallResult" has incompatible type "str"; expected "Dict[str, Dict[str, str]]"
  319. for bound in _yieldBindingsFromServiceCallResult(ctx, r, variables): # type: ignore[arg-type]
  320. yield bound
  321. else:
  322. raise Exception(
  323. "Service: %s responded with code: %s", service_url, response.status
  324. )
  325. """
  326. Build a query string to be used by the service call.
  327. It is supposed to pass in the existing bound solutions.
  328. Re-adds prefixes if added and sets the base.
  329. Wraps it in select if needed.
  330. """
  331. def _buildQueryStringForServiceCall(ctx: QueryContext, service_query: str) -> str:
  332. try:
  333. parser.parseQuery(service_query)
  334. except ParseException:
  335. # This could be because we don't have a select around the service call.
  336. service_query = "SELECT REDUCED * WHERE {" + service_query + "}"
  337. # type error: Item "None" of "Optional[Prologue]" has no attribute "namespace_manager"
  338. for p in ctx.prologue.namespace_manager.store.namespaces(): # type: ignore[union-attr]
  339. service_query = "PREFIX " + p[0] + ":" + p[1].n3() + " " + service_query
  340. # re add the base if one was defined
  341. # type error: Item "None" of "Optional[Prologue]" has no attribute "base"
  342. base = ctx.prologue.base # type: ignore[union-attr]
  343. if base is not None and len(base) > 0:
  344. service_query = "BASE <" + base + "> " + service_query
  345. sol = [v for v in ctx.solution() if isinstance(v, Variable)]
  346. if len(sol) > 0:
  347. variables = " ".join([v.n3() for v in sol])
  348. variables_bound = " ".join([ctx.get(v).n3() for v in sol])
  349. service_query = (
  350. service_query + "VALUES (" + variables + ") {(" + variables_bound + ")}"
  351. )
  352. return service_query
  353. def _yieldBindingsFromServiceCallResult(
  354. ctx: QueryContext, r: Dict[str, Dict[str, str]], variables: List[str]
  355. ) -> Generator[FrozenBindings, None, None]:
  356. res_dict: Dict[Variable, Identifier] = {}
  357. for var in variables:
  358. if var in r and r[var]:
  359. var_binding = r[var]
  360. var_type = var_binding["type"]
  361. if var_type == "uri":
  362. res_dict[Variable(var)] = URIRef(var_binding["value"])
  363. elif var_type == "literal":
  364. res_dict[Variable(var)] = Literal(
  365. var_binding["value"],
  366. datatype=var_binding.get("datatype"),
  367. lang=var_binding.get("xml:lang"),
  368. )
  369. # This is here because of
  370. # https://www.w3.org/TR/2006/NOTE-rdf-sparql-json-res-20061004/#variable-binding-results
  371. elif var_type == "typed-literal":
  372. res_dict[Variable(var)] = Literal(
  373. var_binding["value"], datatype=URIRef(var_binding["datatype"])
  374. )
  375. elif var_type == "bnode":
  376. res_dict[Variable(var)] = BNode(var_binding["value"])
  377. else:
  378. raise ValueError(f"invalid type {var_type!r} for variable {var!r}")
  379. yield FrozenBindings(ctx, res_dict)
  380. def evalGroup(ctx: QueryContext, group: CompValue):
  381. """
  382. http://www.w3.org/TR/sparql11-query/#defn_algGroup
  383. """
  384. # grouping should be implemented by evalAggregateJoin
  385. return evalPart(ctx, group.p)
  386. def evalAggregateJoin(
  387. ctx: QueryContext, agg: CompValue
  388. ) -> Generator[FrozenBindings, None, None]:
  389. # import pdb ; pdb.set_trace()
  390. p = evalPart(ctx, agg.p)
  391. # p is always a Group, we always get a dict back
  392. group_expr = agg.p.expr
  393. res: Dict[Any, Any] = collections.defaultdict(
  394. lambda: Aggregator(aggregations=agg.A)
  395. )
  396. if group_expr is None:
  397. # no grouping, just COUNT in SELECT clause
  398. # get 1 aggregator for counting
  399. aggregator = res[True]
  400. for row in p:
  401. aggregator.update(row)
  402. else:
  403. for row in p:
  404. # determine right group aggregator for row
  405. k = tuple(_eval(e, row, False) for e in group_expr)
  406. res[k].update(row)
  407. # all rows are done; yield aggregated values
  408. for aggregator in res.values():
  409. yield FrozenBindings(ctx, aggregator.get_bindings())
  410. # there were no matches
  411. if len(res) == 0:
  412. yield FrozenBindings(ctx)
  413. def evalOrderBy(
  414. ctx: QueryContext, part: CompValue
  415. ) -> Generator[FrozenBindings, None, None]:
  416. res = evalPart(ctx, part.p)
  417. for e in reversed(part.expr):
  418. reverse = bool(e.order and e.order == "DESC")
  419. res = sorted(
  420. res, key=lambda x: _val(value(x, e.expr, variables=True)), reverse=reverse
  421. )
  422. return res
  423. def evalSlice(ctx: QueryContext, slice: CompValue):
  424. res = evalPart(ctx, slice.p)
  425. return itertools.islice(
  426. res,
  427. slice.start,
  428. slice.start + slice.length if slice.length is not None else None,
  429. )
  430. def evalReduced(
  431. ctx: QueryContext, part: CompValue
  432. ) -> Generator[FrozenBindings, None, None]:
  433. """apply REDUCED to result
  434. REDUCED is not as strict as DISTINCT, but if the incoming rows were sorted
  435. it should produce the same result with limited extra memory and time per
  436. incoming row.
  437. """
  438. # This implementation uses a most recently used strategy and a limited
  439. # buffer size. It relates to a LRU caching algorithm:
  440. # https://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used_.28LRU.29
  441. MAX = 1
  442. # TODO: add configuration or determine "best" size for most use cases
  443. # 0: No reduction
  444. # 1: compare only with the last row, almost no reduction with
  445. # unordered incoming rows
  446. # N: The greater the buffer size the greater the reduction but more
  447. # memory and time are needed
  448. # mixed data structure: set for lookup, deque for append/pop/remove
  449. mru_set = set()
  450. mru_queue: Deque[Any] = collections.deque()
  451. for row in evalPart(ctx, part.p):
  452. if row in mru_set:
  453. # forget last position of row
  454. mru_queue.remove(row)
  455. else:
  456. # row seems to be new
  457. yield row
  458. mru_set.add(row)
  459. if len(mru_set) > MAX:
  460. # drop the least recently used row from buffer
  461. mru_set.remove(mru_queue.pop())
  462. # put row to the front
  463. mru_queue.appendleft(row)
  464. def evalDistinct(
  465. ctx: QueryContext, part: CompValue
  466. ) -> Generator[FrozenBindings, None, None]:
  467. res = evalPart(ctx, part.p)
  468. done = set()
  469. for x in res:
  470. if x not in done:
  471. yield x
  472. done.add(x)
  473. def evalProject(ctx: QueryContext, project: CompValue):
  474. res = evalPart(ctx, project.p)
  475. return (row.project(project.PV) for row in res)
  476. def evalSelectQuery(
  477. ctx: QueryContext, query: CompValue
  478. ) -> Mapping[str, Union[str, List[Variable], Iterable[FrozenDict]]]:
  479. res: Dict[str, Union[str, List[Variable], Iterable[FrozenDict]]] = {}
  480. res["type_"] = "SELECT"
  481. res["bindings"] = evalPart(ctx, query.p)
  482. res["vars_"] = query.PV
  483. return res
  484. def evalAskQuery(ctx: QueryContext, query: CompValue) -> Mapping[str, Union[str, bool]]:
  485. res: Dict[str, Union[bool, str]] = {}
  486. res["type_"] = "ASK"
  487. res["askAnswer"] = False
  488. for x in evalPart(ctx, query.p):
  489. res["askAnswer"] = True
  490. break
  491. return res
  492. def evalConstructQuery(
  493. ctx: QueryContext, query: CompValue
  494. ) -> Mapping[str, Union[str, Graph]]:
  495. template = query.template
  496. if not template:
  497. # a construct-where query
  498. template = query.p.p.triples # query->project->bgp ...
  499. graph = Graph()
  500. for c in evalPart(ctx, query.p):
  501. graph += _fillTemplate(template, c)
  502. res: Dict[str, Union[str, Graph]] = {}
  503. res["type_"] = "CONSTRUCT"
  504. res["graph"] = graph
  505. return res
  506. def evalDescribeQuery(ctx: QueryContext, query) -> Dict[str, Union[str, Graph]]:
  507. # Create a result graph and bind namespaces from the graph being queried
  508. graph = Graph()
  509. # type error: Item "None" of "Optional[Graph]" has no attribute "namespaces"
  510. for pfx, ns in ctx.graph.namespaces(): # type: ignore[union-attr]
  511. graph.bind(pfx, ns)
  512. to_describe = set()
  513. # Explicit IRIs may be provided to a DESCRIBE query.
  514. # If there is a WHERE clause, explicit IRIs may be provided in
  515. # addition to projected variables. Find those explicit IRIs and
  516. # prepare to describe them.
  517. for iri in query.PV:
  518. if isinstance(iri, URIRef):
  519. to_describe.add(iri)
  520. # If there is a WHERE clause, evaluate it then find the unique set of
  521. # resources to describe across all bindings and projected variables
  522. if query.p is not None:
  523. bindings = evalPart(ctx, query.p)
  524. to_describe.update(*(set(binding.values()) for binding in bindings))
  525. # Get a CBD for all resources identified to describe
  526. for resource in to_describe:
  527. # type error: Item "None" of "Optional[Graph]" has no attribute "cbd"
  528. ctx.graph.cbd(resource, target_graph=graph) # type: ignore[union-attr]
  529. res: Dict[str, Union[str, Graph]] = {}
  530. res["type_"] = "DESCRIBE"
  531. res["graph"] = graph
  532. return res
  533. def evalQuery(
  534. graph: Graph,
  535. query: Query,
  536. initBindings: Optional[Mapping[str, Identifier]] = None,
  537. base: Optional[str] = None,
  538. ) -> Mapping[Any, Any]:
  539. """Evaluate a SPARQL query against a graph.
  540. !!! warning "Caution"
  541. This method can access indirectly requested network endpoints, for
  542. example, query processing will attempt to access network endpoints
  543. specified in `SERVICE` directives.
  544. When processing untrusted or potentially malicious queries, measures
  545. should be taken to restrict network and file access.
  546. For information on available security measures, see the RDFLib
  547. [Security Considerations](../security_considerations.md)
  548. documentation.
  549. """
  550. main = query.algebra
  551. initBindings = dict((Variable(k), v) for k, v in (initBindings or {}).items())
  552. ctx = QueryContext(
  553. graph, initBindings=initBindings, datasetClause=main.datasetClause
  554. )
  555. ctx.prologue = query.prologue
  556. return evalPart(ctx, main)