Skip to content

Commit

Permalink
Merge pull request #1206 from sa-bpelakh/graph-filter-query
Browse files Browse the repository at this point in the history
Reset graph on exit from context
  • Loading branch information
nicholascar authored Dec 27, 2020
2 parents 7e2c8e3 + 80fa7da commit 009dc24
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
3 changes: 3 additions & 0 deletions rdflib/plugins/sparql/evaluate.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,7 @@ def evalGraph(ctx, part):

ctx = ctx.clone()
graph = ctx[part.term]
prev_graph = ctx.graph
if graph is None:

for graph in ctx.dataset.contexts():
Expand All @@ -199,11 +200,13 @@ def evalGraph(ctx, part):
c = c.push()
graphSolution = [{part.term: graph.identifier}]
for x in _join(evalPart(c, part.p), graphSolution):
x.ctx.graph = prev_graph
yield x

else:
c = ctx.pushGraph(ctx.dataset.get_context(graph))
for x in evalPart(c, part.p):
x.ctx.graph = prev_graph
yield x


Expand Down
34 changes: 33 additions & 1 deletion test/test_sparql.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from rdflib import Graph, URIRef, Literal, BNode
from rdflib import Graph, URIRef, Literal, BNode, ConjunctiveGraph
from rdflib.namespace import Namespace, RDF, RDFS
from rdflib.plugins.sparql import prepareQuery
from rdflib.compare import isomorphic

Expand Down Expand Up @@ -112,6 +113,37 @@ def test_sparql_update_with_bnode_serialize_parse():
assert not raised


def test_named_filter_graph_query():
g = ConjunctiveGraph()
g.namespace_manager.bind('rdf', RDF)
g.namespace_manager.bind('rdfs', RDFS)
ex = Namespace('https://ex.com/')
g.namespace_manager.bind('ex', ex)
g.get_context(ex.g1).parse(format="turtle", data=f"""
PREFIX ex: <{str(ex)}>
PREFIX rdfs: <{str(RDFS)}>
ex:Boris rdfs:label "Boris" .
ex:Susan rdfs:label "Susan" .
""")
g.get_context(ex.g2).parse(format="turtle", data=f"""
PREFIX ex: <{str(ex)}>
ex:Boris a ex:Person .
""")

assert list(g.query("SELECT ?l WHERE { GRAPH ex:g1 { ?a rdfs:label ?l } ?a a ?type }",
initNs={'ex': ex})) == [(Literal('Boris'),)]
assert list(g.query("SELECT ?l WHERE { GRAPH ex:g1 { ?a rdfs:label ?l } FILTER EXISTS { ?a a ?type }}",
initNs={'ex': ex})) == [(Literal('Boris'),)]
assert list(g.query("SELECT ?l WHERE { GRAPH ex:g1 { ?a rdfs:label ?l } FILTER NOT EXISTS { ?a a ?type }}",
initNs={'ex': ex})) == [(Literal('Susan'),)]
assert list(g.query("SELECT ?l WHERE { GRAPH ?g { ?a rdfs:label ?l } ?a a ?type }",
initNs={'ex': ex})) == [(Literal('Boris'),)]
assert list(g.query("SELECT ?l WHERE { GRAPH ?g { ?a rdfs:label ?l } FILTER EXISTS { ?a a ?type }}",
initNs={'ex': ex})) == [(Literal('Boris'),)]
assert list(g.query("SELECT ?l WHERE { GRAPH ?g { ?a rdfs:label ?l } FILTER NOT EXISTS { ?a a ?type }}",
initNs={'ex': ex})) == [(Literal('Susan'),)]


if __name__ == "__main__":
import nose

Expand Down

0 comments on commit 009dc24

Please sign in to comment.