py_graph.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653
  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_Term *gr_uri = ((TermObject*)value)->ob_struct;
  155. log_debug ("New graph URI: %s", (gr_uri->data));
  156. LSUP_rc rc = LSUP_graph_set_uri (self->ob_struct, LSUP_term_copy (gr_uri));
  157. return rc == LSUP_OK ? 0 : -1;
  158. }
  159. static PyGetSetDef Graph_getsetters[] = {
  160. {
  161. "uri", (getter) Graph_get_uri, (setter) Graph_set_uri,
  162. "Graph URI.", NULL
  163. },
  164. {NULL}
  165. };
  166. static PyObject *
  167. Graph_copy (PyTypeObject *cls, PyObject *src)
  168. {
  169. if (! PyObject_TypeCheck (src, cls)) return NULL;
  170. GraphObject *res = (GraphObject *) cls->tp_alloc(cls, 0);
  171. if (!res) return NULL;
  172. res->ob_struct = LSUP_graph_copy (((GraphObject *) src)->ob_struct);
  173. Py_INCREF(res);
  174. return (PyObject *) res;
  175. };
  176. static PyObject *
  177. Graph_store (PyObject *self)
  178. {
  179. GraphObject *dest_obj = (GraphObject *) Py_TYPE (self)->tp_alloc(
  180. Py_TYPE (self), 0);
  181. if (!dest_obj) return PyErr_NoMemory();
  182. LSUP_rc rc = LSUP_graph_store (
  183. ((GraphObject *) self)->ob_struct, &((dest_obj)->ob_struct), NULL);
  184. if (rc != LSUP_OK) {
  185. log_error (LSUP_strerror (rc));
  186. PyErr_SetString (PyExc_SystemError, "Error storing graph.");
  187. return NULL;
  188. };
  189. Py_INCREF (dest_obj);
  190. return (PyObject *)dest_obj;
  191. }
  192. static PyObject *
  193. Graph_new_from_rdf (PyTypeObject *cls, PyObject *args)
  194. {
  195. PyObject *buf, *fileno_fn, *fileno_obj;
  196. const char *type;
  197. if (! PyArg_ParseTuple (args, "Os", &buf, &type)) return NULL;
  198. // Get the file descriptor from the Python BufferedIO object.
  199. // FIXME This is not sure to be reliable. See
  200. // https://docs.python.org/3/library/io.html?highlight=io%20bufferedreader#io.IOBase.fileno
  201. if (! (fileno_fn = PyObject_GetAttrString (buf, "fileno"))) {
  202. PyErr_SetString (PyExc_TypeError, "Object has no fileno function.");
  203. return NULL;
  204. }
  205. PyObject* fileno_args = PyTuple_New(0);
  206. if (! (fileno_obj = PyObject_CallObject (fileno_fn, fileno_args))) {
  207. PyErr_SetString (PyExc_SystemError, "Error calling fileno function.");
  208. return NULL;
  209. }
  210. int fd = PyLong_AsSize_t (fileno_obj);
  211. /*
  212. * From the Linux man page:
  213. *
  214. * > The file descriptor is not dup'ed, and will be closed when the stream
  215. * > created by fdopen() is closed. The result of applying fdopen() to a
  216. * > shared memory object is undefined.
  217. *
  218. * Hence the `dup()`.
  219. */
  220. fd = dup (fd);
  221. FILE *fh = fdopen (fd, "r");
  222. GraphObject *res = (GraphObject *) cls->tp_alloc(cls, 0);
  223. if (!res) return PyErr_NoMemory();
  224. const LSUP_Codec *codec;
  225. if (strcmp(type, "nt") == 0) codec = &nt_codec;
  226. // TODO other codecs here.
  227. else {
  228. PyErr_SetString (PyExc_ValueError, "Unsupported codec.");
  229. return NULL;
  230. }
  231. size_t ct;
  232. char *err;
  233. codec->decode_graph (fh, &res->ob_struct, &ct, &err);
  234. fclose (fh);
  235. log_debug ("Decoded %lu triples.", ct);
  236. if (UNLIKELY (err)) {
  237. PyErr_SetString (PyExc_IOError, err);
  238. return NULL;
  239. }
  240. Py_INCREF (res);
  241. return (PyObject *) res;
  242. }
  243. /** @brief Build a triple pattern for lookup purposes.
  244. */
  245. inline static int build_trp_pattern (PyObject *args, LSUP_Term *spo[])
  246. {
  247. PyObject *s_obj, *p_obj, *o_obj;
  248. if (! (PyArg_ParseTuple (args, "OOO", &s_obj, &p_obj, &o_obj)))
  249. return -1;
  250. if (s_obj != Py_None && !PyObject_TypeCheck (s_obj, &TermType)) {
  251. PyErr_SetString (PyExc_TypeError, "Subject must be a term or None.");
  252. return -1;
  253. }
  254. if (p_obj != Py_None && !PyObject_TypeCheck (p_obj, &TermType)) {
  255. PyErr_SetString (PyExc_TypeError, "Predicate must be a term or None.");
  256. return -1;
  257. }
  258. if (o_obj != Py_None && !PyObject_TypeCheck (o_obj, &TermType)) {
  259. PyErr_SetString (PyExc_TypeError, "Object must be a term or None.");
  260. return -1;
  261. }
  262. spo[0] = s_obj != Py_None ? ((TermObject *)s_obj)->ob_struct : NULL;
  263. spo[1] = p_obj != Py_None ? ((TermObject *)p_obj)->ob_struct : NULL;
  264. spo[2] = o_obj != Py_None ? ((TermObject *)o_obj)->ob_struct : NULL;
  265. return 0;
  266. }
  267. /*
  268. static PyObject *
  269. Graph_new_set_from_store_lookup (PyTypeObject *cls, PyObject *args)
  270. {
  271. LSUP_Term *spo[3];
  272. if (UNLIKELY ((build_trp_pattern (args, spo)) < 0)) return NULL;
  273. LSUP_Graph **gr_a = LSUP_graph_new_lookup (spo[0], spo[1], spo[2]);
  274. if (UNLIKELY (!gr_a)) {
  275. // TODO implement LSUP_strerror for more details.
  276. PyErr_SetString (PyExc_SystemError, "Error looking up triples.");
  277. return NULL;
  278. }
  279. PyObject *ret = PySet_New (NULL);
  280. size_t i;
  281. for (i = 0; gr_a[i] != NULL; i++) {
  282. PyObject *gr_obj = cls->tp_alloc(cls, 0);
  283. if (!gr_obj) return NULL;
  284. ((GraphObject *) gr_obj)->ob_struct = gr_a[i];
  285. Py_INCREF (gr_obj);
  286. PySet_Add (ret, gr_obj);
  287. }
  288. log_debug ("Found %lu graphs for pattern.", i + 1);
  289. Py_INCREF (ret);
  290. return ret;
  291. }
  292. */
  293. static PyObject *
  294. Graph_richcmp (PyObject *self, PyObject *other, int op)
  295. {
  296. // Only equality and non-equality are supported.
  297. if (op != Py_EQ && op != Py_NE) Py_RETURN_NOTIMPLEMENTED;
  298. LSUP_Graph *t1 = ((GraphObject *) self)->ob_struct;
  299. LSUP_Graph *t2 = ((GraphObject *) other)->ob_struct;
  300. if (LSUP_graph_equals (t1, t2) ^ (op == Py_NE)) Py_RETURN_TRUE;
  301. Py_RETURN_FALSE;
  302. }
  303. static inline PyObject *
  304. Graph_bool_op (
  305. PyTypeObject *cls, LSUP_bool_op op, PyObject *gr1, PyObject *gr2)
  306. {
  307. if (! PyObject_TypeCheck (gr1, cls) || ! PyObject_TypeCheck (gr2, cls))
  308. return NULL;
  309. GraphObject *res = (GraphObject *) cls->tp_alloc (cls, 0);
  310. if (!res) return NULL;
  311. res->ob_struct = LSUP_graph_bool_op (
  312. op, ((GraphObject *) gr1)->ob_struct,
  313. ((GraphObject *) gr2)->ob_struct);
  314. Py_INCREF(res);
  315. return (PyObject *) res;
  316. }
  317. static PyObject *
  318. Graph_add (PyObject *self, PyObject *triples)
  319. {
  320. // Triple may be any iterable.
  321. PyObject *iter = PyObject_GetIter (triples);
  322. if (! iter) {
  323. PyErr_SetString (
  324. PyExc_ValueError, "Triples object cannot be iterated.");
  325. return NULL;
  326. }
  327. PyObject *trp_obj;
  328. int rc = 0;
  329. size_t ct = 0;
  330. LSUP_GraphIterator *it = LSUP_graph_add_init (
  331. ((GraphObject *)self)->ob_struct);
  332. while ((trp_obj = PyIter_Next (iter))) {
  333. if (!PyObject_TypeCheck (trp_obj, &TripleType)) {
  334. PyErr_SetString (
  335. PyExc_ValueError, "Object is not a triple.");
  336. rc = -1;
  337. goto finally;
  338. }
  339. log_trace ("Inserting triple #%lu", ct);
  340. LSUP_rc db_rc = LSUP_graph_add_iter (
  341. it, ((TripleObject *) trp_obj)->ob_struct);
  342. if (db_rc == LSUP_OK) {
  343. rc = LSUP_OK;
  344. ct++;
  345. } else if (UNLIKELY (db_rc < 0)) {
  346. PyErr_SetString (PyExc_ValueError, "Error while adding triples.");
  347. rc = -1;
  348. goto finally;
  349. }
  350. // If db_rc > 0, it's a no-op and the counter is not increased.
  351. }
  352. finally:
  353. LSUP_graph_add_done (it);
  354. if (rc == LSUP_OK) return PyLong_FromSize_t (ct);
  355. return NULL;
  356. }
  357. static PyObject *Graph_remove (PyObject *self, PyObject *args)
  358. {
  359. LSUP_rc rc;
  360. LSUP_Term *spo[3];
  361. rc = build_trp_pattern (args, spo);
  362. if (rc < 0) goto finally;
  363. size_t ct;
  364. rc = LSUP_graph_remove (
  365. ((GraphObject *)self)->ob_struct, spo[0], spo[1], spo[2], &ct);
  366. if (rc < 0) {
  367. // TODO implement strerror for more details.
  368. PyErr_SetString (PyExc_SystemError, "Error removing triples.");
  369. goto finally;
  370. }
  371. log_debug ("Removed %lu triples.", ct);
  372. finally:
  373. if (rc < 0) return NULL;
  374. Py_RETURN_NONE;
  375. }
  376. static PyObject *Graph_lookup (PyObject *self, PyObject *args)
  377. {
  378. LSUP_rc rc;
  379. GraphIteratorObject *it_obj = NULL;
  380. LSUP_Term *spo[3];
  381. rc = build_trp_pattern (args, spo);
  382. if (UNLIKELY (rc < 0)) goto finally;
  383. size_t ct;
  384. LSUP_GraphIterator *it = LSUP_graph_lookup (
  385. ((GraphObject *)self)->ob_struct, spo[0], spo[1], spo[2], &ct);
  386. if (UNLIKELY (!it)) {
  387. // TODO implement LSUP_strerror for more details.
  388. PyErr_SetString (PyExc_SystemError, "Error looking up triples.");
  389. rc = -1;
  390. goto finally;
  391. }
  392. log_debug ("Found %lu triples.", ct);
  393. // Initialize the generator object.
  394. it_obj = PyObject_New (
  395. GraphIteratorObject, &GraphIteratorType);
  396. if (UNLIKELY (!it_obj)) return PyErr_NoMemory();
  397. it_obj->it = it;
  398. it_obj->spo = TRP_DUMMY;
  399. Py_INCREF (it_obj);
  400. finally:
  401. return (PyObject *)it_obj;
  402. }
  403. static PyObject *
  404. Graph_encode (PyObject *self, PyObject *args)
  405. {
  406. const char *type;
  407. if (! PyArg_ParseTuple (args, "s", &type)) return NULL;
  408. const LSUP_Codec *codec;
  409. if (strcmp(type, "nt") == 0) codec = &nt_codec;
  410. // TODO other codecs here.
  411. else {
  412. PyErr_SetString (PyExc_ValueError, "Unsupported codec.");
  413. return NULL;
  414. }
  415. LSUP_CodecIterator *it = codec->encode_graph_init (
  416. ((GraphObject *)self)->ob_struct);
  417. // Initialize the generator object.
  418. StringIteratorObject *it_obj = PyObject_New (
  419. StringIteratorObject, &StringIteratorType);
  420. if (!it_obj) return NULL;
  421. it_obj->it = it;
  422. it_obj->line = NULL;
  423. Py_INCREF (it_obj);
  424. return (PyObject *)it_obj;
  425. }
  426. static PyMethodDef Graph_methods[] = {
  427. {
  428. "copy", (PyCFunction) Graph_copy, METH_CLASS | METH_VARARGS,
  429. "Copy a graph."
  430. },
  431. {
  432. "from_rdf", (PyCFunction) Graph_new_from_rdf,
  433. METH_CLASS | METH_VARARGS,
  434. "Create a graph from a RDF file."
  435. },
  436. /*
  437. {
  438. "from_lookup", (PyCFunction) Graph_new_set_from_store_lookup,
  439. METH_CLASS | METH_VARARGS,
  440. "Create a set of graphs from a store SPO lookup."
  441. },
  442. */
  443. {
  444. "store", (PyCFunction) Graph_store, METH_NOARGS,
  445. "Store a graph into the permanent back end."
  446. },
  447. {"add", (PyCFunction) Graph_add, METH_O, "Add triples to a graph."},
  448. {
  449. "remove", (PyCFunction) Graph_remove, METH_VARARGS,
  450. "Remove triples from a graph by matching a pattern."
  451. },
  452. {
  453. "lookup", (PyCFunction) Graph_lookup, METH_VARARGS,
  454. "Look triples in a graph by matching a pattern."
  455. },
  456. {
  457. "to_rdf", (PyCFunction) Graph_encode, METH_VARARGS,
  458. "Encode a graph into a RDF byte buffer."
  459. },
  460. {NULL},
  461. };
  462. static inline PyObject *Graph_bool_and (
  463. PyTypeObject *cls, PyObject *gr1, PyObject *gr2)
  464. { return Graph_bool_op (cls, LSUP_BOOL_INTERSECTION, gr1, gr2); }
  465. static inline PyObject *Graph_bool_or (
  466. PyTypeObject *cls, PyObject *gr1, PyObject *gr2)
  467. { return Graph_bool_op (cls, LSUP_BOOL_UNION, gr1, gr2); }
  468. static inline PyObject *Graph_bool_subtract (
  469. PyTypeObject *cls, PyObject *gr1, PyObject *gr2)
  470. { return Graph_bool_op (cls, LSUP_BOOL_SUBTRACTION, gr1, gr2); }
  471. static inline PyObject *Graph_bool_xor (
  472. PyTypeObject *cls, PyObject *gr1, PyObject *gr2)
  473. { return Graph_bool_op (cls, LSUP_BOOL_XOR, gr1, gr2); }
  474. static PyNumberMethods Graph_number_methods = {
  475. .nb_and = (binaryfunc) Graph_bool_and,
  476. .nb_or = (binaryfunc) Graph_bool_or,
  477. .nb_subtract = (binaryfunc) Graph_bool_subtract,
  478. .nb_xor = (binaryfunc) Graph_bool_xor,
  479. };
  480. static int
  481. Graph_contains (PyObject *self, PyObject *value)
  482. {
  483. if (!PyObject_TypeCheck (value, &TripleType)) {
  484. PyErr_SetString (PyExc_ValueError, "Error parsing input value.");
  485. return -1;
  486. }
  487. int rc = LSUP_graph_contains (
  488. ((GraphObject *) self)->ob_struct,
  489. ((TripleObject *) value)->ob_struct);
  490. return rc;
  491. }
  492. static Py_ssize_t
  493. Graph_get_size (PyObject *self)
  494. { return LSUP_graph_size (((GraphObject *) self)->ob_struct); }
  495. static PySequenceMethods Graph_seq_methods = {
  496. .sq_length = (lenfunc) Graph_get_size,
  497. .sq_contains = (objobjproc) Graph_contains,
  498. };
  499. PyTypeObject GraphType = {
  500. PyVarObject_HEAD_INIT(NULL, 0)
  501. .tp_name = "graph.Graph",
  502. .tp_doc = "RDF graph",
  503. .tp_basicsize = sizeof (GraphObject),
  504. .tp_itemsize = 0,
  505. .tp_flags = Py_TPFLAGS_DEFAULT,
  506. .tp_new = PyType_GenericNew,
  507. .tp_init = (initproc) Graph_init,
  508. .tp_dealloc = (destructor) Graph_dealloc,
  509. .tp_getset = Graph_getsetters,
  510. .tp_methods = Graph_methods,
  511. .tp_richcompare = (richcmpfunc) Graph_richcmp,
  512. .tp_as_number = &Graph_number_methods,
  513. .tp_as_sequence = &Graph_seq_methods,
  514. };
  515. #endif