py_graph.h 17 KB

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