py_graph.h 14 KB

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