Пример #1
0
def evalQuery(graph, query, initBindings, base=None):

    initBindings = dict( ( Variable(k),v ) for k,v in iteritems(initBindings) )

    ctx = QueryContext(graph, initBindings=initBindings)

    ctx.prologue = query.prologue
    main = query.algebra

    if main.datasetClause:
        if ctx.dataset is None:
            raise Exception(
                "Non-conjunctive-graph doesn't know about " +
                "graphs! Try a query without FROM (NAMED).")

        ctx = ctx.clone()  # or push/pop?

        firstDefault = False
        for d in main.datasetClause:
            if d.default:

                if firstDefault:
                    # replace current default graph
                    dg = ctx.dataset.get_context(BNode())
                    ctx = ctx.pushGraph(dg)
                    firstDefault = True

                ctx.load(d.default, default=True)

            elif d.named:
                g = d.named
                ctx.load(g, default=False)

    return evalPart(ctx, main)
Пример #2
0
 def _evaluate(self, bindings):
     """Evaluate the FILTER expression with a set mappings"""
     d = {Variable(key[1:]): to_rdflib_term(value) for key, value in bindings.items()}
     b = Bindings(d=d)
     context = QueryContext(bindings=b)
     context.prologue = self._prologue
     return self._compiled_expression.eval(context)
Пример #3
0
def evalQuery(graph, query, initBindings, base=None):

    initBindings = dict((Variable(k), v) for k, v in iteritems(initBindings))

    ctx = QueryContext(graph, initBindings=initBindings)

    ctx.prologue = query.prologue
    main = query.algebra

    if main.datasetClause:
        if ctx.dataset is None:
            raise Exception(
                "Non-conjunctive-graph doesn't know about " +
                "graphs! Try a query without FROM (NAMED).")

        ctx = ctx.clone()  # or push/pop?

        firstDefault = False
        for d in main.datasetClause:
            if d.default:

                if firstDefault:
                    # replace current default graph
                    dg = ctx.dataset.get_context(BNode())
                    ctx = ctx.pushGraph(dg)
                    firstDefault = True

                ctx.load(d.default, default=True)

            elif d.named:
                g = d.named
                ctx.load(g, default=False)

    return evalPart(ctx, main)
Пример #4
0
def evalUpdate(graph, update, initBindings=None):
    """

    http://www.w3.org/TR/sparql11-update/#updateLanguage

    'A request is a sequence of operations [...] Implementations MUST
    ensure that operations of a single request are executed in a
    fashion that guarantees the same effects as executing them in
    lexical order.

    Operations all result either in success or failure.

    If multiple operations are present in a single request, then a
    result of failure from any operation MUST abort the sequence of
    operations, causing the subsequent operations to be ignored.'

    This will return None on success and raise Exceptions on error

    """

    for u in update:

        ctx = QueryContext(graph)
        ctx.prologue = u.prologue

        if initBindings:
            for k, v in initBindings.items():
                if not isinstance(k, Variable):
                    k = Variable(k)
                ctx[k] = v
            # ctx.push()  # nescessary?

        try:
            if u.name == 'Load':
                evalLoad(ctx, u)
            elif u.name == 'Clear':
                evalClear(ctx, u)
            elif u.name == 'Drop':
                evalDrop(ctx, u)
            elif u.name == 'Create':
                evalCreate(ctx, u)
            elif u.name == 'Add':
                evalAdd(ctx, u)
            elif u.name == 'Move':
                evalMove(ctx, u)
            elif u.name == 'Copy':
                evalCopy(ctx, u)
            elif u.name == 'InsertData':
                evalInsertData(ctx, u)
            elif u.name == 'DeleteData':
                evalDeleteData(ctx, u)
            elif u.name == 'DeleteWhere':
                evalDeleteWhere(ctx, u)
            elif u.name == 'Modify':
                evalModify(ctx, u)
            else:
                raise Exception('Unknown update operation: %s' % (u,))
        except:
            if not u.silent:
                raise
Пример #5
0
def evalUpdate(graph, update, initBindings=None):
    """

    http://www.w3.org/TR/sparql11-update/#updateLanguage

    'A request is a sequence of operations [...] Implementations MUST
    ensure that operations of a single request are executed in a
    fashion that guarantees the same effects as executing them in
    lexical order.

    Operations all result either in success or failure.

    If multiple operations are present in a single request, then a
    result of failure from any operation MUST abort the sequence of
    operations, causing the subsequent operations to be ignored.'

    This will return None on success and raise Exceptions on error

    """

    for u in update:

        ctx = QueryContext(graph)
        ctx.prologue = u.prologue

        if initBindings:
            for k, v in initBindings.iteritems():
                if not isinstance(k, Variable):
                    k = Variable(k)
                ctx[k] = v
            # ctx.push()  # nescessary?

        try:
            if u.name == 'Load':
                evalLoad(ctx, u)
            elif u.name == 'Clear':
                evalClear(ctx, u)
            elif u.name == 'Drop':
                evalDrop(ctx, u)
            elif u.name == 'Create':
                evalCreate(ctx, u)
            elif u.name == 'Add':
                evalAdd(ctx, u)
            elif u.name == 'Move':
                evalMove(ctx, u)
            elif u.name == 'Copy':
                evalCopy(ctx, u)
            elif u.name == 'InsertData':
                evalInsertData(ctx, u)
            elif u.name == 'DeleteData':
                evalDeleteData(ctx, u)
            elif u.name == 'DeleteWhere':
                evalDeleteWhere(ctx, u)
            elif u.name == 'Modify':
                evalModify(ctx, u)
            else:
                raise Exception('Unknown update operation: %s' % (u, ))
        except:
            if not u.silent:
                raise
Пример #6
0
def evalUpdate(graph, update, initBindings={}):
    """

    http://www.w3.org/TR/sparql11-update/#updateLanguage

    'A request is a sequence of operations [...] Implementations MUST
    ensure that operations of a single request are executed in a
    fashion that guarantees the same effects as executing them in
    lexical order.

    Operations all result either in success or failure.

    If multiple operations are present in a single request, then a
    result of failure from any operation MUST abort the sequence of
    operations, causing the subsequent operations to be ignored.'

    This will return None on success and raise Exceptions on error

    """

    for u in update:

        initBindings = dict((Variable(k), v) for k, v in initBindings.items())

        ctx = QueryContext(graph, initBindings=initBindings)
        ctx.prologue = u.prologue

        try:
            if u.name == "Load":
                evalLoad(ctx, u)
            elif u.name == "Clear":
                evalClear(ctx, u)
            elif u.name == "Drop":
                evalDrop(ctx, u)
            elif u.name == "Create":
                evalCreate(ctx, u)
            elif u.name == "Add":
                evalAdd(ctx, u)
            elif u.name == "Move":
                evalMove(ctx, u)
            elif u.name == "Copy":
                evalCopy(ctx, u)
            elif u.name == "InsertData":
                evalInsertData(ctx, u)
            elif u.name == "DeleteData":
                evalDeleteData(ctx, u)
            elif u.name == "DeleteWhere":
                evalDeleteWhere(ctx, u)
            elif u.name == "Modify":
                evalModify(ctx, u)
            else:
                raise Exception("Unknown update operation: %s" % (u, ))
        except:
            if not u.silent:
                raise
Пример #7
0
    def _evaluate(self, bindings: Dict[str, str]) -> bool:
        """Evaluate the FILTER expression with a set mappings.
        
        Argument: A set of solution mappings.

        Returns: The outcome of evaluating the SPARQL FILTER on the input set of solution mappings.
        """
        d = {Variable(key[1:]): to_rdflib_term(value) for key, value in bindings.items()}
        b = Bindings(d=d)
        context = QueryContext(bindings=b)
        context.prologue = self._prologue
        return self._compiled_expression.eval(context)
Пример #8
0
    def _evaluate(self, bindings: Dict[str, str]) -> bool:
        """Evaluate the BIND expression with a set mappings.

        Argument: A set of solution mappings.

        Returns: The outcome of evaluating the SPARQL BIND on the input set of solution mappings.
        """
        #        print("bind_eval:"+str(bindings))
        ## For experiments on summaries
        if self._expr.startswith("<esumm>"):
            #print("express summ")
            s = URIRef(bindings['?s'])
            p = URIRef(bindings['?p'])
            o = Literal(bindings['?o'])
            dummy = Dummy()
            dummy.expr = [s, p, o]
            self._result = summary(dummy, None)
            return self._result
        elif self._expr.startswith("<fsumm>"):
            self._result = esummary(bindings['?s'], bindings['?p'],
                                    bindings['?o'])
            return self._result
        elif self._expr.startswith("<ehib>"):
            self._result = ehibsumm(bindings['?s'], bindings['?p'],
                                    bindings['?o'])
            return self._result
        elif self._expr.startswith("<split>"):
            self._result = splitsumm(bindings['?s'], bindings['?p'],
                                     bindings['?o'])
            return self._result
        elif self._expr.startswith("<suf>"):
            self._result = sufsumm(bindings['?s'], bindings['?p'],
                                   bindings['?o'])
            return self._result
        elif self._expr.startswith("<void>"):
            self._result = voidsumm(bindings['?s'], bindings['?p'],
                                    bindings['?o'])
            return self._result

        context = None
        if bindings is None:
            context = QueryContext(Bindings())
        else:
            d = {
                Variable(key[1:]): to_rdflib_term(value)
                for key, value in bindings.items()
            }
            b = Bindings(d=d)
            context = QueryContext(bindings=b)
        context.prologue = self._prologue
        self._result = self._compiled_expression.eval(context)
        return self._result
Пример #9
0
def evalQuery(graph, query, initBindings, base=None):
    ctx = QueryContext(graph)

    ctx.prologue = query.prologue

    if initBindings:
        for k, v in initBindings.items():
            if not isinstance(k, Variable):
                k = Variable(k)
            ctx[k] = v
        # ctx.push()  # nescessary?

    main = query.algebra

    # import pdb; pdb.set_trace()
    if main.datasetClause:
        if ctx.dataset is None:
            raise Exception(
                "Non-conjunctive-graph doesn't know about " +
                "graphs! Try a query without FROM (NAMED).")

        ctx = ctx.clone()  # or push/pop?

        firstDefault = False
        for d in main.datasetClause:
            if d.default:

                if firstDefault:
                    # replace current default graph
                    dg = ctx.dataset.get_context(BNode())
                    ctx = ctx.pushGraph(dg)
                    firstDefault = True

                ctx.load(d.default, default=True)

            elif d.named:
                g = d.named
                ctx.load(g, default=False)

    return evalPart(ctx, main)
Пример #10
0
def evalQuery(graph, query, initBindings, base=None):
    ctx = QueryContext(graph)

    ctx.prologue = query.prologue

    if initBindings:
        for k, v in initBindings.iteritems():
            if not isinstance(k, Variable):
                k = Variable(k)
            ctx[k] = v
        # ctx.push()  # nescessary?

    main = query.algebra

    # import pdb; pdb.set_trace()
    if main.datasetClause:
        if ctx.dataset is None:
            raise Exception("Non-conjunctive-graph doesn't know about " +
                            "graphs! Try a query without FROM (NAMED).")

        ctx = ctx.clone()  # or push/pop?

        firstDefault = False
        for d in main.datasetClause:
            if d.default:

                if firstDefault:
                    # replace current default graph
                    dg = ctx.dataset.get_context(BNode())
                    ctx = ctx.pushGraph(dg)
                    firstDefault = True

                ctx.load(d.default, default=True)

            elif d.named:
                g = d.named
                ctx.load(g, default=False)

    return evalPart(ctx, main)
Пример #11
0
def evalQuery(graph, query, initBindings, base=None):

    initBindings = dict( ( Variable(k),v ) for k,v in iteritems(initBindings) )

    ctx = QueryContext(graph, initBindings=initBindings)

    ctx.prologue = query.prologue
    main = query.algebra

    if main.datasetClause:
        if ctx.dataset is None:
            raise Exception(
                "Non-conjunctive-graph doesn't know about " +
                "graphs! Try a query without FROM (NAMED).")

        ctx = ctx.clone()  # or push/pop?

        firstDefault = False
        for d in main.datasetClause:
            if d.default:

                if firstDefault:
                    # replace current default graph
                    dg = ctx.dataset.get_context(BNode())
                    ctx = ctx.pushGraph(dg)
                    firstDefault = True

                ctx.load(d.default, default=True)

            # TODO re-enable original behaviour if FROM NAMED works with named graphs
            # https://github.com/AKSW/QuitStore/issues/144
            elif d.named:
                raise FromNamedError
            #     g = d.named
            #     ctx.load(g, default=False)

    return evalPart(ctx, main)
Пример #12
0
def evalQuery(graph, query, initBindings, base=None):
    ctx = QueryContext(graph)

    ctx.prologue = query.prologue

    main = query.algebra

    if initBindings:
        # add initBindings as a values clause

        values = {}  # no dict comprehension in 2.6 :(
        for k, v in initBindings.iteritems():
            if not isinstance(k, Variable):
                k = Variable(k)
            values[k] = v

        main = main.clone()  # clone to not change prepared q
        main['p'] = main.p.clone()
        # Find the right place to insert MultiSet join
        repl = main.p
        if repl.name == 'Slice':
            repl['p'] = repl.p.clone()
            repl = repl.p
        if repl.name == 'Distinct':
            repl['p'] = repl.p.clone()
            repl = repl.p
        if repl.p.name == 'OrderBy':
            repl['p'] = repl.p.clone()
            repl = repl.p
        if repl.p.name == 'Extend':
            repl['p'] = repl.p.clone()
            repl = repl.p

        repl['p'] = Join(repl.p, ToMultiSet(Values([values])))

        # TODO: Vars?

    if main.datasetClause:
        if ctx.dataset is None:
            raise Exception("Non-conjunctive-graph doesn't know about " +
                            "graphs! Try a query without FROM (NAMED).")

        ctx = ctx.clone()  # or push/pop?

        firstDefault = False
        for d in main.datasetClause:
            if d.default:

                if firstDefault:
                    # replace current default graph
                    dg = ctx.dataset.get_context(BNode())
                    ctx = ctx.pushGraph(dg)
                    firstDefault = True

                ctx.load(d.default, default=True)

            elif d.named:
                g = d.named
                ctx.load(g, default=False)

    return evalPart(ctx, main)
Пример #13
0
def evalQuery(graph, query, initBindings, base=None):
    ctx = QueryContext(graph)

    ctx.prologue = query.prologue

    main = query.algebra

    if initBindings:
        # add initBindings as a values clause

        values = {} # no dict comprehension in 2.6 :(
        for k,v in initBindings.iteritems():
            if not isinstance(k, Variable):
                k = Variable(k)
            values[k] = v

        main = main.clone() # clone to not change prepared q
        main['p'] = main.p.clone()
        # Find the right place to insert MultiSet join
        repl = main.p
        if repl.name == 'Slice':
            repl['p'] = repl.p.clone()
            repl = repl.p
        if repl.name == 'Distinct':
            repl['p'] = repl.p.clone()
            repl = repl.p
        if repl.p.name == 'OrderBy':
            repl['p'] = repl.p.clone()
            repl = repl.p
        if repl.p.name == 'Extend':
            repl['p'] = repl.p.clone()
            repl = repl.p

        repl['p'] = Join(repl.p, ToMultiSet(Values([values])))

        # TODO: Vars?

    if main.datasetClause:
        if ctx.dataset is None:
            raise Exception(
                "Non-conjunctive-graph doesn't know about " +
                "graphs! Try a query without FROM (NAMED).")

        ctx = ctx.clone()  # or push/pop?

        firstDefault = False
        for d in main.datasetClause:
            if d.default:

                if firstDefault:
                    # replace current default graph
                    dg = ctx.dataset.get_context(BNode())
                    ctx = ctx.pushGraph(dg)
                    firstDefault = True

                ctx.load(d.default, default=True)

            elif d.named:
                g = d.named
                ctx.load(g, default=False)

    return evalPart(ctx, main)