Source code

Download source archive ↓

src/rdflib/plugins/sparql/evalutils.py

1from __future__ import annotations
2
3import collections
4from typing import (
5    Any,
6    DefaultDict,
7    Generator,
8    Iterable,
9    Mapping,
10    Set,
11    Tuple,
12    TypeVar,
13    Union,
14    overload,
15)
16
17from rdflib.plugins.sparql.operators import EBV
18from rdflib.plugins.sparql.parserutils import CompValue, Expr
19from rdflib.plugins.sparql.sparql import (
20    FrozenBindings,
21    FrozenDict,
22    NotBoundError,
23    QueryContext,
24    SPARQLError,
25)
26from rdflib.term import BNode, Identifier, Literal, URIRef, Variable
27
28_ContextType = Union[FrozenBindings, QueryContext]
29_FrozenDictT = TypeVar("_FrozenDictT", bound=FrozenDict)
30
31
32def _diff(
33    a: Iterable[_FrozenDictT], b: Iterable[_FrozenDictT], expr
34) -> Set[_FrozenDictT]:
35    res = set()
36
37    for x in a:
38        if all(not x.compatible(y) or not _ebv(expr, x.merge(y)) for y in b):
39            res.add(x)
40
41    return res
42
43
44def _minus(
45    a: Iterable[_FrozenDictT], b: Iterable[_FrozenDictT]
46) -> Generator[_FrozenDictT, None, None]:
47    for x in a:
48        if all((not x.compatible(y)) or x.disjointDomain(y) for y in b):
49            yield x
50
51
52@overload
53def _join(
54    a: Iterable[FrozenBindings], b: Iterable[Mapping[Identifier, Identifier]]
55) -> Generator[FrozenBindings, None, None]: ...
56
57
58@overload
59def _join(
60    a: Iterable[FrozenDict], b: Iterable[Mapping[Identifier, Identifier]]
61) -> Generator[FrozenDict, None, None]: ...
62
63
64def _join(
65    a: Iterable[FrozenDict], b: Iterable[Mapping[Identifier, Identifier]]
66) -> Generator[FrozenDict, None, None]:
67    for x in a:
68        for y in b:
69            if x.compatible(y):
70                yield x.merge(y)
71
72
73def _ebv(expr: Union[Literal, Variable, Expr], ctx: FrozenDict) -> bool:
74    """
75    Return true/false for the given expr
76    Either the expr is itself true/false
77    or evaluates to something, with the given ctx
78
79    an error is false
80    """
81
82    try:
83        return EBV(expr)
84    except SPARQLError:
85        pass
86    if isinstance(expr, Expr):
87        try:
88            return EBV(expr.eval(ctx))
89        except SPARQLError:
90            return False  # filter error == False
91    # type error: Subclass of "Literal" and "CompValue" cannot exist: would have incompatible method signatures
92    elif isinstance(expr, CompValue):  # type: ignore[unreachable]
93        raise Exception("Weird - filter got a CompValue without evalfn! %r" % expr)
94    elif isinstance(expr, Variable):
95        try:
96            return EBV(ctx[expr])
97        except:  # noqa: E722
98            return False
99    return False
100
101
102@overload
103def _eval(
104    expr: Union[Literal, URIRef],
105    ctx: FrozenBindings,
106    raise_not_bound_error: bool = ...,
107) -> Union[Literal, URIRef]: ...
108
109
110@overload
111def _eval(
112    expr: Union[Variable, Expr],
113    ctx: FrozenBindings,
114    raise_not_bound_error: bool = ...,
115) -> Union[Any, SPARQLError]: ...
116
117
118def _eval(
119    expr: Union[Literal, URIRef, Variable, Expr],
120    ctx: FrozenBindings,
121    raise_not_bound_error: bool = True,
122) -> Any:
123    if isinstance(expr, (Literal, URIRef)):
124        return expr
125    if isinstance(expr, Expr):
126        return expr.eval(ctx)
127    elif isinstance(expr, Variable):
128        try:
129            return ctx[expr]
130        except KeyError:
131            if raise_not_bound_error:
132                raise NotBoundError("Variable %s is not bound" % expr)
133            else:
134                return None
135    elif isinstance(expr, CompValue):  # type: ignore[unreachable]
136        raise Exception("Weird - _eval got a CompValue without evalfn! %r" % expr)
137    else:
138        raise Exception("Cannot eval thing: %s (%s)" % (expr, type(expr)))
139
140
141def _filter(
142    a: Iterable[FrozenDict], expr: Union[Literal, Variable, Expr]
143) -> Generator[FrozenDict, None, None]:
144    for c in a:
145        if _ebv(expr, c):
146            yield c
147
148
149def _fillTemplate(
150    template: Iterable[Tuple[Identifier, Identifier, Identifier]],
151    solution: _ContextType,
152) -> Generator[Tuple[Identifier, Identifier, Identifier], None, None]:
153    """
154    For construct/deleteWhere and friends
155
156    Fill a triple template with instantiated variables
157    """
158
159    bnodeMap: DefaultDict[BNode, BNode] = collections.defaultdict(BNode)
160    for t in template:
161        s, p, o = t
162
163        _s = solution.get(s)
164        _p = solution.get(p)
165        _o = solution.get(o)
166
167        # instantiate new bnodes for each solution
168        _s, _p, _o = [
169            bnodeMap[x] if isinstance(x, BNode) else y for x, y in zip(t, (_s, _p, _o))
170        ]
171
172        if _s is not None and _p is not None and _o is not None:
173            yield (_s, _p, _o)
174
175
176_ValueT = TypeVar("_ValueT", Variable, BNode, URIRef, Literal)
177
178
179def _val(v: _ValueT) -> Tuple[int, _ValueT]:
180    """utilitity for ordering things"""
181    if isinstance(v, Variable):
182        return (0, v)
183    elif isinstance(v, BNode):
184        return (1, v)
185    elif isinstance(v, URIRef):
186        return (2, v)
187    elif isinstance(v, Literal):
188        return (3, v)