#!/usr/bin/python """Semantic Web API Query Module.""" __author__ = 'Sean B. Palmer' __license__ = 'Copyright (C) 2002 Sean B. Palmer. GNU GPL 2' import api, ntuples, copy class Query: def __init__(self): self.result = [] def mquery(self, store, querytuples, bindings, found=[]): if len(querytuples) > 0: # Now we query p = [] for j in range(len(querytuples[0])): if querytuples[0][j].type == 'Univar': p.append(j) res = store.query(querytuples[0]) for r in res: b = copy.copy(bindings) f = copy.copy(found) cont = 1 for j in p: # add the variables to the binding, and query again if b[`querytuples[0][j]`] in (None, `r[j]`): b[`querytuples[0][j]`] = `r[j]` else: cont = 0 if cont: f.append(r) self.mquery(store, querytuples[1:], b, f) elif None not in bindings.values(): self.result.append((found, bindings)) def uquery(self, store, querytuples): """Query a set of triples against a store.""" bindings = {} # Make a dictionary of all the variables in querytuples for qtuple in querytuples: for x in qtuple: if x.type == 'Univar': bindings[`x`] = None self.mquery(store, querytuples, bindings) return self.result def query(f, q, fmt=0): assert isinstance(f, api.TupleStore) assert isinstance(q, api.TupleStore) x = Query().uquery(f, q) return [x, '\n\n'.join([ntuples.serialize(api.TupleStore(y[0])) for y in x])][fmt] if __name__=="__main__": print __doc__