py_graph.h 16 KB

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