Esempio n. 1
0
    def read_context(self, key):

        user = self.get_user()

        for q in self.kb.filter_quads(s=user, p=USER_PROP_PREFIX + key):
            return rdf_to_pl(q[2])

        user = DEFAULT_USER

        for q in self.kb.filter_quads(s=user, p=USER_PROP_PREFIX + key):
            return rdf_to_pl(q[2])

        return None
Esempio n. 2
0
def builtin_sparql_query(g, pe):

    pe._trace('CALLED BUILTIN sparql_query', g)

    pred = g.terms[g.inx]
    args = pred.args
    if len(args) < 1:
        raise PrologRuntimeError('sparql_query: at least 1 argument expected.')

    query = pe.prolog_get_string(args[0], g.env)

    # logging.debug("builtin_sparql_query called, query: '%s'" % query)

    # run query

    result = pe.kb.query(query)

    # logging.debug("builtin_sparql_query result: '%s'" % repr(result))

    if len(result) == 0:
        return False

    # turn result into lists of literals we can then bind to prolog variables

    res_map = {}
    res_vars = {}  # variable idx -> variable name

    for binding in result:

        for v in binding.labels:

            l = binding[v]

            value = rdf_to_pl(l)

            if not v in res_map:
                res_map[v] = []
                res_vars[binding.labels[v]] = v

            res_map[v].append(value)

    # logging.debug("builtin_sparql_query res_map : '%s'" % repr(res_map))
    # logging.debug("builtin_sparql_query res_vars: '%s'" % repr(res_vars))

    # apply bindings to environment vars

    v_idx = 0

    for arg in args[1:]:

        sparql_var = res_vars[v_idx]
        prolog_var = pe.prolog_get_variable(arg, g.env)
        value = res_map[sparql_var]

        # logging.debug("builtin_sparql_query mapping %s -> %s: '%s'" % (sparql_var, prolog_var, value))

        g.env[prolog_var] = ListLiteral(value)

        v_idx += 1

    return True
Esempio n. 3
0
def _rdf_exec(g, pe, generate_lists=False):

    # rdflib.plugins.sparql.parserutils.CompValue
    #
    # class CompValue(OrderedDict):
    #     def __init__(self, name, **values):
    #
    # SelectQuery(
    #   p =
    #     Project(
    #       p =
    #         LeftJoin(
    #           p2 =
    #             BGP(
    #               triples = [(rdflib.term.Variable(u'leaderobj'), rdflib.term.URIRef(u'http://dbpedia.org/ontology/leader'), rdflib.term.Variable(u'leader'))]
    #               _vars = set([rdflib.term.Variable(u'leaderobj'), rdflib.term.Variable(u'leader')])
    #             )
    #           expr =
    #             TrueFilter(
    #               _vars = set([])
    #             )
    #           p1 =
    #             BGP(
    #               triples = [(rdflib.term.Variable(u'leader'), rdflib.term.URIRef(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#type'), rdflib.term.URIRef(u'http://schema.org/Person')), (rdflib.term.Variable(u'leader'), rdflib.term.URIRef(u'http://www.w3.org/2000/01/rdf-schema#label'), rdflib.term.Variable(u'label'))]
    #               _vars = set([rdflib.term.Variable(u'label'), rdflib.term.Variable(u'leader')])
    #             )
    #           _vars = set([rdflib.term.Variable(u'leaderobj'), rdflib.term.Variable(u'label'), rdflib.term.Variable(u'leader')])
    #         )
    #       PV = [rdflib.term.Variable(u'leader'), rdflib.term.Variable(u'label'), rdflib.term.Variable(u'leaderobj')]
    #       _vars = set([rdflib.term.Variable(u'leaderobj'), rdflib.term.Variable(u'label'), rdflib.term.Variable(u'leader')])
    #     )
    #   datasetClause = None
    #   PV = [rdflib.term.Variable(u'leader'), rdflib.term.Variable(u'label'), rdflib.term.Variable(u'leaderobj')]
    #   _vars = set([rdflib.term.Variable(u'leaderobj'), rdflib.term.Variable(u'label'), rdflib.term.Variable(u'leader')])
    # )

    pred = g.terms[g.inx]
    args = pred.args
    # if len(args) == 0 or len(args) % 3 != 0:
    #     raise PrologRuntimeError('rdf: one or more argument triple(s) expected, got %d args' % len(args))

    distinct = False
    triples = []
    optional_triples = []
    filters = []
    limit = 0
    offset = 0

    arg_idx = 0
    var_map = {}  # string -> rdflib.term.Variable

    while arg_idx < len(args):

        arg_s = args[arg_idx]

        # check for optional structure
        if isinstance(arg_s, Predicate) and arg_s.name == 'optional':

            s_args = arg_s.args

            if len(s_args) != 3:
                raise PrologRuntimeError('rdf: optional: triple arg expected')

            arg_s = s_args[0]
            arg_p = s_args[1]
            arg_o = s_args[2]

            logging.debug('rdf: optional arg triple: %s' % repr(
                (arg_s, arg_p, arg_o)))

            optional_triples.append(
                (pl_to_rdf(arg_s, g.env, pe, var_map,
                           pe.kb), pl_to_rdf(arg_p, g.env, pe, var_map, pe.kb),
                 pl_to_rdf(arg_o, g.env, pe, var_map, pe.kb)))

            arg_idx += 1

        # check for filter structure
        elif isinstance(arg_s, Predicate) and arg_s.name == 'filter':

            logging.debug('rdf: filter structure detected: %s' %
                          repr(arg_s.args))

            s_args = arg_s.args

            # transform multiple arguments into explicit and-tree

            pl_expr = s_args[0]
            for a in s_args[1:]:
                pl_expr = Predicate('and', [pl_expr, a])

            filters.append(
                prolog_to_filter_expression(pl_expr, g.env, pe, var_map,
                                            pe.kb))

            arg_idx += 1

        # check for distinct
        elif isinstance(arg_s, Predicate) and arg_s.name == 'distinct':

            s_args = arg_s.args
            if len(s_args) != 0:
                raise PrologRuntimeError(
                    'rdf: distinct: unexpected arguments.')

            distinct = True
            arg_idx += 1

        # check for limit/offset
        elif isinstance(arg_s, Predicate) and arg_s.name == 'limit':

            s_args = arg_s.args
            if len(s_args) != 1:
                raise PrologRuntimeError('rdf: limit: one argument expected.')

            limit = pe.prolog_get_int(s_args[0], g.env)
            arg_idx += 1

        elif isinstance(arg_s, Predicate) and arg_s.name == 'offset':

            s_args = arg_s.args
            if len(s_args) != 1:
                raise PrologRuntimeError('rdf: offset: one argument expected.')

            offset = pe.prolog_get_int(s_args[0], g.env)
            arg_idx += 1

        else:

            if arg_idx > len(args) - 3:
                raise PrologRuntimeError(
                    'rdf: not enough arguments for triple')

            arg_p = args[arg_idx + 1]
            arg_o = args[arg_idx + 2]

            logging.debug('rdf: arg triple: %s' % repr((arg_s, arg_p, arg_o)))

            triples.append(
                (pl_to_rdf(arg_s, g.env, pe, var_map,
                           pe.kb), pl_to_rdf(arg_p, g.env, pe, var_map, pe.kb),
                 pl_to_rdf(arg_o, g.env, pe, var_map, pe.kb)))

            arg_idx += 3

    logging.debug('rdf: triples: %s' % repr(triples))
    logging.debug('rdf: optional_triples: %s' % repr(optional_triples))
    logging.debug('rdf: filters: %s' % repr(filters))

    if len(triples) == 0:
        raise PrologRuntimeError(
            'rdf: at least one non-optional triple expected')

    var_list = var_map.values()
    var_set = set(var_list)

    p = CompValue('BGP', triples=triples, _vars=var_set)

    for t in optional_triples:
        p = CompValue('LeftJoin',
                      p1=p,
                      p2=CompValue('BGP', triples=[t], _vars=var_set),
                      expr=CompValue('TrueFilter', _vars=set([])))

    for f in filters:
        p = CompValue('Filter', p=p, expr=f, _vars=var_set)

    if limit > 0:
        p = CompValue('Slice', start=offset, length=limit, p=p, _vars=var_set)

    if distinct:
        p = CompValue('Distinct', p=p, _vars=var_set)

    algebra = CompValue('SelectQuery',
                        p=p,
                        datasetClause=None,
                        PV=var_list,
                        _vars=var_set)

    result = pe.kb.query_algebra(algebra)

    logging.debug('rdf: result (len: %d): %s' % (len(result), repr(result)))

    if len(result) == 0:
        return False

    if generate_lists:

        # bind each variable to list of values

        for binding in result:

            for v in binding.labels:

                l = binding[v]

                value = rdf_to_pl(l)

                if not v in g.env:
                    g.env[v] = ListLiteral([])

                g.env[v].l.append(value)

        return True

    else:

        # turn result into list of bindings

        res_bindings = []
        for binding in result:

            res_binding = {}

            for v in binding.labels:

                l = binding[v]

                value = rdf_to_pl(l)

                res_binding[v] = value

            res_bindings.append(res_binding)

        if len(res_bindings) == 0 and len(result) > 0:
            res_bindings.append({})  # signal success

        logging.debug('rdf: res_bindings: %s' % repr(res_bindings))

        return res_bindings