py_graph.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  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 = NULL;
  310. int rc = 0;
  311. size_t i;
  312. LSUP_SerTriple *sspo = LSUP_striple_new (BUF_DUMMY, BUF_DUMMY, BUF_DUMMY);
  313. LSUP_GraphIterator *it = LSUP_graph_add_init (
  314. ((GraphObject *)self)->ob_struct);
  315. for (i = 0; (trp_obj = PyIter_Next (iter)); i++) {
  316. if (!PyObject_TypeCheck (trp_obj, &TripleType)) {
  317. PyErr_SetString (
  318. PyExc_ValueError, "Object is not a triple.");
  319. rc = -1;
  320. goto finalize;
  321. }
  322. log_trace ("Inserting triple #%lu", i);
  323. LSUP_triple_serialize (((TripleObject *)trp_obj)->ob_struct, sspo);
  324. LSUP_rc db_rc = LSUP_graph_add_iter (it, sspo);
  325. if (db_rc == LSUP_OK) rc = LSUP_OK;
  326. if (UNLIKELY (db_rc < 0)) {
  327. rc = -1;
  328. goto finalize;
  329. }
  330. }
  331. finalize:
  332. LSUP_graph_add_done (it);
  333. LSUP_striple_free (sspo);
  334. PyObject *ret = PyLong_FromSize_t (LSUP_graph_iter_cur (it));
  335. if (rc == 0) {
  336. Py_INCREF (ret);
  337. return ret;
  338. }
  339. return NULL;
  340. }
  341. static PyObject *Graph_remove (PyObject *self, PyObject *args)
  342. {
  343. LSUP_rc rc;
  344. LSUP_Term *spo[3];
  345. rc = build_trp_pattern (args, spo);
  346. if (rc < 0) goto finally;
  347. size_t ct;
  348. rc = LSUP_graph_remove (
  349. ((GraphObject *)self)->ob_struct, spo[0], spo[1], spo[2], &ct);
  350. if (rc < 0) {
  351. // TODO implement strerror for more details.
  352. PyErr_SetString (PyExc_SystemError, "Error removing triples.");
  353. goto finally;
  354. }
  355. log_debug ("Removed %lu triples.", ct);
  356. finally:
  357. if (rc < 0) return NULL;
  358. Py_RETURN_NONE;
  359. }
  360. static PyObject *Graph_lookup (PyObject *self, PyObject *args)
  361. {
  362. LSUP_rc rc;
  363. GraphIteratorObject *it_obj = NULL;
  364. LSUP_Term *spo[3];
  365. rc = build_trp_pattern (args, spo);
  366. if (UNLIKELY (rc < 0)) goto finally;
  367. size_t ct;
  368. LSUP_GraphIterator *it = LSUP_graph_lookup (
  369. ((GraphObject *)self)->ob_struct, spo[0], spo[1], spo[2], &ct);
  370. if (UNLIKELY (!it)) {
  371. // TODO implement LSUP_strerror for more details.
  372. PyErr_SetString (PyExc_SystemError, "Error looking up triples.");
  373. rc = -1;
  374. goto finally;
  375. }
  376. log_debug ("Found %lu triples.", ct);
  377. // Initialize the generator object.
  378. it_obj = PyObject_New (
  379. GraphIteratorObject, &GraphIteratorType);
  380. if (UNLIKELY (!it_obj)) goto finally;
  381. it_obj->it = it;
  382. it_obj->spo = TRP_DUMMY;
  383. Py_INCREF (it_obj);
  384. finally:
  385. return (PyObject *)it_obj;
  386. }
  387. static PyObject *
  388. Graph_encode (PyObject *self, PyObject *args)
  389. {
  390. const char *type;
  391. if (! PyArg_ParseTuple (args, "s", &type)) return NULL;
  392. const LSUP_Codec *codec;
  393. if (strcmp(type, "nt") == 0) codec = &nt_codec;
  394. // TODO other codecs here.
  395. else {
  396. PyErr_SetString (PyExc_ValueError, "Unsupported codec.");
  397. return NULL;
  398. }
  399. LSUP_CodecIterator *it = codec->encode_graph_init (
  400. ((GraphObject *)self)->ob_struct);
  401. // Initialize the generator object.
  402. StringIteratorObject *it_obj = PyObject_New (
  403. StringIteratorObject, &StringIteratorType);
  404. if (!it_obj) return NULL;
  405. it_obj->it = it;
  406. it_obj->line = NULL;
  407. Py_INCREF (it_obj);
  408. return (PyObject *)it_obj;
  409. }
  410. static PyMethodDef Graph_methods[] = {
  411. {
  412. "copy", (PyCFunction) Graph_copy, METH_CLASS | METH_VARARGS,
  413. "Copy a graph."
  414. },
  415. {
  416. "from_rdf", (PyCFunction) Graph_new_from_rdf,
  417. METH_CLASS | METH_VARARGS,
  418. "Create a graph from a RDF file."
  419. },
  420. {
  421. "from_lookup", (PyCFunction) Graph_new_set_from_store_lookup,
  422. METH_CLASS | METH_VARARGS,
  423. "Create a set of graphs from a store SPO lookup."
  424. },
  425. {
  426. "store", (PyCFunction) Graph_store, METH_NOARGS,
  427. "Store a graph into the permanent back end."
  428. },
  429. {"add", (PyCFunction) Graph_add, METH_O, "Add triples to a graph."},
  430. {
  431. "remove", (PyCFunction) Graph_remove, METH_VARARGS,
  432. "Remove triples from a graph by matching a pattern."
  433. },
  434. {
  435. "lookup", (PyCFunction) Graph_lookup, METH_VARARGS,
  436. "Look triples in a graph by matching a pattern."
  437. },
  438. {
  439. "to_rdf", (PyCFunction) Graph_encode, METH_VARARGS,
  440. "Encode a graph into a RDF byte buffer."
  441. },
  442. {NULL},
  443. };
  444. static inline PyObject *Graph_bool_and (
  445. PyTypeObject *cls, PyObject *gr1, PyObject *gr2)
  446. { return Graph_bool_op (cls, LSUP_BOOL_INTERSECTION, gr1, gr2); }
  447. static inline PyObject *Graph_bool_or (
  448. PyTypeObject *cls, PyObject *gr1, PyObject *gr2)
  449. { return Graph_bool_op (cls, LSUP_BOOL_UNION, gr1, gr2); }
  450. static inline PyObject *Graph_bool_subtract (
  451. PyTypeObject *cls, PyObject *gr1, PyObject *gr2)
  452. { return Graph_bool_op (cls, LSUP_BOOL_SUBTRACTION, gr1, gr2); }
  453. static inline PyObject *Graph_bool_xor (
  454. PyTypeObject *cls, PyObject *gr1, PyObject *gr2)
  455. { return Graph_bool_op (cls, LSUP_BOOL_XOR, gr1, gr2); }
  456. static PyNumberMethods Graph_number_methods = {
  457. .nb_and = (binaryfunc) Graph_bool_and,
  458. .nb_or = (binaryfunc) Graph_bool_or,
  459. .nb_subtract = (binaryfunc) Graph_bool_subtract,
  460. .nb_xor = (binaryfunc) Graph_bool_xor,
  461. };
  462. static int
  463. Graph_contains (PyObject *self, PyObject *value)
  464. {
  465. if (!PyObject_TypeCheck (value, &TripleType)) {
  466. PyErr_SetString (PyExc_ValueError, "Error parsing input value.");
  467. return -1;
  468. }
  469. int rc = LSUP_graph_contains (
  470. ((GraphObject *) self)->ob_struct,
  471. ((TripleObject *) value)->ob_struct);
  472. return rc;
  473. }
  474. static Py_ssize_t
  475. Graph_get_size (PyObject *self)
  476. { return LSUP_graph_size (((GraphObject *) self)->ob_struct); }
  477. static PySequenceMethods Graph_seq_methods = {
  478. .sq_length = (lenfunc) Graph_get_size,
  479. .sq_contains = (objobjproc) Graph_contains,
  480. };
  481. PyTypeObject GraphType = {
  482. PyVarObject_HEAD_INIT(NULL, 0)
  483. .tp_name = "graph.Graph",
  484. .tp_doc = "RDF graph",
  485. .tp_basicsize = sizeof (GraphObject),
  486. .tp_itemsize = 0,
  487. .tp_flags = Py_TPFLAGS_DEFAULT,
  488. .tp_new = PyType_GenericNew,
  489. .tp_init = (initproc) Graph_init,
  490. .tp_dealloc = (destructor) Graph_dealloc,
  491. .tp_getset = Graph_getsetters,
  492. .tp_methods = Graph_methods,
  493. .tp_richcompare = (richcmpfunc) Graph_richcmp,
  494. .tp_as_number = &Graph_number_methods,
  495. .tp_as_sequence = &Graph_seq_methods,
  496. };
  497. #endif