SparqlQuery

From ActiveArchives
Jump to: navigation, search
class SparqlQuery (object):
    """ A very thin sparql query builder """
    def __init__(self):
        self._prefixes = []
        self._select = None
        self._wheres = []
        self._whereclauses = None
        self._orderby = None
        self._filters = []
 
    def prefix (self, val):
        if not val in self._prefixes:
            self._prefixes.append(val)
 
    def select (self, vals, distinct=False):
        self._select = vals
        self._selectdistinct = distinct
 
    def where (self, val):
        val = "  " + val
        self._wheres.append(val)
 
    def filter (self, val):
        self._filters.append(val)
 
    def orderby(self, val):
        self._orderby = val
 
    def where_clause(self, clause):
        if self._whereclauses == None:
            self._whereclauses = []
        clause = "    {%s}\n" % clause
        self._whereclauses.append(clause)
 
    def where_clause_end(self):
        self.where("{\n" + "    UNION\n".join(self._whereclauses) + "  }")
        self._whereclauses = None
 
    def render(self):
        ret = ""
        ret += "".join(["PREFIX %s\n" % x for x in self._prefixes])
        if self._select:
            if self._selectdistinct:
                ret += "SELECT DISTINCT %s\n" % self._select
            else:
                ret += "SELECT %s\n" % self._select
        if self._wheres:
            ret += "WHERE {\n"
            ret += "".join(["%s\n" % x for x in self._wheres])
            if self._filters:
                ret += "".join(["  FILTER %s\n" % x for x in self._filters])
            ret += "}\n"
        if self._orderby:
            ret += "ORDER BY %s\n" % self._orderby
 
        return ret

What links here

Personal tools
Namespaces

Variants
Actions
Navigation
Toolbox