py_graph.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. #ifndef _PY_GRAPH_MOD_H
  2. #define _PY_GRAPH_MOD_H
  3. #define PY_SSIZE_T_CLEAN
  4. #include <Python.h>
  5. #include <structmember.h>
  6. #include "graph.h"
  7. #include "codec_nt.h"
  8. #include "py_triple.h"
  9. /*
  10. * String iterator for codec output.
  11. *
  12. * Yields one string (one or more lines) at a time.
  13. */
  14. typedef struct {
  15. PyObject_HEAD
  16. LSUP_CodecIterator *it;
  17. unsigned char *line;
  18. } StringIteratorObject;
  19. static void
  20. StringIterator_dealloc (StringIteratorObject *it_obj)
  21. { it_obj->it->codec->encode_graph_done (it_obj->it); }
  22. static PyObject *
  23. StringIterator_next (StringIteratorObject *it_obj)
  24. {
  25. LSUP_rc rc = it_obj->it->codec->encode_graph_iter (
  26. it_obj->it, &it_obj->line);
  27. if (rc != LSUP_OK) {
  28. if (rc != LSUP_END)
  29. PyErr_SetString (PyExc_ValueError, "Error encoding graph.");
  30. // If not an error, this raises StopIteration.
  31. return NULL;
  32. }
  33. PyObject *rdf_obj = PyUnicode_FromString ((char*)it_obj->line);
  34. if (UNLIKELY (!rdf_obj)) return NULL;
  35. Py_INCREF (rdf_obj);
  36. return (rdf_obj);
  37. }
  38. /*
  39. * String iterator type.
  40. *
  41. * Objects of this type are never generated from Python code, rather from
  42. * Graph_encode, hence the type has no special new or init function.
  43. */
  44. PyTypeObject StringIteratorType = {
  45. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  46. .tp_name = "graph.StringIterator",
  47. .tp_basicsize = sizeof (StringIteratorObject),
  48. .tp_itemsize = 0,
  49. .tp_flags = Py_TPFLAGS_DEFAULT,
  50. .tp_dealloc = (destructor) StringIterator_dealloc,
  51. .tp_iter = PyObject_SelfIter,
  52. .tp_iternext = (iternextfunc)StringIterator_next,
  53. };
  54. /*
  55. * Graph stuff.
  56. */
  57. typedef struct {
  58. PyObject_HEAD
  59. LSUP_Graph *ob_struct;
  60. } GraphObject;
  61. static int
  62. Graph_init (GraphObject *self, PyObject *args, PyObject *kwargs)
  63. {
  64. unsigned char store_type;
  65. if (!PyArg_ParseTuple (args, "b", &store_type))
  66. return -1;
  67. self->ob_struct = LSUP_graph_new ((LSUP_store_type)store_type);
  68. if (!self->ob_struct) {
  69. PyErr_SetString (PyExc_ValueError, "Could not create graph.");
  70. return -1;
  71. }
  72. return 0;
  73. }
  74. static void
  75. Graph_dealloc (GraphObject *self)
  76. {
  77. LSUP_graph_free (self->ob_struct);
  78. Py_TYPE (self)->tp_free ((PyObject *) self);
  79. }
  80. static PyObject *
  81. Graph_get_uri (GraphObject *self, void *closure)
  82. {
  83. PyObject *uri = PyUnicode_FromString (
  84. LSUP_graph_uri (self->ob_struct)->data);
  85. if ( UNLIKELY (!uri)) return NULL;
  86. Py_INCREF(uri);
  87. return uri;
  88. }
  89. static int
  90. Graph_set_uri (GraphObject *self, PyObject *value, void *closure)
  91. {
  92. if (!PyObject_TypeCheck (value, &TermType)) return -1;
  93. LSUP_rc rc = LSUP_graph_set_uri (
  94. self->ob_struct, ((TermObject*)value)->ob_struct->data);
  95. return rc == LSUP_OK ? 0 : -1;
  96. }
  97. static PyGetSetDef Graph_getsetters[] = {
  98. {
  99. "uri", (getter) Graph_get_uri, (setter) Graph_set_uri,
  100. "Graph URI.", NULL
  101. },
  102. {NULL}
  103. };
  104. static PyObject *
  105. Graph_copy (PyTypeObject *cls, PyObject *src)
  106. {
  107. if (! PyObject_TypeCheck (src, cls)) return NULL;
  108. GraphObject *res = (GraphObject *) cls->tp_alloc(cls, 0);
  109. if (!res) return NULL;
  110. res->ob_struct = LSUP_graph_copy (((GraphObject *) src)->ob_struct);
  111. Py_INCREF(res);
  112. return (PyObject *) res;
  113. }
  114. static PyObject *
  115. Graph_new_from_rdf (PyTypeObject *cls, PyObject *args)
  116. {
  117. PyObject *buf, *fileno_fn, *fileno_obj;
  118. const char *type;
  119. if (! PyArg_ParseTuple (args, "Os", &buf, &type)) return NULL;
  120. // Get the file descriptor from the Python BufferedIO object.
  121. // FIXME This is not sure to be reliable. See
  122. // https://docs.python.org/3/library/io.html?highlight=io%20bufferedreader#io.IOBase.fileno
  123. if (! (fileno_fn = PyObject_GetAttrString (buf, "fileno"))) {
  124. PyErr_SetString (PyExc_TypeError, "Object has no fileno function.");
  125. return NULL;
  126. }
  127. PyObject* fileno_args = PyTuple_New(0);
  128. if (! (fileno_obj = PyObject_CallObject (fileno_fn, fileno_args))) {
  129. PyErr_SetString (PyExc_SystemError, "Error calling fileno function.");
  130. return NULL;
  131. }
  132. int fd = PyLong_AsSize_t (fileno_obj);
  133. /*
  134. * From the Linux man page:
  135. *
  136. * > The file descriptor is not dup'ed, and will be closed when the stream
  137. * > created by fdopen() is closed. The result of applying fdopen() to a
  138. * > shared memory object is undefined.
  139. *
  140. * This handle must not be closed. Leave open for the Python caller to
  141. * handle it.
  142. */
  143. FILE *fh = fdopen (fd, "r");
  144. GraphObject *res = (GraphObject *) cls->tp_alloc(cls, 0);
  145. if (!res) return PyErr_NoMemory();
  146. const LSUP_Codec *codec;
  147. if (strcmp(type, "nt") == 0) codec = &nt_codec;
  148. // TODO other codecs here.
  149. else {
  150. PyErr_SetString (PyExc_ValueError, "Unsupported codec.");
  151. return NULL;
  152. }
  153. size_t ct;
  154. char *err;
  155. codec->decode_graph (fh, &res->ob_struct, &ct, &err);
  156. TRACE ("Decoded %lu triples.\n", ct);
  157. if (UNLIKELY (err)) {
  158. PyErr_SetString (PyExc_IOError, err);
  159. return NULL;
  160. }
  161. Py_INCREF(res);
  162. return (PyObject *) res;
  163. }
  164. static PyObject *
  165. Graph_richcmp (PyObject *self, PyObject *other, int op)
  166. {
  167. // Only equality and non-equality are supported.
  168. if (op != Py_EQ && op != Py_NE) Py_RETURN_NOTIMPLEMENTED;
  169. LSUP_Graph *t1 = ((GraphObject *) self)->ob_struct;
  170. LSUP_Graph *t2 = ((GraphObject *) other)->ob_struct;
  171. if (LSUP_graph_equals (t1, t2) ^ (op == Py_NE)) Py_RETURN_TRUE;
  172. Py_RETURN_FALSE;
  173. }
  174. static inline PyObject *
  175. Graph_bool_op (
  176. PyTypeObject *cls, LSUP_bool_op op, PyObject *gr1, PyObject *gr2)
  177. {
  178. if (! PyObject_TypeCheck (gr1, cls) || ! PyObject_TypeCheck (gr2, cls))
  179. return NULL;
  180. GraphObject *res = (GraphObject *) cls->tp_alloc (cls, 0);
  181. if (!res) return NULL;
  182. res->ob_struct = LSUP_graph_bool_op (
  183. op, ((GraphObject *) gr1)->ob_struct,
  184. ((GraphObject *) gr2)->ob_struct);
  185. Py_INCREF(res);
  186. return (PyObject *) res;
  187. }
  188. static PyObject *
  189. Graph_add (PyObject *self, PyObject *triples)
  190. {
  191. // Triple may be any iterable.
  192. PyObject *iter = PyObject_GetIter (triples);
  193. if (! iter) {
  194. PyErr_SetString (
  195. PyExc_ValueError, "Triples object cannot be iterated.");
  196. return NULL;
  197. }
  198. PyObject *trp_obj = NULL;
  199. int rc = 0;
  200. size_t i;
  201. LSUP_SerTriple *sspo = LSUP_striple_new (BUF_DUMMY, BUF_DUMMY, BUF_DUMMY);
  202. LSUP_GraphIterator *it = LSUP_graph_add_init (
  203. ((GraphObject *)self)->ob_struct);
  204. for (i = 0; (trp_obj = PyIter_Next (iter)); i++) {
  205. if (!PyObject_TypeCheck (trp_obj, &TripleType)) {
  206. PyErr_SetString (
  207. PyExc_ValueError, "Object is not a triple.");
  208. rc = -1;
  209. goto finalize;
  210. }
  211. TRACE ("Inserting triple #%lu\n", i);
  212. LSUP_triple_serialize (((TripleObject *)trp_obj)->ob_struct, sspo);
  213. LSUP_rc db_rc = LSUP_graph_add_iter (it, sspo);
  214. if (db_rc == LSUP_OK) rc = LSUP_OK;
  215. if (UNLIKELY (db_rc < 0)) {
  216. rc = -1;
  217. goto finalize;
  218. }
  219. }
  220. finalize:
  221. LSUP_graph_add_done (it);
  222. LSUP_striple_free (sspo);
  223. PyObject *ret = PyLong_FromSize_t (LSUP_graph_iter_cur (it));
  224. if (rc == 0) {
  225. Py_INCREF (ret);
  226. return ret;
  227. }
  228. return NULL;
  229. }
  230. // TODO
  231. static int Graph_remove (PyObject *self, PyObject *s, PyObject *p, PyObject *o)
  232. {
  233. return 0;
  234. }
  235. // TODO
  236. static PyObject *Graph_lookup (
  237. PyObject *self, PyObject *s, PyObject *p, PyObject *o)
  238. {
  239. return NULL;
  240. }
  241. static PyObject *
  242. Graph_encode (PyObject *self, PyObject *args)
  243. {
  244. char *type;
  245. if (! PyArg_ParseTuple (args, "s", &type)) return NULL;
  246. const LSUP_Codec *codec;
  247. if (strcmp(type, "nt") == 0) codec = &nt_codec;
  248. // TODO other codecs here.
  249. else {
  250. PyErr_SetString (PyExc_ValueError, "Unsupported codec.");
  251. return NULL;
  252. }
  253. LSUP_CodecIterator *it = codec->encode_graph_init (
  254. ((GraphObject *)self)->ob_struct);
  255. // Initialize the generator object.
  256. StringIteratorObject *it_obj = PyObject_New (
  257. StringIteratorObject, &StringIteratorType);
  258. if (!it_obj) return NULL;
  259. it_obj->it = it;
  260. it_obj->line = NULL;
  261. Py_INCREF (it_obj);
  262. return (PyObject *)it_obj;
  263. }
  264. static PyMethodDef Graph_methods[] = {
  265. {
  266. "copy", (PyCFunction) Graph_copy,
  267. METH_CLASS | METH_VARARGS, "Copy a graph."
  268. },
  269. {
  270. "from_rdf", (PyCFunction) Graph_new_from_rdf,
  271. METH_CLASS | METH_VARARGS, "Create a graph from a RDF file."
  272. },
  273. {"add", (PyCFunction) Graph_add, METH_O, "Add triples to a graph."},
  274. {
  275. "remove", (PyCFunction) Graph_remove, METH_VARARGS,
  276. "Remove triples from a graph by matching a pattern."
  277. },
  278. {
  279. "lookup", (PyCFunction) Graph_lookup, METH_VARARGS,
  280. "Look triples in a graph by matching a pattern."
  281. },
  282. {
  283. "to_rdf", (PyCFunction) Graph_encode, METH_VARARGS,
  284. "Encode a graph into a RDF byte buffer."
  285. },
  286. {NULL},
  287. };
  288. static inline PyObject *Graph_bool_and (
  289. PyTypeObject *cls, PyObject *gr1, PyObject *gr2)
  290. { return Graph_bool_op (cls, LSUP_BOOL_INTERSECTION, gr1, gr2); }
  291. static inline PyObject *Graph_bool_or (
  292. PyTypeObject *cls, PyObject *gr1, PyObject *gr2)
  293. { return Graph_bool_op (cls, LSUP_BOOL_UNION, gr1, gr2); }
  294. static inline PyObject *Graph_bool_subtract (
  295. PyTypeObject *cls, PyObject *gr1, PyObject *gr2)
  296. { return Graph_bool_op (cls, LSUP_BOOL_SUBTRACTION, gr1, gr2); }
  297. static inline PyObject *Graph_bool_xor (
  298. PyTypeObject *cls, PyObject *gr1, PyObject *gr2)
  299. { return Graph_bool_op (cls, LSUP_BOOL_XOR, gr1, gr2); }
  300. static PyNumberMethods Graph_number_methods = {
  301. .nb_and = (binaryfunc) Graph_bool_and,
  302. .nb_or = (binaryfunc) Graph_bool_or,
  303. .nb_subtract = (binaryfunc) Graph_bool_subtract,
  304. .nb_xor = (binaryfunc) Graph_bool_xor,
  305. };
  306. static int
  307. Graph_contains (PyObject *self, PyObject *value)
  308. {
  309. if (!PyObject_TypeCheck (value, &TripleType)) {
  310. PyErr_SetString (PyExc_ValueError, "Error parsing input value.");
  311. return -1;
  312. }
  313. int rc = LSUP_graph_contains (
  314. ((GraphObject *) self)->ob_struct,
  315. ((TripleObject *) value)->ob_struct);
  316. return rc;
  317. }
  318. static Py_ssize_t
  319. Graph_get_size (PyObject *self)
  320. { return LSUP_graph_size (((GraphObject *) self)->ob_struct); }
  321. static PySequenceMethods Graph_seq_methods = {
  322. .sq_length = (lenfunc) Graph_get_size,
  323. .sq_contains = (objobjproc) Graph_contains,
  324. };
  325. PyTypeObject GraphType = {
  326. PyVarObject_HEAD_INIT(NULL, 0)
  327. .tp_name = "graph.Graph",
  328. .tp_doc = "RDF graph",
  329. .tp_basicsize = sizeof (GraphObject),
  330. .tp_itemsize = 0,
  331. .tp_flags = Py_TPFLAGS_DEFAULT,
  332. .tp_new = PyType_GenericNew,
  333. .tp_init = (initproc) Graph_init,
  334. .tp_dealloc = (destructor) Graph_dealloc,
  335. .tp_getset = Graph_getsetters,
  336. .tp_methods = Graph_methods,
  337. .tp_richcompare = (richcmpfunc) Graph_richcmp,
  338. .tp_as_number = &Graph_number_methods,
  339. .tp_as_sequence = &Graph_seq_methods,
  340. };
  341. #endif