diff --git a/rdflib/plugins/sparql/evaluate.py b/rdflib/plugins/sparql/evaluate.py index 496bc8721..f5fd86ed2 100644 --- a/rdflib/plugins/sparql/evaluate.py +++ b/rdflib/plugins/sparql/evaluate.py @@ -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(): @@ -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 diff --git a/test/test_sparql.py b/test/test_sparql.py index 8da1f799d..ae11226c5 100644 --- a/test/test_sparql.py +++ b/test/test_sparql.py @@ -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 @@ -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