query.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. from dataclasses import dataclass, field
  2. from typing import List
  3. from urllib.error import URLError
  4. import arklog
  5. from SPARQLWrapper import SPARQLWrapper, JSON, POSTDIRECTLY
  6. from SPARQLWrapper.SPARQLExceptions import QueryBadFormed
  7. arklog.set_config_logging()
  8. @dataclass(init=True, repr=True, order=False, frozen=True)
  9. class Prefix:
  10. name: str
  11. namespace: str
  12. def __str__(self) -> str:
  13. """Return the prefix in the SPARQL format."""
  14. return f"PREFIX {self.name}: <{self.namespace}>"
  15. @dataclass(init=True, repr=True, order=False, frozen=True)
  16. class Replacement:
  17. placeholder: str
  18. description: str
  19. suggestion: str
  20. @dataclass(init=True, repr=True, order=False, frozen=True)
  21. class QueryTemplate:
  22. group: str
  23. name: str
  24. prefix: str
  25. query: str
  26. description: str
  27. visual_support: bool = False
  28. replacements: List[Replacement] = field(default_factory=list)
  29. modifies: bool = False
  30. # TODO Rewrite this
  31. reverse_prefix = {
  32. "https://ontology.rys.app/dt/function/": "dtf",
  33. "http://www.w3.org/2002/07/owl#": "owl",
  34. "http://www.w3.org/1999/02/22-rdf-syntax-ns#": "rdf",
  35. "http://www.w3.org/2001/XMLSchema#": "xsd",
  36. "http://www.w3.org/2000/01/rdf-schema#": "rdfs",
  37. "http://ua.be/drivetrain/description/artifacts/artifacts#": "art",
  38. "http://ua.be/sdo2l/vocabulary/base/tabular#": "tabular",
  39. "http://purl.org/dc/elements/1.1/": "dc",
  40. "http://ua.be/sdo2l/vocabulary/ftg#": "ftg",
  41. "http://ua.be/sdo2l/vocabulary/base#": "base",
  42. "http://bipm.org/jcgm/vim4#": "vim4",
  43. "http://ua.be/sdo2l/vocabulary/component#": "comp",
  44. "http://ua.be/sdo2l/vocabulary/base/code#":"code",
  45. "http://ua.be/sdo2l/vocabulary/base/script#": "script",
  46. "http://ua.be/sdo2l/vocabulary/base/file#": "file",
  47. "http://www.w3.org/2003/11/swrl#": "swrl",
  48. "http://ua.be/sdo2l/vocabulary/processtraces#":"traces",
  49. "http://ua.be/sdo2l/vocabulary/workflow#": "wf",
  50. "http://ua.be/sdo2l/vocabulary/base/text#": "text",
  51. "http://ua.be/sdo2l/vocabulary/federation#": "federation",
  52. "http://ua.be/drivetrain/description/ftg#": "dftg",
  53. }
  54. def perform_query(endpoint: str, query_text: str, post: bool = False) -> dict:
  55. """"""
  56. sparql = SPARQLWrapper(endpoint)
  57. sparql.setReturnFormat(JSON)
  58. if post:
  59. sparql.setRequestMethod(POSTDIRECTLY)
  60. sparql.setQuery(query_text)
  61. try:
  62. ret = sparql.query().convert()
  63. except QueryBadFormed:
  64. raise
  65. except URLError:
  66. raise
  67. return ret