py_graph.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648
  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. * Iterator helpers.
  11. */
  12. /*
  13. * String iterator for encoder output.
  14. *
  15. * Yields one string (one or more lines) at a time.
  16. */
  17. typedef struct {
  18. PyObject_HEAD
  19. LSUP_CodecIterator *it;
  20. unsigned char *line;
  21. } StringIteratorObject;
  22. static void
  23. StringIterator_dealloc (StringIteratorObject *it_obj)
  24. { it_obj->it->codec->encode_graph_done (it_obj->it); }
  25. static PyObject *
  26. StringIterator_next (StringIteratorObject *it_obj)
  27. {
  28. LSUP_rc rc = it_obj->it->codec->encode_graph_iter (
  29. it_obj->it, &it_obj->line);
  30. if (rc != LSUP_OK) {
  31. if (rc != LSUP_END)
  32. PyErr_SetString (PyExc_ValueError, "Error encoding graph.");
  33. // If not an error, this raises StopIteration.
  34. return NULL;
  35. }
  36. return PyUnicode_FromString ((char *) it_obj->line);
  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 iterator.
  56. *
  57. * Yields one triple at a time.
  58. */
  59. typedef struct {
  60. PyObject_HEAD
  61. LSUP_GraphIterator *it;
  62. LSUP_Triple *spo;
  63. } GraphIteratorObject;
  64. static void
  65. GraphIterator_dealloc (GraphIteratorObject *it_obj)
  66. {
  67. LSUP_graph_iter_free (it_obj->it);
  68. free (it_obj->spo);
  69. }
  70. static PyObject *
  71. GraphIterator_next (GraphIteratorObject *it_obj)
  72. {
  73. LSUP_rc rc = LSUP_graph_iter_next (it_obj->it, it_obj->spo);
  74. if (rc != LSUP_OK) {
  75. if (rc != LSUP_END)
  76. PyErr_SetString (PyExc_ValueError, "Error encoding graph.");
  77. // If not an error, this raises StopIteration.
  78. return NULL;
  79. }
  80. return build_triple (it_obj->spo);
  81. }
  82. /*
  83. * Graph iterator type.
  84. */
  85. PyTypeObject GraphIteratorType = {
  86. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  87. .tp_name = "graph.GraphIterator",
  88. .tp_basicsize = sizeof (GraphIteratorObject),
  89. .tp_itemsize = 0,
  90. .tp_flags = Py_TPFLAGS_DEFAULT,
  91. .tp_dealloc = (destructor) GraphIterator_dealloc,
  92. .tp_iter = PyObject_SelfIter,
  93. .tp_iternext = (iternextfunc) GraphIterator_next,
  94. };
  95. /*
  96. * Graph stuff.
  97. */
  98. typedef struct {
  99. PyObject_HEAD
  100. LSUP_Graph *ob_struct;
  101. } GraphObject;
  102. static int
  103. Graph_init (GraphObject *self, PyObject *args, PyObject *kwargs)
  104. {
  105. unsigned char store_type;
  106. PyObject *uri_obj = NULL;
  107. LSUP_Term *uri = NULL, *src_uri = NULL;
  108. static char *kwlist[] = {"", "uri_obj", NULL};
  109. if (!PyArg_ParseTupleAndKeywords (
  110. args, kwargs, "b|O", kwlist, &store_type, &uri_obj))
  111. return -1;
  112. if (uri_obj) {
  113. if (!PyObject_TypeCheck (uri_obj, &TermType)) {
  114. PyErr_SetString (PyExc_TypeError, "uri is not a Term type.");
  115. return -1;
  116. }
  117. src_uri = ((TermObject *) uri_obj)->ob_struct;
  118. uri = LSUP_iriref_new (src_uri->data, LSUP_iriref_nsm (src_uri));
  119. if (! LSUP_IS_IRI (uri)) {
  120. PyErr_SetString (PyExc_TypeError, "uri is not a IRIREF type.");
  121. return -1;
  122. }
  123. } else uri = LSUP_iriref_new (NULL, NULL);
  124. self->ob_struct = LSUP_graph_new (uri, (LSUP_store_type) store_type);
  125. if (!self->ob_struct) {
  126. PyErr_SetString (PyExc_ValueError, "Could not create graph.");
  127. return -1;
  128. }
  129. LSUP_Term *uri2 = LSUP_graph_uri (self->ob_struct);
  130. log_debug("Graph URI (%p): %s", uri2, uri2->data);
  131. return 0;
  132. }
  133. static void
  134. Graph_dealloc (GraphObject *self)
  135. {
  136. LSUP_graph_free (self->ob_struct);
  137. Py_TYPE (self)->tp_free ((PyObject *) self);
  138. }
  139. static PyObject *
  140. Graph_get_uri (GraphObject *self, void *closure)
  141. {
  142. LSUP_Term *uri = LSUP_graph_uri (self->ob_struct);
  143. log_debug("Graph URI address: %p", uri);
  144. log_debug("Graph URI: %s", uri->data);
  145. return PyUnicode_FromString (uri->data);
  146. }
  147. static int
  148. Graph_set_uri (GraphObject *self, PyObject *value, void *closure)
  149. {
  150. if (!PyObject_TypeCheck (value, &TermType)) {
  151. PyErr_SetString (PyExc_TypeError, "URI is not a Term type.");
  152. return -1;
  153. }
  154. LSUP_rc rc = LSUP_graph_set_uri (
  155. self->ob_struct, ((TermObject*)value)->ob_struct);
  156. return rc == LSUP_OK ? 0 : -1;
  157. }
  158. static PyGetSetDef Graph_getsetters[] = {
  159. {
  160. "uri", (getter) Graph_get_uri, (setter) Graph_set_uri,
  161. "Graph URI.", NULL
  162. },
  163. {NULL}
  164. };
  165. static PyObject *
  166. Graph_copy (PyTypeObject *cls, PyObject *src)
  167. {
  168. if (! PyObject_TypeCheck (src, cls)) return NULL;
  169. GraphObject *res = (GraphObject *) cls->tp_alloc(cls, 0);
  170. if (!res) return NULL;
  171. res->ob_struct = LSUP_graph_copy (((GraphObject *) src)->ob_struct);
  172. Py_INCREF(res);
  173. return (PyObject *) res;
  174. };
  175. static PyObject *
  176. Graph_store (PyObject *self)
  177. {
  178. GraphObject *dest_obj = (GraphObject *) Py_TYPE (self)->tp_alloc(
  179. Py_TYPE (self), 0);
  180. if (!dest_obj) return PyErr_NoMemory();
  181. LSUP_rc rc = LSUP_graph_store (
  182. ((GraphObject *) self)->ob_struct, &((dest_obj)->ob_struct), NULL);
  183. if (rc != LSUP_OK) {
  184. log_error (LSUP_strerror (rc));
  185. PyErr_SetString (PyExc_SystemError, "Error storing graph.");
  186. return NULL;
  187. };
  188. Py_INCREF (dest_obj);
  189. return (PyObject *)dest_obj;
  190. }
  191. static PyObject *
  192. Graph_new_from_rdf (PyTypeObject *cls, PyObject *args)
  193. {
  194. PyObject *buf, *fileno_fn, *fileno_obj;
  195. const char *type;
  196. if (! PyArg_ParseTuple (args, "Os", &buf, &type)) return NULL;
  197. // Get the file descriptor from the Python BufferedIO object.
  198. // FIXME This is not sure to be reliable. See
  199. // https://docs.python.org/3/library/io.html?highlight=io%20bufferedreader#io.IOBase.fileno
  200. if (! (fileno_fn = PyObject_GetAttrString (buf, "fileno"))) {
  201. PyErr_SetString (PyExc_TypeError, "Object has no fileno function.");
  202. return NULL;
  203. }
  204. PyObject* fileno_args = PyTuple_New(0);
  205. if (! (fileno_obj = PyObject_CallObject (fileno_fn, fileno_args))) {
  206. PyErr_SetString (PyExc_SystemError, "Error calling fileno function.");
  207. return NULL;
  208. }
  209. int fd = PyLong_AsSize_t (fileno_obj);
  210. /*
  211. * From the Linux man page:
  212. *
  213. * > The file descriptor is not dup'ed, and will be closed when the stream
  214. * > created by fdopen() is closed. The result of applying fdopen() to a
  215. * > shared memory object is undefined.
  216. *
  217. * Hence the `dup()`.
  218. */
  219. fd = dup (fd);
  220. FILE *fh = fdopen (fd, "r");
  221. GraphObject *res = (GraphObject *) cls->tp_alloc(cls, 0);
  222. if (!res) return PyErr_NoMemory();
  223. const LSUP_Codec *codec;
  224. if (strcmp(type, "nt") == 0) codec = &nt_codec;
  225. // TODO other codecs here.
  226. else {
  227. PyErr_SetString (PyExc_ValueError, "Unsupported codec.");
  228. return NULL;
  229. }
  230. size_t ct;
  231. char *err;
  232. codec->decode_graph (fh, &res->ob_struct, &ct, &err);
  233. fclose (fh);
  234. log_debug ("Decoded %lu triples.", ct);
  235. if (UNLIKELY (err)) {
  236. PyErr_SetString (PyExc_IOError, err);
  237. return NULL;
  238. }
  239. Py_INCREF (res);
  240. return (PyObject *) res;
  241. }
  242. /** @brief Build a triple pattern for lookup purposes.
  243. */
  244. inline static int build_trp_pattern (PyObject *args, LSUP_Term *spo[])
  245. {
  246. PyObject *s_obj, *p_obj, *o_obj;
  247. if (! (PyArg_ParseTuple (args, "OOO", &s_obj, &p_obj, &o_obj)))
  248. return -1;
  249. if (s_obj != Py_None && !PyObject_TypeCheck (s_obj, &TermType)) {
  250. PyErr_SetString (PyExc_TypeError, "Subject must be a term or None.");
  251. return -1;
  252. }
  253. if (p_obj != Py_None && !PyObject_TypeCheck (p_obj, &TermType)) {
  254. PyErr_SetString (PyExc_TypeError, "Predicate must be a term or None.");
  255. return -1;
  256. }
  257. if (o_obj != Py_None && !PyObject_TypeCheck (o_obj, &TermType)) {
  258. PyErr_SetString (PyExc_TypeError, "Object must be a term or None.");
  259. return -1;
  260. }
  261. spo[0] = s_obj != Py_None ? ((TermObject *)s_obj)->ob_struct : NULL;
  262. spo[1] = p_obj != Py_None ? ((TermObject *)p_obj)->ob_struct : NULL;
  263. spo[2] = o_obj != Py_None ? ((TermObject *)o_obj)->ob_struct : NULL;
  264. return 0;
  265. }
  266. static PyObject *
  267. Graph_new_set_from_store_lookup (PyTypeObject *cls, PyObject *args)
  268. {
  269. LSUP_Term *spo[3];
  270. if (UNLIKELY ((build_trp_pattern (args, spo)) < 0)) return NULL;
  271. LSUP_Graph **gr_a = LSUP_graph_new_lookup (spo[0], spo[1], spo[2]);
  272. if (UNLIKELY (!gr_a)) {
  273. // TODO implement LSUP_strerror for more details.
  274. PyErr_SetString (PyExc_SystemError, "Error looking up triples.");
  275. return NULL;
  276. }
  277. PyObject *ret = PySet_New (NULL);
  278. size_t i;
  279. for (i = 0; gr_a[i] != NULL; i++) {
  280. PyObject *gr_obj = cls->tp_alloc(cls, 0);
  281. if (!gr_obj) return NULL;
  282. ((GraphObject *) gr_obj)->ob_struct = gr_a[i];
  283. Py_INCREF (gr_obj);
  284. PySet_Add (ret, gr_obj);
  285. }
  286. log_debug ("Found %lu graphs for pattern.", i + 1);
  287. Py_INCREF (ret);
  288. return ret;
  289. }
  290. static PyObject *
  291. Graph_richcmp (PyObject *self, PyObject *other, int op)
  292. {
  293. // Only equality and non-equality are supported.
  294. if (op != Py_EQ && op != Py_NE) Py_RETURN_NOTIMPLEMENTED;
  295. LSUP_Graph *t1 = ((GraphObject *) self)->ob_struct;
  296. LSUP_Graph *t2 = ((GraphObject *) other)->ob_struct;
  297. if (LSUP_graph_equals (t1, t2) ^ (op == Py_NE)) Py_RETURN_TRUE;
  298. Py_RETURN_FALSE;
  299. }
  300. static inline PyObject *
  301. Graph_bool_op (
  302. PyTypeObject *cls, LSUP_bool_op op, PyObject *gr1, PyObject *gr2)
  303. {
  304. if (! PyObject_TypeCheck (gr1, cls) || ! PyObject_TypeCheck (gr2, cls))
  305. return NULL;
  306. GraphObject *res = (GraphObject *) cls->tp_alloc (cls, 0);
  307. if (!res) return NULL;
  308. res->ob_struct = LSUP_graph_bool_op (
  309. op, ((GraphObject *) gr1)->ob_struct,
  310. ((GraphObject *) gr2)->ob_struct);
  311. Py_INCREF(res);
  312. return (PyObject *) res;
  313. }
  314. static PyObject *
  315. Graph_add (PyObject *self, PyObject *triples)
  316. {
  317. // Triple may be any iterable.
  318. PyObject *iter = PyObject_GetIter (triples);
  319. if (! iter) {
  320. PyErr_SetString (
  321. PyExc_ValueError, "Triples object cannot be iterated.");
  322. return NULL;
  323. }
  324. PyObject *trp_obj;
  325. int rc = 0;
  326. size_t i;
  327. LSUP_GraphIterator *it = LSUP_graph_add_init (
  328. ((GraphObject *)self)->ob_struct);
  329. for (i = 0; (trp_obj = PyIter_Next (iter)); i++) {
  330. if (!PyObject_TypeCheck (trp_obj, &TripleType)) {
  331. PyErr_SetString (
  332. PyExc_ValueError, "Object is not a triple.");
  333. rc = -1;
  334. goto finally;
  335. }
  336. log_trace ("Inserting triple #%lu", i);
  337. LSUP_rc db_rc = LSUP_graph_add_iter (
  338. it, ((TripleObject *) trp_obj)->ob_struct);
  339. if (db_rc == LSUP_OK) rc = LSUP_OK;
  340. if (UNLIKELY (db_rc < 0)) {
  341. PyErr_SetString (
  342. PyExc_ValueError, "Unknown error while adding triples.");
  343. rc = -1;
  344. goto finally;
  345. }
  346. }
  347. finally:
  348. LSUP_graph_add_done (it);
  349. if (rc == LSUP_OK)
  350. return PyLong_FromSize_t (LSUP_graph_iter_cur (it));
  351. return NULL;
  352. }
  353. static PyObject *Graph_remove (PyObject *self, PyObject *args)
  354. {
  355. LSUP_rc rc;
  356. LSUP_Term *spo[3];
  357. rc = build_trp_pattern (args, spo);
  358. if (rc < 0) goto finally;
  359. size_t ct;
  360. rc = LSUP_graph_remove (
  361. ((GraphObject *)self)->ob_struct, spo[0], spo[1], spo[2], &ct);
  362. if (rc < 0) {
  363. // TODO implement strerror for more details.
  364. PyErr_SetString (PyExc_SystemError, "Error removing triples.");
  365. goto finally;
  366. }
  367. log_debug ("Removed %lu triples.", ct);
  368. finally:
  369. if (rc < 0) return NULL;
  370. Py_RETURN_NONE;
  371. }
  372. static PyObject *Graph_lookup (PyObject *self, PyObject *args)
  373. {
  374. LSUP_rc rc;
  375. GraphIteratorObject *it_obj = NULL;
  376. LSUP_Term *spo[3];
  377. rc = build_trp_pattern (args, spo);
  378. if (UNLIKELY (rc < 0)) goto finally;
  379. size_t ct;
  380. LSUP_GraphIterator *it = LSUP_graph_lookup (
  381. ((GraphObject *)self)->ob_struct, spo[0], spo[1], spo[2], &ct);
  382. if (UNLIKELY (!it)) {
  383. // TODO implement LSUP_strerror for more details.
  384. PyErr_SetString (PyExc_SystemError, "Error looking up triples.");
  385. rc = -1;
  386. goto finally;
  387. }
  388. log_debug ("Found %lu triples.", ct);
  389. // Initialize the generator object.
  390. it_obj = PyObject_New (
  391. GraphIteratorObject, &GraphIteratorType);
  392. if (UNLIKELY (!it_obj)) return PyErr_NoMemory();
  393. it_obj->it = it;
  394. it_obj->spo = TRP_DUMMY;
  395. Py_INCREF (it_obj);
  396. finally:
  397. return (PyObject *)it_obj;
  398. }
  399. static PyObject *
  400. Graph_encode (PyObject *self, PyObject *args)
  401. {
  402. const char *type;
  403. if (! PyArg_ParseTuple (args, "s", &type)) return NULL;
  404. const LSUP_Codec *codec;
  405. if (strcmp(type, "nt") == 0) codec = &nt_codec;
  406. // TODO other codecs here.
  407. else {
  408. PyErr_SetString (PyExc_ValueError, "Unsupported codec.");
  409. return NULL;
  410. }
  411. LSUP_CodecIterator *it = codec->encode_graph_init (
  412. ((GraphObject *)self)->ob_struct);
  413. // Initialize the generator object.
  414. StringIteratorObject *it_obj = PyObject_New (
  415. StringIteratorObject, &StringIteratorType);
  416. if (!it_obj) return NULL;
  417. it_obj->it = it;
  418. it_obj->line = NULL;
  419. Py_INCREF (it_obj);
  420. return (PyObject *)it_obj;
  421. }
  422. static PyMethodDef Graph_methods[] = {
  423. {
  424. "copy", (PyCFunction) Graph_copy, METH_CLASS | METH_VARARGS,
  425. "Copy a graph."
  426. },
  427. {
  428. "from_rdf", (PyCFunction) Graph_new_from_rdf,
  429. METH_CLASS | METH_VARARGS,
  430. "Create a graph from a RDF file."
  431. },
  432. {
  433. "from_lookup", (PyCFunction) Graph_new_set_from_store_lookup,
  434. METH_CLASS | METH_VARARGS,
  435. "Create a set of graphs from a store SPO lookup."
  436. },
  437. {
  438. "store", (PyCFunction) Graph_store, METH_NOARGS,
  439. "Store a graph into the permanent back end."
  440. },
  441. {"add", (PyCFunction) Graph_add, METH_O, "Add triples to a graph."},
  442. {
  443. "remove", (PyCFunction) Graph_remove, METH_VARARGS,
  444. "Remove triples from a graph by matching a pattern."
  445. },
  446. {
  447. "lookup", (PyCFunction) Graph_lookup, METH_VARARGS,
  448. "Look triples in a graph by matching a pattern."
  449. },
  450. {
  451. "to_rdf", (PyCFunction) Graph_encode, METH_VARARGS,
  452. "Encode a graph into a RDF byte buffer."
  453. },
  454. {NULL},
  455. };
  456. static inline PyObject *Graph_bool_and (
  457. PyTypeObject *cls, PyObject *gr1, PyObject *gr2)
  458. { return Graph_bool_op (cls, LSUP_BOOL_INTERSECTION, gr1, gr2); }
  459. static inline PyObject *Graph_bool_or (
  460. PyTypeObject *cls, PyObject *gr1, PyObject *gr2)
  461. { return Graph_bool_op (cls, LSUP_BOOL_UNION, gr1, gr2); }
  462. static inline PyObject *Graph_bool_subtract (
  463. PyTypeObject *cls, PyObject *gr1, PyObject *gr2)
  464. { return Graph_bool_op (cls, LSUP_BOOL_SUBTRACTION, gr1, gr2); }
  465. static inline PyObject *Graph_bool_xor (
  466. PyTypeObject *cls, PyObject *gr1, PyObject *gr2)
  467. { return Graph_bool_op (cls, LSUP_BOOL_XOR, gr1, gr2); }
  468. static PyNumberMethods Graph_number_methods = {
  469. .nb_and = (binaryfunc) Graph_bool_and,
  470. .nb_or = (binaryfunc) Graph_bool_or,
  471. .nb_subtract = (binaryfunc) Graph_bool_subtract,
  472. .nb_xor = (binaryfunc) Graph_bool_xor,
  473. };
  474. static int
  475. Graph_contains (PyObject *self, PyObject *value)
  476. {
  477. if (!PyObject_TypeCheck (value, &TripleType)) {
  478. PyErr_SetString (PyExc_ValueError, "Error parsing input value.");
  479. return -1;
  480. }
  481. int rc = LSUP_graph_contains (
  482. ((GraphObject *) self)->ob_struct,
  483. ((TripleObject *) value)->ob_struct);
  484. return rc;
  485. }
  486. static Py_ssize_t
  487. Graph_get_size (PyObject *self)
  488. { return LSUP_graph_size (((GraphObject *) self)->ob_struct); }
  489. static PySequenceMethods Graph_seq_methods = {
  490. .sq_length = (lenfunc) Graph_get_size,
  491. .sq_contains = (objobjproc) Graph_contains,
  492. };
  493. PyTypeObject GraphType = {
  494. PyVarObject_HEAD_INIT(NULL, 0)
  495. .tp_name = "graph.Graph",
  496. .tp_doc = "RDF graph",
  497. .tp_basicsize = sizeof (GraphObject),
  498. .tp_itemsize = 0,
  499. .tp_flags = Py_TPFLAGS_DEFAULT,
  500. .tp_new = PyType_GenericNew,
  501. .tp_init = (initproc) Graph_init,
  502. .tp_dealloc = (destructor) Graph_dealloc,
  503. .tp_getset = Graph_getsetters,
  504. .tp_methods = Graph_methods,
  505. .tp_richcompare = (richcmpfunc) Graph_richcmp,
  506. .tp_as_number = &Graph_number_methods,
  507. .tp_as_sequence = &Graph_seq_methods,
  508. };
  509. #endif