Skip to content

Commit 756d933

Browse files
committed
sparqls optionals clause can now bind variables. with test. issue 2957
1 parent 34751ac commit 756d933

File tree

2 files changed

+38
-1
lines changed

2 files changed

+38
-1
lines changed

rdflib/plugins/sparql/evaluate.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -180,7 +180,7 @@ def evalLeftJoin(
180180
for b in evalPart(c, join.p2):
181181
if _ebv(join.expr, b.forget(ctx)):
182182
ok = True
183-
yield b
183+
yield b.merge(a)
184184
if not ok:
185185
# we've cheated, the ctx above may contain
186186
# vars bound outside our scope

test/test_sparql/test_optional.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
from rdflib import Graph, Literal, URIRef, Variable
2+
3+
4+
def test_binding_with_optional_clause() -> None:
5+
"""
6+
Optional clauses should bind variables if feasible.
7+
8+
See https://github.com/RDFLib/rdflib/issues/2957
9+
"""
10+
g = Graph().parse(
11+
data="""
12+
prefix ex: <https://www.example.org/>
13+
ex:document ex:subject "Nice cars" .
14+
ex:someCar ex:type "Car" .
15+
"""
16+
)
17+
result = g.query(
18+
"""prefix ex: <https://www.example.org/>
19+
select ?subject ?car
20+
where {
21+
$this ex:subject ?subject.
22+
optional
23+
{
24+
# an offending subselect clause
25+
select ?car
26+
where {
27+
?car ex:type "Car".
28+
}
29+
}
30+
}"""
31+
)
32+
assert len(result.bindings) == 1
33+
(first,) = result.bindings
34+
assert first.get(Variable("car")) == URIRef("https://www.example.org/someCar")
35+
assert first.get(Variable("subject")) == Literal(
36+
"Nice cars"
37+
), "optional clause didnt bind"

0 commit comments

Comments
 (0)