py_graph.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  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)) return -1;
  137. LSUP_rc rc = LSUP_graph_set_uri (
  138. self->ob_struct, ((TermObject*)value)->ob_struct->data);
  139. return rc == LSUP_OK ? 0 : -1;
  140. }
  141. static PyGetSetDef Graph_getsetters[] = {
  142. {
  143. "uri", (getter) Graph_get_uri, (setter) Graph_set_uri,
  144. "Graph URI.", NULL
  145. },
  146. {NULL}
  147. };
  148. static PyObject *
  149. Graph_copy (PyTypeObject *cls, PyObject *src)
  150. {
  151. if (! PyObject_TypeCheck (src, cls)) return NULL;
  152. GraphObject *res = (GraphObject *) cls->tp_alloc(cls, 0);
  153. if (!res) return NULL;
  154. res->ob_struct = LSUP_graph_copy (((GraphObject *) src)->ob_struct);
  155. Py_INCREF(res);
  156. return (PyObject *) res;
  157. };
  158. static PyObject *
  159. Graph_store (PyObject *self)
  160. {
  161. /*
  162. PyObject *dest_obj = PyObject_CallFunction (self, "b", LSUP_STORE_MDB);
  163. if (UNLIKELY (!dest_obj)) {
  164. PyErr_SetString (PyExc_SystemError, "Error Creating stored graph.");
  165. return NULL;
  166. }
  167. */
  168. GraphObject *dest_obj = (GraphObject *) Py_TYPE (self)->tp_alloc(
  169. Py_TYPE (self), 0);
  170. if (!dest_obj) return PyErr_NoMemory();
  171. LSUP_rc rc = LSUP_graph_store (
  172. ((GraphObject *) self)->ob_struct, &((dest_obj)->ob_struct), NULL);
  173. if (rc != LSUP_OK) {
  174. log_error (LSUP_strerror (rc));
  175. PyErr_SetString (PyExc_SystemError, "Error storing graph.");
  176. return NULL;
  177. };
  178. Py_INCREF (dest_obj);
  179. return (PyObject *)dest_obj;
  180. }
  181. static PyObject *
  182. Graph_new_from_rdf (PyTypeObject *cls, PyObject *args)
  183. {
  184. PyObject *buf, *fileno_fn, *fileno_obj;
  185. const char *type;
  186. if (! PyArg_ParseTuple (args, "Os", &buf, &type)) return NULL;
  187. // Get the file descriptor from the Python BufferedIO object.
  188. // FIXME This is not sure to be reliable. See
  189. // https://docs.python.org/3/library/io.html?highlight=io%20bufferedreader#io.IOBase.fileno
  190. if (! (fileno_fn = PyObject_GetAttrString (buf, "fileno"))) {
  191. PyErr_SetString (PyExc_TypeError, "Object has no fileno function.");
  192. return NULL;
  193. }
  194. PyObject* fileno_args = PyTuple_New(0);
  195. if (! (fileno_obj = PyObject_CallObject (fileno_fn, fileno_args))) {
  196. PyErr_SetString (PyExc_SystemError, "Error calling fileno function.");
  197. return NULL;
  198. }
  199. int fd = PyLong_AsSize_t (fileno_obj);
  200. /*
  201. * From the Linux man page:
  202. *
  203. * > The file descriptor is not dup'ed, and will be closed when the stream
  204. * > created by fdopen() is closed. The result of applying fdopen() to a
  205. * > shared memory object is undefined.
  206. *
  207. * This handle must not be closed. Leave open for the Python caller to
  208. * handle it.
  209. */
  210. FILE *fh = fdopen (fd, "r");
  211. GraphObject *res = (GraphObject *) cls->tp_alloc(cls, 0);
  212. if (!res) return PyErr_NoMemory();
  213. const LSUP_Codec *codec;
  214. if (strcmp(type, "nt") == 0) codec = &nt_codec;
  215. // TODO other codecs here.
  216. else {
  217. PyErr_SetString (PyExc_ValueError, "Unsupported codec.");
  218. return NULL;
  219. }
  220. size_t ct;
  221. char *err;
  222. codec->decode_graph (fh, &res->ob_struct, &ct, &err);
  223. log_debug ("Decoded %lu triples.", ct);
  224. if (UNLIKELY (err)) {
  225. PyErr_SetString (PyExc_IOError, err);
  226. return NULL;
  227. }
  228. Py_INCREF(res);
  229. return (PyObject *) res;
  230. }
  231. static PyObject *
  232. Graph_richcmp (PyObject *self, PyObject *other, int op)
  233. {
  234. // Only equality and non-equality are supported.
  235. if (op != Py_EQ && op != Py_NE) Py_RETURN_NOTIMPLEMENTED;
  236. LSUP_Graph *t1 = ((GraphObject *) self)->ob_struct;
  237. LSUP_Graph *t2 = ((GraphObject *) other)->ob_struct;
  238. if (LSUP_graph_equals (t1, t2) ^ (op == Py_NE)) Py_RETURN_TRUE;
  239. Py_RETURN_FALSE;
  240. }
  241. static inline PyObject *
  242. Graph_bool_op (
  243. PyTypeObject *cls, LSUP_bool_op op, PyObject *gr1, PyObject *gr2)
  244. {
  245. if (! PyObject_TypeCheck (gr1, cls) || ! PyObject_TypeCheck (gr2, cls))
  246. return NULL;
  247. GraphObject *res = (GraphObject *) cls->tp_alloc (cls, 0);
  248. if (!res) return NULL;
  249. res->ob_struct = LSUP_graph_bool_op (
  250. op, ((GraphObject *) gr1)->ob_struct,
  251. ((GraphObject *) gr2)->ob_struct);
  252. Py_INCREF(res);
  253. return (PyObject *) res;
  254. }
  255. static PyObject *
  256. Graph_add (PyObject *self, PyObject *triples)
  257. {
  258. // Triple may be any iterable.
  259. PyObject *iter = PyObject_GetIter (triples);
  260. if (! iter) {
  261. PyErr_SetString (
  262. PyExc_ValueError, "Triples object cannot be iterated.");
  263. return NULL;
  264. }
  265. PyObject *trp_obj = NULL;
  266. int rc = 0;
  267. size_t i;
  268. LSUP_SerTriple *sspo = LSUP_striple_new (BUF_DUMMY, BUF_DUMMY, BUF_DUMMY);
  269. LSUP_GraphIterator *it = LSUP_graph_add_init (
  270. ((GraphObject *)self)->ob_struct);
  271. for (i = 0; (trp_obj = PyIter_Next (iter)); i++) {
  272. if (!PyObject_TypeCheck (trp_obj, &TripleType)) {
  273. PyErr_SetString (
  274. PyExc_ValueError, "Object is not a triple.");
  275. rc = -1;
  276. goto finalize;
  277. }
  278. log_trace ("Inserting triple #%lu", i);
  279. LSUP_triple_serialize (((TripleObject *)trp_obj)->ob_struct, sspo);
  280. LSUP_rc db_rc = LSUP_graph_add_iter (it, sspo);
  281. if (db_rc == LSUP_OK) rc = LSUP_OK;
  282. if (UNLIKELY (db_rc < 0)) {
  283. rc = -1;
  284. goto finalize;
  285. }
  286. }
  287. finalize:
  288. LSUP_graph_add_done (it);
  289. LSUP_striple_free (sspo);
  290. PyObject *ret = PyLong_FromSize_t (LSUP_graph_iter_cur (it));
  291. if (rc == 0) {
  292. Py_INCREF (ret);
  293. return ret;
  294. }
  295. return NULL;
  296. }
  297. inline static int build_trp_pattern (PyObject *args, LSUP_Term *spo[])
  298. {
  299. PyObject *s_obj, *p_obj, *o_obj;
  300. if (! (PyArg_ParseTuple (args, "OOO", &s_obj, &p_obj, &o_obj)))
  301. return -1;
  302. if (s_obj != Py_None && !PyObject_TypeCheck (s_obj, &TermType)) {
  303. PyErr_SetString (PyExc_TypeError, "Subject must be a term or None.");
  304. return -1;
  305. }
  306. if (p_obj != Py_None && !PyObject_TypeCheck (p_obj, &TermType)) {
  307. PyErr_SetString (PyExc_TypeError, "Predicate must be a term or None.");
  308. return -1;
  309. }
  310. if (o_obj != Py_None && !PyObject_TypeCheck (o_obj, &TermType)) {
  311. PyErr_SetString (PyExc_TypeError, "Object must be a term or None.");
  312. return -1;
  313. }
  314. spo[0] = s_obj != Py_None ? ((TermObject *)s_obj)->ob_struct : NULL;
  315. spo[1] = s_obj != Py_None ? ((TermObject *)p_obj)->ob_struct : NULL;
  316. spo[2] = s_obj != Py_None ? ((TermObject *)o_obj)->ob_struct : NULL;
  317. return 0;
  318. }
  319. static PyObject *Graph_remove (PyObject *self, PyObject *args)
  320. {
  321. LSUP_rc rc;
  322. LSUP_Term *spo[3];
  323. rc = build_trp_pattern (args, spo);
  324. if (rc < 0) goto finally;
  325. size_t ct;
  326. rc = LSUP_graph_remove (
  327. ((GraphObject *)self)->ob_struct, spo[0], spo[1], spo[2], &ct);
  328. if (rc < 0) {
  329. // TODO implement strerror for more details.
  330. PyErr_SetString (PyExc_SystemError, "Error removing triples.");
  331. goto finally;
  332. }
  333. log_debug ("Removed %lu triples.", ct);
  334. finally:
  335. if (rc < 0) return NULL;
  336. Py_RETURN_NONE;
  337. }
  338. static PyObject *Graph_lookup (PyObject *self, PyObject *args)
  339. {
  340. LSUP_rc rc;
  341. GraphIteratorObject *it_obj = NULL;
  342. LSUP_Term *spo[3];
  343. rc = build_trp_pattern (args, spo);
  344. if (UNLIKELY (rc < 0)) goto finally;
  345. size_t ct;
  346. LSUP_GraphIterator *it = LSUP_graph_lookup (
  347. ((GraphObject *)self)->ob_struct, spo[0], spo[1], spo[2], &ct);
  348. if (UNLIKELY (!it)) {
  349. // TODO implement LSUP_strerror for more details.
  350. PyErr_SetString (PyExc_SystemError, "Error looking up triples.");
  351. rc = -1;
  352. goto finally;
  353. }
  354. log_debug ("Found %lu triples.", ct);
  355. // Initialize the generator object.
  356. it_obj = PyObject_New (
  357. GraphIteratorObject, &GraphIteratorType);
  358. if (UNLIKELY (!it_obj)) goto finally;
  359. it_obj->it = it;
  360. it_obj->spo = NULL;
  361. Py_INCREF (it_obj);
  362. finally:
  363. return (PyObject *)it_obj;
  364. }
  365. static PyObject *
  366. Graph_encode (PyObject *self, PyObject *args)
  367. {
  368. const char *type;
  369. if (! PyArg_ParseTuple (args, "s", &type)) return NULL;
  370. const LSUP_Codec *codec;
  371. if (strcmp(type, "nt") == 0) codec = &nt_codec;
  372. // TODO other codecs here.
  373. else {
  374. PyErr_SetString (PyExc_ValueError, "Unsupported codec.");
  375. return NULL;
  376. }
  377. LSUP_CodecIterator *it = codec->encode_graph_init (
  378. ((GraphObject *)self)->ob_struct);
  379. // Initialize the generator object.
  380. StringIteratorObject *it_obj = PyObject_New (
  381. StringIteratorObject, &StringIteratorType);
  382. if (!it_obj) return NULL;
  383. it_obj->it = it;
  384. it_obj->line = NULL;
  385. Py_INCREF (it_obj);
  386. return (PyObject *)it_obj;
  387. }
  388. static PyMethodDef Graph_methods[] = {
  389. {
  390. "copy", (PyCFunction) Graph_copy,
  391. METH_CLASS | METH_VARARGS, "Copy a graph."
  392. },
  393. {
  394. "from_rdf", (PyCFunction) Graph_new_from_rdf,
  395. METH_CLASS | METH_VARARGS, "Create a graph from a RDF file."
  396. },
  397. {
  398. "store", (PyCFunction) Graph_store, METH_NOARGS,
  399. "Store a graph into the permanent back end."
  400. },
  401. {"add", (PyCFunction) Graph_add, METH_O, "Add triples to a graph."},
  402. {
  403. "remove", (PyCFunction) Graph_remove, METH_VARARGS,
  404. "Remove triples from a graph by matching a pattern."
  405. },
  406. {
  407. "lookup", (PyCFunction) Graph_lookup, METH_VARARGS,
  408. "Look triples in a graph by matching a pattern."
  409. },
  410. {
  411. "to_rdf", (PyCFunction) Graph_encode, METH_VARARGS,
  412. "Encode a graph into a RDF byte buffer."
  413. },
  414. {NULL},
  415. };
  416. static inline PyObject *Graph_bool_and (
  417. PyTypeObject *cls, PyObject *gr1, PyObject *gr2)
  418. { return Graph_bool_op (cls, LSUP_BOOL_INTERSECTION, gr1, gr2); }
  419. static inline PyObject *Graph_bool_or (
  420. PyTypeObject *cls, PyObject *gr1, PyObject *gr2)
  421. { return Graph_bool_op (cls, LSUP_BOOL_UNION, gr1, gr2); }
  422. static inline PyObject *Graph_bool_subtract (
  423. PyTypeObject *cls, PyObject *gr1, PyObject *gr2)
  424. { return Graph_bool_op (cls, LSUP_BOOL_SUBTRACTION, gr1, gr2); }
  425. static inline PyObject *Graph_bool_xor (
  426. PyTypeObject *cls, PyObject *gr1, PyObject *gr2)
  427. { return Graph_bool_op (cls, LSUP_BOOL_XOR, gr1, gr2); }
  428. static PyNumberMethods Graph_number_methods = {
  429. .nb_and = (binaryfunc) Graph_bool_and,
  430. .nb_or = (binaryfunc) Graph_bool_or,
  431. .nb_subtract = (binaryfunc) Graph_bool_subtract,
  432. .nb_xor = (binaryfunc) Graph_bool_xor,
  433. };
  434. static int
  435. Graph_contains (PyObject *self, PyObject *value)
  436. {
  437. if (!PyObject_TypeCheck (value, &TripleType)) {
  438. PyErr_SetString (PyExc_ValueError, "Error parsing input value.");
  439. return -1;
  440. }
  441. int rc = LSUP_graph_contains (
  442. ((GraphObject *) self)->ob_struct,
  443. ((TripleObject *) value)->ob_struct);
  444. return rc;
  445. }
  446. static Py_ssize_t
  447. Graph_get_size (PyObject *self)
  448. { return LSUP_graph_size (((GraphObject *) self)->ob_struct); }
  449. static PySequenceMethods Graph_seq_methods = {
  450. .sq_length = (lenfunc) Graph_get_size,
  451. .sq_contains = (objobjproc) Graph_contains,
  452. };
  453. PyTypeObject GraphType = {
  454. PyVarObject_HEAD_INIT(NULL, 0)
  455. .tp_name = "graph.Graph",
  456. .tp_doc = "RDF graph",
  457. .tp_basicsize = sizeof (GraphObject),
  458. .tp_itemsize = 0,
  459. .tp_flags = Py_TPFLAGS_DEFAULT,
  460. .tp_new = PyType_GenericNew,
  461. .tp_init = (initproc) Graph_init,
  462. .tp_dealloc = (destructor) Graph_dealloc,
  463. .tp_getset = Graph_getsetters,
  464. .tp_methods = Graph_methods,
  465. .tp_richcompare = (richcmpfunc) Graph_richcmp,
  466. .tp_as_number = &Graph_number_methods,
  467. .tp_as_sequence = &Graph_seq_methods,
  468. };
  469. #endif