Source code

Download source archive ↓

src/rdflib/plugins/sparql/processor.py

1"""
2Code for tying SPARQL Engine into RDFLib
3
4These should be automatically registered with RDFLib
5"""
6
7from __future__ import annotations
8
9from typing import Any, Mapping, Optional, Union
10
11from rdflib.graph import Graph
12from rdflib.plugins.sparql.algebra import translateQuery, translateUpdate
13from rdflib.plugins.sparql.evaluate import evalQuery
14from rdflib.plugins.sparql.parser import parseQuery, parseUpdate
15from rdflib.plugins.sparql.sparql import Query, Update
16from rdflib.plugins.sparql.update import evalUpdate
17from rdflib.query import Processor, Result, UpdateProcessor
18from rdflib.term import Identifier
19
20
21def prepareQuery(
22    queryString: str,
23    initNs: Optional[Mapping[str, Any]] = None,
24    base: Optional[str] = None,
25) -> Query:
26    """
27    Parse and translate a SPARQL Query
28    """
29    if initNs is None:
30        initNs = {}
31    ret = translateQuery(parseQuery(queryString), base, initNs)
32    ret._original_args = (queryString, initNs, base)
33    return ret
34
35
36def prepareUpdate(
37    updateString: str,
38    initNs: Optional[Mapping[str, Any]] = None,
39    base: Optional[str] = None,
40) -> Update:
41    """
42    Parse and translate a SPARQL Update
43    """
44    if initNs is None:
45        initNs = {}
46    ret = translateUpdate(parseUpdate(updateString), base, initNs)
47    ret._original_args = (updateString, initNs, base)
48    return ret
49
50
51def processUpdate(
52    graph: Graph,
53    updateString: str,
54    initBindings: Optional[Mapping[str, Identifier]] = None,
55    initNs: Optional[Mapping[str, Any]] = None,
56    base: Optional[str] = None,
57) -> None:
58    """
59    Process a SPARQL Update Request
60    returns Nothing on success or raises Exceptions on error
61    """
62    evalUpdate(
63        graph, translateUpdate(parseUpdate(updateString), base, initNs), initBindings
64    )
65
66
67class SPARQLResult(Result):
68    def __init__(self, res: Mapping[str, Any]):
69        Result.__init__(self, res["type_"])
70        self.vars = res.get("vars_")
71        # type error: Incompatible types in assignment (expression has type "Optional[Any]", variable has type "MutableSequence[Mapping[Variable, Identifier]]")
72        self.bindings = res.get("bindings")  # type: ignore[assignment]
73        self.askAnswer = res.get("askAnswer")
74        self.graph = res.get("graph")
75
76
77class SPARQLUpdateProcessor(UpdateProcessor):
78    def __init__(self, graph):
79        self.graph = graph
80
81    def update(
82        self,
83        strOrQuery: Union[str, Update],
84        initBindings: Optional[Mapping[str, Identifier]] = None,
85        initNs: Optional[Mapping[str, Any]] = None,
86    ) -> None:
87        """
88        !!! warning "Caution"
89
90            This method can access indirectly requested network endpoints, for
91            example, query processing will attempt to access network endpoints
92            specified in `SERVICE` directives.
93
94            When processing untrusted or potentially malicious queries, measures
95            should be taken to restrict network and file access.
96
97            For information on available security measures, see the RDFLib
98            [Security Considerations](../security_considerations.md)
99            documentation.
100        """
101
102        if isinstance(strOrQuery, str):
103            strOrQuery = translateUpdate(parseUpdate(strOrQuery), initNs=initNs)
104
105        return evalUpdate(self.graph, strOrQuery, initBindings)
106
107
108class SPARQLProcessor(Processor):
109    def __init__(self, graph):
110        self.graph = graph
111
112    # NOTE on type error: this is because the super type constructor does not
113    # accept base argument and thie position of the DEBUG argument is
114    # different.
115    # type error: Signature of "query" incompatible with supertype "Processor"
116    def query(  # type: ignore[override]
117        self,
118        strOrQuery: Union[str, Query],
119        initBindings: Optional[Mapping[str, Identifier]] = None,
120        initNs: Optional[Mapping[str, Any]] = None,
121        base: Optional[str] = None,
122        DEBUG: bool = False,
123    ) -> Mapping[str, Any]:
124        """
125        Evaluate a query with the given initial bindings, and initial
126        namespaces. The given base is used to resolve relative URIs in
127        the query and will be overridden by any BASE given in the query.
128
129        !!! warning "Caution"
130
131            This method can access indirectly requested network endpoints, for
132            example, query processing will attempt to access network endpoints
133            specified in `SERVICE` directives.
134
135            When processing untrusted or potentially malicious queries, measures
136            should be taken to restrict network and file access.
137
138            For information on available security measures, see the RDFLib
139            [Security Considerations](../security_considerations.md)
140            documentation.
141        """
142
143        if isinstance(strOrQuery, str):
144            strOrQuery = translateQuery(parseQuery(strOrQuery), base, initNs)
145
146        return evalQuery(self.graph, strOrQuery, initBindings, base)