PageRenderTime 271ms CodeModel.GetById 35ms RepoModel.GetById 37ms app.codeStats 0ms

/api/query.py

https://bitbucket.org/timgluz/franziska
Python | 137 lines | 82 code | 3 blank | 52 comment | 2 complexity | 46898dd7003804b6551e9b34debdd094 MD5 | raw file
  1. """
  2. Query.py - includes query handlers
  3. doing query, rest-server expect those params:
  4. query - The query to be executed. The query may use the namespace prefixes defined for the user.
  5. queryLn - The language of the query. Can be sparql or prolog. Defaults to sparql.
  6. infer - A string that determines what kind of reasoning is used when executing the query.
  7. Default is false, no reasoning. Other options are rdfs++ (same as true),
  8. and hasvalue.
  9. context - Can be passed zero or more times. Sets the graph name, or list of graph names,
  10. that will be used by this query (as in FROM).
  11. When no context is given, all graphs are used.
  12. The string null can be used to refer to the default graph of the store.
  13. namedContext - Also can be given multiple times.
  14. Behaves like context, except that the named graphs retain their
  15. names (as in FROM NAMED).
  16. default-graph-uri - Can be passed any number of times.
  17. Works like context except that plain-URI values should be given,
  18. without wrapping < and > characters.
  19. named-graph-uri - Works like default-graph-uri, except that this specifies the named
  20. graphs to be used.
  21. limit - An integer. Can be used to limit the amount of results returned by the query.
  22. offset - An integer. Can be used to skip a number of results at the start of the query.
  23. $[varname] - Parameters starting with a $ character can be used to bind query variables
  24. to fixed value (an N-Triples term) when executing a SPARQL query.
  25. checkVariables - A boolean that defaults to false, indicating whether an error should be
  26. raised when a SPARQL query selects variables that are not mentioned in the query body.
  27. defaultGraphName - Can be used to provide a resource (URL) name for the default graph.
  28. Any references to that resource will reference the default graph, and in the
  29. output the resource will be substituted for any references to the default graph.
  30. Can be given multiple times to have multiple names refer to this graph,
  31. but only the first one will appear in the output.
  32. planner - Can be used to control the way the query is planned .
  33. save - When given, will cause the server to (as well as executing the query normally)
  34. save the query as a prepared query under the name passed as the value for this parameter. See preparing queries below.
  35. The result formats supported depends on the query. Prolog queries return tabular data,
  36. as do SPARQL select queries. describe or construct queries return triples, and ask queries
  37. return a boolean value.
  38. Prolog queries are allowed to return nested lists of results, in which case the result
  39. can only be returned as application/json, and the nested structure (both in the list of
  40. column names and in the results themselves) will be represented as nested JSON arrays.
  41. """
  42. class Param(object):
  43. """
  44. This class maps python objects with AllegroGraph params, this class is important
  45. because Agraph params dont follow any logic,sometimes variables are camelCased and
  46. another time they separates-variables-with-minus
  47. """
  48. #TODO: default decoder to unicode
  49. def __init__(self, name, value, decoder = lambda x: str(x)):
  50. self.name = name
  51. self.value = value #TODO; test different values -utf8
  52. self.decoder = decoder
  53. def _unicode(val):
  54. """decodes strings to unicode"""
  55. return val
  56. def __str__(self):
  57. """serialize object as string, skips param, which value is just None"""
  58. if self.value:
  59. val = "%s=%s" % (self.name, self.decoder(self.value))
  60. else:
  61. val = ""
  62. return val
  63. class AllegroQuery(object):
  64. """prolog/sparql queries returns tabular data,
  65. describe/construct - triples
  66. ask - boolean,
  67. sparql/update queries need POST method
  68. """
  69. def __init__(self, query, **kwargs):
  70. self.query = Param("query", query, lambda x: str(x))
  71. self.qlanq = Param("queryLn", kwargs.get("qlang", "sparql"),
  72. lambda x: str(x)) #'sparql', 'prolog'
  73. self.infer = Param("infer", kwargs.get("infer", False),
  74. lambda x: str(x).lower())
  75. self.context = Param("context", kwargs.get("context", None)) #"null"
  76. self.named_context = Param("namedContext",kwargs.get("named_context", None))
  77. self.limit = Param("limit", kwargs.get("limit", None))
  78. self.offset = Param("offset", kwargs.get("offset", None))
  79. self.check_variables = Param("checkVariables",
  80. kwargs.get("check_variables", False),
  81. lambda x: str(x).lower())
  82. self.default_graph = Param("defaultGraphName", kwargs.get("default_graph", None))
  83. self.planner = Param("planner", kwargs.get("planner", None))
  84. self.save = Param("save", kwargs.get("save", None),
  85. lambda x: str(x).lower())
  86. def serialize(self, separator = ","):
  87. """object to string"""
  88. result = separator
  89. for key in self.__dict__.iterkeys():
  90. val = self.__dict__[key]
  91. if isinstance(val, Param) and val.value is not None:
  92. result.join(str(val))
  93. return result
  94. def to_dict(self):
  95. """build dictionary from class"""
  96. result = {}
  97. for key in self.__dict__.iterkeys():
  98. val = self.__dict__[key]
  99. #add only values which are not None and Param instance, that means will be part
  100. #of query arguments
  101. if isinstance(val, Param) and val.value is not None:
  102. result[val.name] = val.decoder(val.value)
  103. return result
  104. #TODO: add execute and save functionality - integrate with Queries
  105. class PrologQuery(AllegroQuery):
  106. def __init__(self, query, **kwargs ):
  107. """
  108. Args:
  109. query - query string
  110. infer - boolean, do you need infer rules
  111. """
  112. self.type = "prolog"
  113. kwargs["qlang"] = self.type
  114. super(PrologQuery, self).__init__(query, **kwargs)
  115. class SparqlQuery(AllegroQuery):
  116. """ """
  117. def __init__(self, query, **kwargs):
  118. self.type = "sparql"
  119. kwargs["qlang"] = self.type
  120. super(SparqlQuery, self).__init__(query, **kwargs)
  121. class StatementQuery(object):
  122. '''object to represent query for asking statements from DB'''
  123. pass