Skip to content

Commit

Permalink
Merge e387b1e into 7e060ad
Browse files Browse the repository at this point in the history
  • Loading branch information
kusamau committed Dec 9, 2013
2 parents 7e060ad + e387b1e commit a6b4c6e
Showing 1 changed file with 60 additions and 0 deletions.
60 changes: 60 additions & 0 deletions rdflib/plugins/stores/sparqlstore.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@
SPARQL_POST_UPDATE = "application/sparql-update"
SPARQL_POST_ENCODED = "application/x-www-form-urlencoded"

#Defines some SPARQL keywords
LIMIT = 'LIMIT'
OFFSET = 'OFFSET'
ORDERBY = 'ORDER BY'

import re
# import warnings
try:
Expand Down Expand Up @@ -276,7 +281,38 @@ def query(self, query,

def triples(self, (s, p, o), context=None):
"""
- tuple **(s, o, p)**
the triple used as filter for the SPARQL select.
(None, None, None) means anything.
- context **context**
the graph effectively calling this method.
Returns a tuple of triples executing essentially a SPARQL like
SELECT ?subj ?pred ?obj WHERE { ?subj ?pred ?obj }
**context** may include three parameter
to refine the underlying query:
* LIMIT: an integer to limit the number of results
* OFFSET: an integer to enable paging of results
* ORDERBY: an instance of Variable('s'), Variable('o') or Variable('p')
or, by default, the first 'None' from the given triple
.. warning::
- Using LIMIT or OFFSET automatically include ORDERBY otherwise this is
because the results are retrieved in a not deterministic way (depends on
the walking path on the graph)
- Using OFFSET without defining LIMIT will discard the first OFFSET - 1
results
``
g.LIMIT = limit
g.OFFSET = offset
triple_generator = graph.triples(mytriple):
#do something
#Removes LIMIT and OFFSET if not required for the next triple() calls
del g.LIMIT
del g.OFFSET
``
"""

if ( isinstance(s, BNode) or
Expand Down Expand Up @@ -304,6 +340,30 @@ def triples(self, (s, p, o), context=None):
query = "SELECT %s WHERE { %s %s %s }" % \
(v, s.n3(), p.n3(), o.n3())

#The ORDER BY is necessary
if hasattr(context, LIMIT) or hasattr(context, OFFSET) \
or hasattr(context, ORDERBY):
var = None
if isinstance(s, Variable):
var = s
elif isinstance(p, Variable):
var = p
elif isinstance(o, Variable):
var = o
elif hasattr(context, ORDERBY) \
and isinstance(getattr(context, ORDERBY), Variable):
var = getattr(context, ORDERBY)
query = query + ' %s %s' % (ORDERBY, var.n3())

try:
query = query + ' LIMIT %s' % int(getattr(context, LIMIT))
except (ValueError, TypeError, AttributeError):
pass
try:
query = query + ' OFFSET %s' % int(getattr(context, OFFSET))
except (ValueError, TypeError, AttributeError):
pass

self.resetQuery()
if self.context_aware and context is not None:
self.addDefaultGraph(context.identifier)
Expand Down

0 comments on commit a6b4c6e

Please sign in to comment.