py_graph.h 16 KB

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