py_graph.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  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. /*
  267. static PyObject *
  268. Graph_new_set_from_store_lookup (PyTypeObject *cls, PyObject *args)
  269. {
  270. LSUP_Term *spo[3];
  271. if (UNLIKELY ((build_trp_pattern (args, spo)) < 0)) return NULL;
  272. LSUP_Graph **gr_a = LSUP_graph_new_lookup (spo[0], spo[1], spo[2]);
  273. if (UNLIKELY (!gr_a)) {
  274. // TODO implement LSUP_strerror for more details.
  275. PyErr_SetString (PyExc_SystemError, "Error looking up triples.");
  276. return NULL;
  277. }
  278. PyObject *ret = PySet_New (NULL);
  279. size_t i;
  280. for (i = 0; gr_a[i] != NULL; i++) {
  281. PyObject *gr_obj = cls->tp_alloc(cls, 0);
  282. if (!gr_obj) return NULL;
  283. ((GraphObject *) gr_obj)->ob_struct = gr_a[i];
  284. Py_INCREF (gr_obj);
  285. PySet_Add (ret, gr_obj);
  286. }
  287. log_debug ("Found %lu graphs for pattern.", i + 1);
  288. Py_INCREF (ret);
  289. return ret;
  290. }
  291. */
  292. static PyObject *
  293. Graph_richcmp (PyObject *self, PyObject *other, int op)
  294. {
  295. // Only equality and non-equality are supported.
  296. if (op != Py_EQ && op != Py_NE) Py_RETURN_NOTIMPLEMENTED;
  297. LSUP_Graph *t1 = ((GraphObject *) self)->ob_struct;
  298. LSUP_Graph *t2 = ((GraphObject *) other)->ob_struct;
  299. if (LSUP_graph_equals (t1, t2) ^ (op == Py_NE)) Py_RETURN_TRUE;
  300. Py_RETURN_FALSE;
  301. }
  302. static inline PyObject *
  303. Graph_bool_op (
  304. PyTypeObject *cls, LSUP_bool_op op, PyObject *gr1, PyObject *gr2)
  305. {
  306. if (! PyObject_TypeCheck (gr1, cls) || ! PyObject_TypeCheck (gr2, cls))
  307. return NULL;
  308. GraphObject *res = (GraphObject *) cls->tp_alloc (cls, 0);
  309. if (!res) return NULL;
  310. res->ob_struct = LSUP_graph_bool_op (
  311. op, ((GraphObject *) gr1)->ob_struct,
  312. ((GraphObject *) gr2)->ob_struct);
  313. Py_INCREF(res);
  314. return (PyObject *) res;
  315. }
  316. static PyObject *
  317. Graph_add (PyObject *self, PyObject *triples)
  318. {
  319. // Triple may be any iterable.
  320. PyObject *iter = PyObject_GetIter (triples);
  321. if (! iter) {
  322. PyErr_SetString (
  323. PyExc_ValueError, "Triples object cannot be iterated.");
  324. return NULL;
  325. }
  326. PyObject *trp_obj;
  327. int rc = 0;
  328. size_t ct = 0;
  329. LSUP_GraphIterator *it = LSUP_graph_add_init (
  330. ((GraphObject *)self)->ob_struct);
  331. while ((trp_obj = PyIter_Next (iter))) {
  332. if (!PyObject_TypeCheck (trp_obj, &TripleType)) {
  333. PyErr_SetString (
  334. PyExc_ValueError, "Object is not a triple.");
  335. rc = -1;
  336. goto finally;
  337. }
  338. log_trace ("Inserting triple #%lu", ct);
  339. LSUP_rc db_rc = LSUP_graph_add_iter (
  340. it, ((TripleObject *) trp_obj)->ob_struct);
  341. if (db_rc == LSUP_OK) {
  342. rc = LSUP_OK;
  343. ct++;
  344. } else if (UNLIKELY (db_rc < 0)) {
  345. PyErr_SetString (PyExc_ValueError, "Error while adding triples.");
  346. rc = -1;
  347. goto finally;
  348. }
  349. // If db_rc > 0, it's a no-op and the counter is not increased.
  350. }
  351. finally:
  352. LSUP_graph_add_done (it);
  353. if (rc == LSUP_OK) return PyLong_FromSize_t (ct);
  354. return NULL;
  355. }
  356. static PyObject *Graph_remove (PyObject *self, PyObject *args)
  357. {
  358. LSUP_rc rc;
  359. LSUP_Term *spo[3];
  360. rc = build_trp_pattern (args, spo);
  361. if (rc < 0) goto finally;
  362. size_t ct;
  363. rc = LSUP_graph_remove (
  364. ((GraphObject *)self)->ob_struct, spo[0], spo[1], spo[2], &ct);
  365. if (rc < 0) {
  366. // TODO implement strerror for more details.
  367. PyErr_SetString (PyExc_SystemError, "Error removing triples.");
  368. goto finally;
  369. }
  370. log_debug ("Removed %lu triples.", ct);
  371. finally:
  372. if (rc < 0) return NULL;
  373. Py_RETURN_NONE;
  374. }
  375. static PyObject *Graph_lookup (PyObject *self, PyObject *args)
  376. {
  377. LSUP_rc rc;
  378. GraphIteratorObject *it_obj = NULL;
  379. LSUP_Term *spo[3];
  380. rc = build_trp_pattern (args, spo);
  381. if (UNLIKELY (rc < 0)) goto finally;
  382. size_t ct;
  383. LSUP_GraphIterator *it = LSUP_graph_lookup (
  384. ((GraphObject *)self)->ob_struct, spo[0], spo[1], spo[2], &ct);
  385. if (UNLIKELY (!it)) {
  386. // TODO implement LSUP_strerror for more details.
  387. PyErr_SetString (PyExc_SystemError, "Error looking up triples.");
  388. rc = -1;
  389. goto finally;
  390. }
  391. log_debug ("Found %lu triples.", ct);
  392. // Initialize the generator object.
  393. it_obj = PyObject_New (
  394. GraphIteratorObject, &GraphIteratorType);
  395. if (UNLIKELY (!it_obj)) return PyErr_NoMemory();
  396. it_obj->it = it;
  397. it_obj->spo = TRP_DUMMY;
  398. Py_INCREF (it_obj);
  399. finally:
  400. return (PyObject *)it_obj;
  401. }
  402. static PyObject *
  403. Graph_encode (PyObject *self, PyObject *args)
  404. {
  405. const char *type;
  406. if (! PyArg_ParseTuple (args, "s", &type)) return NULL;
  407. const LSUP_Codec *codec;
  408. if (strcmp(type, "nt") == 0) codec = &nt_codec;
  409. // TODO other codecs here.
  410. else {
  411. PyErr_SetString (PyExc_ValueError, "Unsupported codec.");
  412. return NULL;
  413. }
  414. LSUP_CodecIterator *it = codec->encode_graph_init (
  415. ((GraphObject *)self)->ob_struct);
  416. // Initialize the generator object.
  417. StringIteratorObject *it_obj = PyObject_New (
  418. StringIteratorObject, &StringIteratorType);
  419. if (!it_obj) return NULL;
  420. it_obj->it = it;
  421. it_obj->line = NULL;
  422. Py_INCREF (it_obj);
  423. return (PyObject *)it_obj;
  424. }
  425. static PyMethodDef Graph_methods[] = {
  426. {
  427. "copy", (PyCFunction) Graph_copy, METH_CLASS | METH_VARARGS,
  428. "Copy a graph."
  429. },
  430. {
  431. "from_rdf", (PyCFunction) Graph_new_from_rdf,
  432. METH_CLASS | METH_VARARGS,
  433. "Create a graph from a RDF file."
  434. },
  435. /*
  436. {
  437. "from_lookup", (PyCFunction) Graph_new_set_from_store_lookup,
  438. METH_CLASS | METH_VARARGS,
  439. "Create a set of graphs from a store SPO lookup."
  440. },
  441. */
  442. {
  443. "store", (PyCFunction) Graph_store, METH_NOARGS,
  444. "Store a graph into the permanent back end."
  445. },
  446. {"add", (PyCFunction) Graph_add, METH_O, "Add triples to a graph."},
  447. {
  448. "remove", (PyCFunction) Graph_remove, METH_VARARGS,
  449. "Remove triples from a graph by matching a pattern."
  450. },
  451. {
  452. "lookup", (PyCFunction) Graph_lookup, METH_VARARGS,
  453. "Look triples in a graph by matching a pattern."
  454. },
  455. {
  456. "to_rdf", (PyCFunction) Graph_encode, METH_VARARGS,
  457. "Encode a graph into a RDF byte buffer."
  458. },
  459. {NULL},
  460. };
  461. static inline PyObject *Graph_bool_and (
  462. PyTypeObject *cls, PyObject *gr1, PyObject *gr2)
  463. { return Graph_bool_op (cls, LSUP_BOOL_INTERSECTION, gr1, gr2); }
  464. static inline PyObject *Graph_bool_or (
  465. PyTypeObject *cls, PyObject *gr1, PyObject *gr2)
  466. { return Graph_bool_op (cls, LSUP_BOOL_UNION, gr1, gr2); }
  467. static inline PyObject *Graph_bool_subtract (
  468. PyTypeObject *cls, PyObject *gr1, PyObject *gr2)
  469. { return Graph_bool_op (cls, LSUP_BOOL_SUBTRACTION, gr1, gr2); }
  470. static inline PyObject *Graph_bool_xor (
  471. PyTypeObject *cls, PyObject *gr1, PyObject *gr2)
  472. { return Graph_bool_op (cls, LSUP_BOOL_XOR, gr1, gr2); }
  473. static PyNumberMethods Graph_number_methods = {
  474. .nb_and = (binaryfunc) Graph_bool_and,
  475. .nb_or = (binaryfunc) Graph_bool_or,
  476. .nb_subtract = (binaryfunc) Graph_bool_subtract,
  477. .nb_xor = (binaryfunc) Graph_bool_xor,
  478. };
  479. static int
  480. Graph_contains (PyObject *self, PyObject *value)
  481. {
  482. if (!PyObject_TypeCheck (value, &TripleType)) {
  483. PyErr_SetString (PyExc_ValueError, "Error parsing input value.");
  484. return -1;
  485. }
  486. int rc = LSUP_graph_contains (
  487. ((GraphObject *) self)->ob_struct,
  488. ((TripleObject *) value)->ob_struct);
  489. return rc;
  490. }
  491. static Py_ssize_t
  492. Graph_get_size (PyObject *self)
  493. { return LSUP_graph_size (((GraphObject *) self)->ob_struct); }
  494. static PySequenceMethods Graph_seq_methods = {
  495. .sq_length = (lenfunc) Graph_get_size,
  496. .sq_contains = (objobjproc) Graph_contains,
  497. };
  498. PyTypeObject GraphType = {
  499. PyVarObject_HEAD_INIT(NULL, 0)
  500. .tp_name = "graph.Graph",
  501. .tp_doc = "RDF graph",
  502. .tp_basicsize = sizeof (GraphObject),
  503. .tp_itemsize = 0,
  504. .tp_flags = Py_TPFLAGS_DEFAULT,
  505. .tp_new = PyType_GenericNew,
  506. .tp_init = (initproc) Graph_init,
  507. .tp_dealloc = (destructor) Graph_dealloc,
  508. .tp_getset = Graph_getsetters,
  509. .tp_methods = Graph_methods,
  510. .tp_richcompare = (richcmpfunc) Graph_richcmp,
  511. .tp_as_number = &Graph_number_methods,
  512. .tp_as_sequence = &Graph_seq_methods,
  513. };
  514. #endif