lmdb_triplestore.pyx 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104
  1. import logging
  2. from functools import wraps
  3. from rdflib import Graph
  4. from rdflib.graph import DATASET_DEFAULT_GRAPH_ID as RDFLIB_DEFAULT_GRAPH_URI
  5. from rdflib.term import Node
  6. from lakesuperior.store.base_lmdb_store import (
  7. KeyExistsError, KeyNotFoundError, LmdbError)
  8. from lakesuperior.store.base_lmdb_store cimport _check
  9. from cpython.mem cimport PyMem_Malloc, PyMem_Realloc, PyMem_Free
  10. from cython.parallel import prange
  11. from libc.stdlib cimport free
  12. from libc.string cimport memcpy
  13. cimport lakesuperior.cy_include.cylmdb as lmdb
  14. cimport lakesuperior.cy_include.cytpl as tpl
  15. from lakesuperior.store.base_lmdb_store cimport (
  16. BaseLmdbStore, data_v, dbi, key_v)
  17. from lakesuperior.store.ldp_rs.term cimport (
  18. HLEN, Hash, deserialize, hash_, serialize)
  19. DEF KLEN = 5
  20. """
  21. Fixed length for term keys.
  22. 4 or 5 is a safe range. 4 allows for ~4 billion (256 ** 4) unique terms
  23. in the store. 5 allows ~1 trillion terms. While these numbers may seem
  24. huge (the total number of Internet pages indexed by Google as of 2018 is 45
  25. billions), it must be reminded that the keys cannot be reused, so a
  26. repository that deletes a lot of triples may burn through a lot of terms.
  27. If a repository runs ot of keys it can no longer store new terms and must
  28. be migrated to a new database, which will regenerate and compact the keys.
  29. For smaller repositories it should be safe to set this value to 4, which
  30. could improve performance since keys make up the vast majority of record
  31. exchange between the store and the application. However it is sensible not
  32. to expose this value as a configuration option.
  33. TODO: Explore the option to use size_t (8 bits, or in some architectures,
  34. 4 bits). If the overhead of handling 8
  35. vs. 5 bytes is not huge (and maybe counterbalanced by x86_64 arch optimizations
  36. for 8-byte words) it may be worth using those instead of char[5] to simplify
  37. the code significantly.
  38. """
  39. DEF DBL_KLEN = KLEN * 2
  40. DEF TRP_KLEN = KLEN * 3
  41. DEF QUAD_KLEN = KLEN * 4
  42. DEF KEY_START = b'\x01'
  43. """
  44. Lexical sequence start. ``\\x01`` is fine since no special characters are
  45. used, but it's good to leave a spare for potential future use.
  46. """
  47. DEF FIRST_KEY = KEY_START * KLEN
  48. """First key of a sequence."""
  49. DEF IDX_OP_ADD = '_idx_add'
  50. DEF IDX_OP_REMOVE = '_idx_remove'
  51. ctypedef unsigned char Key[KLEN]
  52. ctypedef unsigned char DoubleKey[DBL_KLEN]
  53. ctypedef unsigned char TripleKey[TRP_KLEN]
  54. ctypedef unsigned char QuadKey[QUAD_KLEN]
  55. cdef unsigned char first_key[KLEN]
  56. memcpy(first_key, FIRST_KEY, KLEN)
  57. cdef unsigned char lookup_rank[3]
  58. lookup_rank = [0, 2, 1]
  59. """
  60. Order in which keys are looked up if two terms are bound.
  61. The indices with the smallest average number of values per key should be
  62. looked up first.
  63. 0 = s:po
  64. 1 = p:so
  65. 2 = o:sp
  66. If we want to get fancy, this can be rebalanced from time to time by
  67. looking up the number of keys in (s:po, p:so, o:sp).
  68. """
  69. cdef unsigned char lookup_ordering[3][3]
  70. lookup_ordering = [
  71. [0, 1, 2], # spo
  72. [1, 0, 2], # pso
  73. [2, 0, 1], # osp
  74. ]
  75. cdef unsigned char lookup_ordering_2bound[3][3]
  76. lookup_ordering_2bound = [
  77. [1, 2, 0], # po:s
  78. [0, 2, 1], # so:p
  79. [0, 1, 2], # sp:o
  80. ]
  81. logger = logging.getLogger(__name__)
  82. cdef class ResultSet:
  83. """
  84. Pre-allocated result set.
  85. Data in the set are stored as a 1D contiguous array of characters.
  86. Access to elements at an arbitrary index position is achieved by using the
  87. ``itemsize`` property multiplied by the index number.
  88. Key properties:
  89. ``ct``: number of elements in the set.
  90. ``itemsize``: size of each element, in bytes. All elements have the same
  91. size.
  92. ``size``: Total size, in bytes, of the data set. This is the product of
  93. ``itemsize`` and ``ct``.
  94. """
  95. cdef:
  96. readonly unsigned char *data
  97. readonly unsigned char itemsize
  98. readonly size_t ct, size
  99. def __cinit__(self, size_t ct, unsigned char itemsize):
  100. """
  101. Initialize and allocate memory for the data set.
  102. :param size_t ct: Number of elements to be accounted for.
  103. :param unsigned char itemsize: Size of an individual item.
  104. Note that the ``itemsize`` is an unsigned char,
  105. i.e. an item can be at most 255 bytes. This is for economy reasons,
  106. since many multiplications are done between ``itemsize`` and other
  107. char variables.
  108. """
  109. self.ct = ct
  110. self.itemsize = itemsize
  111. self.size = self.itemsize * self.ct
  112. #logger.debug('Got malloc sizes: {}, {}'.format(ct, itemsize))
  113. #logger.debug(
  114. # 'Allocating {0} ({1}x{2}) bytes of ResultSet data...'.format(
  115. # self.size, self.ct, self.itemsize))
  116. self.data = <unsigned char *>PyMem_Malloc(ct * itemsize)
  117. if not self.data:
  118. raise MemoryError()
  119. #logger.debug('...done allocating @ {0:x}.'.format(
  120. # <unsigned long>self.data))
  121. def __dealloc__(self):
  122. """
  123. Free the memory.
  124. This is called when the Python instance is garbage collected, which
  125. makes it handy to safely pass a ResultSet instance across functions.
  126. """
  127. #logger.debug(
  128. # 'Releasing {0} ({1}x{2}) bytes of ResultSet @ {3:x}...'.format(
  129. # self.size, self.ct, self.itemsize,
  130. # <unsigned long>self.data))
  131. PyMem_Free(self.data)
  132. #logger.debug('...done releasing.')
  133. cdef void resize(self, size_t ct) except *:
  134. """
  135. Resize the result set. Uses ``PyMem_Realloc``.
  136. Note that resizing to a smaller size does not copy or reallocate the
  137. data, resizing to a larger size does.
  138. Also, note that only the number of items can be changed, the item size
  139. cannot.
  140. :param size_t ct: Number of items in the result set.
  141. """
  142. cdef unsigned char *tmp
  143. self.ct = ct
  144. self.size = self.itemsize * self.ct
  145. #logger.debug(
  146. # 'Resizing ResultSet to {0} ({1}x{2}) bytes @ {3:x}...'.format(
  147. # self.itemsize * ct, ct, self.itemsize,
  148. # <unsigned long>self.data))
  149. tmp = <unsigned char *>PyMem_Realloc(self.data, ct * self.itemsize)
  150. if not tmp:
  151. raise MemoryError()
  152. #logger.debug('...done resizing.')
  153. self.data = tmp
  154. # Access methods.
  155. def to_tuple(self):
  156. """
  157. Return the data set as a Python tuple.
  158. :rtype: tuple
  159. """
  160. return tuple(
  161. self.data[i: i + self.itemsize]
  162. for i in range(0, self.size, self.itemsize))
  163. def get_item_obj(self, i):
  164. """
  165. Get an item at a given index position.
  166. :rtype: bytes
  167. """
  168. return self.get_item(i)[: self.itemsize]
  169. cdef unsigned char *get_item(self, i):
  170. """
  171. Get an item at a given index position. Cython-level method.
  172. The item size is known by the ``itemsize`` property of the object.
  173. :rtype: unsigned char*
  174. """
  175. return self.data + self.itemsize * i
  176. def use_data(fn):
  177. """
  178. Decorator to indicate that a set operation between two SimpleGraph
  179. instances should use the ``data`` property of the second term. The second
  180. term can also be a simple set.
  181. """
  182. @wraps(fn)
  183. def _wrapper(self, other):
  184. if isinstance(other, SimpleGraph):
  185. other = other.data
  186. return _wrapper
  187. cdef class SimpleGraph:
  188. """
  189. Fast and simple implementation of a graph.
  190. Most functions should mimic RDFLib's graph with less overhead. It uses
  191. the same funny but functional slicing notation.
  192. An instance of this class can be converted to a ``rdflib.Graph`` instance.
  193. """
  194. cdef:
  195. readonly set data
  196. def __init__(
  197. self, set data=set(), tuple lookup=(), store=None):
  198. """
  199. Initialize the graph with pre-existing data or by looking up a store.
  200. Either ``data``, or both ``lookup`` and ``store``, can be provided.
  201. ``lookup`` and ``store`` have precedence. If none of them is specified,
  202. an empty graph is initialized.
  203. :param rdflib.URIRef uri: The graph URI.
  204. This will serve as the subject for some queries.
  205. :param set data: Initial data as a set of 3-tuples of RDFLib terms.
  206. :param tuple lookup: tuple of a 3-tuple of lookup terms, and a context.
  207. E.g. ``((URIRef('urn:ns:a'), None, None), URIRef('urn:ns:ctx'))``.
  208. Any and all elements may be ``None``.
  209. :param lmdbStore store: the store to look data up.
  210. """
  211. if data:
  212. self.data = set(data)
  213. else:
  214. if not lookup:
  215. self.data = set()
  216. else:
  217. if store is None:
  218. raise ValueError('Store not specified for triple lookup.')
  219. self._data_from_lookup(lookup, store)
  220. cdef void _data_from_lookup(
  221. self, tuple lookup, LmdbTriplestore store) except *:
  222. """
  223. Look up triples in the triplestore and load them into ``data``.
  224. :param tuple lookup: 3-tuple of RDFlib terms or ``None``.
  225. :param LmdbTriplestore store: Reference to a LMDB triplestore. This
  226. is normally set to ``lakesuperior.env.app_globals.rdf_store``.
  227. """
  228. cdef:
  229. size_t i
  230. unsigned char spok[TRP_KLEN]
  231. self.data = set()
  232. with store.txn_ctx():
  233. keyset = store.triple_keys(*lookup)
  234. for i in range(keyset.ct):
  235. spok = keyset.data + i * TRP_KLEN
  236. self.data.add(store.from_trp_key(spok[: TRP_KLEN]))
  237. # Basic set operations.
  238. def add(self, dataset):
  239. """ Set union. """
  240. self.data.add(dataset)
  241. def remove(self, item):
  242. """
  243. Remove one item from the graph.
  244. :param tuple item: A 3-tuple of RDFlib terms. Only exact terms, i.e.
  245. wildcards are not accepted.
  246. """
  247. self.data.remove(item)
  248. def __len__(self):
  249. """ Number of triples in the graph. """
  250. return len(self.data)
  251. @use_data
  252. def __eq__(self, other):
  253. """ Equality operator between ``SimpleGraph`` instances. """
  254. return self.data == other
  255. def __repr__(self):
  256. """
  257. String representation of the graph.
  258. It provides the number of triples in the graph and memory address of
  259. the instance.
  260. """
  261. return (f'<{self.__class__.__name__} @{hex(id(self))} '
  262. f'length={len(self.data)}>')
  263. def __str__(self):
  264. """ String dump of the graph triples. """
  265. return str(self.data)
  266. @use_data
  267. def __sub__(self, other):
  268. """ Set subtraction. """
  269. return self.data - other
  270. @use_data
  271. def __isub__(self, other):
  272. """ In-place set subtraction. """
  273. self.data -= other
  274. return self
  275. @use_data
  276. def __and__(self, other):
  277. """ Set intersection. """
  278. return self.data & other
  279. @use_data
  280. def __iand__(self, other):
  281. """ In-place set intersection. """
  282. self.data &= other
  283. return self
  284. @use_data
  285. def __or__(self, other):
  286. """ Set union. """
  287. return self.data | other
  288. @use_data
  289. def __ior__(self, other):
  290. """ In-place set union. """
  291. self.data |= other
  292. return self
  293. @use_data
  294. def __xor__(self, other):
  295. """ Set exclusive intersection (XOR). """
  296. return self.data ^ other
  297. @use_data
  298. def __ixor__(self, other):
  299. """ In-place set exclusive intersection (XOR). """
  300. self.data ^= other
  301. return self
  302. def __contains__(self, item):
  303. """
  304. Whether the graph contains a triple.
  305. :rtype: boolean
  306. """
  307. return item in self.data
  308. def __iter__(self):
  309. """ Graph iterator. It iterates over the set triples. """
  310. return self.data.__iter__()
  311. # Slicing.
  312. def __getitem__(self, item):
  313. """
  314. Slicing function.
  315. It behaves similarly to `RDFLib graph slicing
  316. <https://rdflib.readthedocs.io/en/stable/utilities.html#slicing-graphs>`__
  317. """
  318. if isinstance(item, slice):
  319. s, p, o = item.start, item.stop, item.step
  320. return self._slice(s, p, o)
  321. else:
  322. raise TypeError(f'Wrong slice format: {item}.')
  323. cpdef void set(self, tuple trp) except *:
  324. """
  325. Set a single value for subject and predicate.
  326. Remove all triples matching ``s`` and ``p`` before adding ``s p o``.
  327. """
  328. self.remove_triples((trp[0], trp[1], None))
  329. if None in trp:
  330. raise ValueError(f'Invalid triple: {trp}')
  331. self.data.add(trp)
  332. cpdef void remove_triples(self, pattern) except *:
  333. """
  334. Remove triples by pattern.
  335. The pattern used is similar to :py:meth:`LmdbTripleStore.delete`.
  336. """
  337. s, p, o = pattern
  338. for match in self.lookup(s, p, o):
  339. logger.debug(f'Removing from graph: {match}.')
  340. self.data.remove(match)
  341. cpdef object as_rdflib(self):
  342. """
  343. Return the data set as an RDFLib Graph.
  344. :rtype: rdflib.Graph
  345. """
  346. gr = Graph()
  347. for trp in self.data:
  348. gr.add(trp)
  349. return gr
  350. cdef _slice(self, s, p, o):
  351. """
  352. Return terms filtered by other terms.
  353. This behaves like the rdflib.Graph slicing policy.
  354. """
  355. if s is None and p is None and o is None:
  356. return self.data
  357. elif s is None and p is None:
  358. return {(r[0], r[1]) for r in self.data if r[2] == o}
  359. elif s is None and o is None:
  360. return {(r[0], r[2]) for r in self.data if r[1] == p}
  361. elif p is None and o is None:
  362. return {(r[1], r[2]) for r in self.data if r[0] == s}
  363. elif s is None:
  364. return {r[0] for r in self.data if r[1] == p and r[2] == o}
  365. elif p is None:
  366. return {r[1] for r in self.data if r[0] == s and r[2] == o}
  367. elif o is None:
  368. return {r[2] for r in self.data if r[0] == s and r[1] == p}
  369. else:
  370. # all given
  371. return (s,p,o) in self.data
  372. cpdef lookup(self, s, p, o):
  373. """
  374. Look up triples by a pattern.
  375. """
  376. logger.debug(f'Looking up in graph: {s}, {p}, {o}.')
  377. if s is None and p is None and o is None:
  378. return self.data
  379. elif s is None and p is None:
  380. return {r for r in self.data if r[2] == o}
  381. elif s is None and o is None:
  382. return {r for r in self.data if r[1] == p}
  383. elif p is None and o is None:
  384. return {r for r in self.data if r[0] == s}
  385. elif s is None:
  386. return {r for r in self.data if r[1] == p and r[2] == o}
  387. elif p is None:
  388. return {r for r in self.data if r[0] == s and r[2] == o}
  389. elif o is None:
  390. return {r for r in self.data if r[0] == s and r[1] == p}
  391. else:
  392. # all given
  393. return (s,p,o) if (s, p, o) in self.data else set()
  394. cpdef set terms(self, str type):
  395. """
  396. Get all terms of a type: subject, predicate or object.
  397. :param str type: One of ``s``, ``p`` or ``o``.
  398. """
  399. i = 'spo'.index(type)
  400. return {r[i] for r in self.data}
  401. cdef class Imr(SimpleGraph):
  402. """
  403. In-memory resource data container.
  404. This is an extension of :py:class:`~SimpleGraph` that adds a subject URI to
  405. the data set and some convenience methods.
  406. An instance of this class can be converted to a ``rdflib.Resource``
  407. instance.
  408. Some set operations that produce a new object (``-``, ``|``, ``&``, ``^``)
  409. will create a new ``Imr`` instance with the same subject URI.
  410. """
  411. cdef:
  412. readonly object uri
  413. def __init__(self, uri, *args, **kwargs):
  414. """
  415. Initialize the graph with pre-existing data or by looking up a store.
  416. Either ``data``, or ``lookup`` *and* ``store``, can be provide.
  417. ``lookup`` and ``store`` have precedence. If none of them is specified,
  418. an empty graph is initialized.
  419. :param rdflib.URIRef uri: The graph URI.
  420. This will serve as the subject for some queries.
  421. :param set data: Initial data as a set of 3-tuples of RDFLib terms.
  422. :param tuple lookup: tuple of a 3-tuple of lookup terms, and a context.
  423. E.g. ``((URIRef('urn:ns:a'), None, None), URIRef('urn:ns:ctx'))``.
  424. Any and all elements may be ``None``.
  425. :param lmdbStore store: the store to look data up.
  426. """
  427. super().__init__(*args, **kwargs)
  428. self.uri = uri
  429. @property
  430. def identifier(self):
  431. """
  432. IMR URI. For compatibility with RDFLib Resource.
  433. :rtype: string
  434. """
  435. return self.uri
  436. @property
  437. def graph(self):
  438. """
  439. Return a SimpleGraph with the same data.
  440. :rtype: SimpleGraph
  441. """
  442. return SimpleGraph(self.data)
  443. def __repr__(self):
  444. """
  445. String representation of an Imr.
  446. This includes the subject URI, number of triples contained and the
  447. memory address of the instance.
  448. """
  449. return (f'<{self.__class__.__name__} @{hex(id(self))} uri={self.uri}, '
  450. f'length={len(self.data)}>')
  451. @use_data
  452. def __sub__(self, other):
  453. """
  454. Set difference. This creates a new Imr with the same subject URI.
  455. """
  456. return self.__class__(uri=self.uri, data=self.data - other)
  457. @use_data
  458. def __and__(self, other):
  459. """
  460. Set intersection. This creates a new Imr with the same subject URI.
  461. """
  462. return self.__class__(uri=self.uri, data=self.data & other)
  463. @use_data
  464. def __or__(self, other):
  465. """
  466. Set union. This creates a new Imr with the same subject URI.
  467. """
  468. return self.__class__(uri=self.uri, data=self.data | other)
  469. @use_data
  470. def __xor__(self, other):
  471. """
  472. Set exclusive OR (XOR). This creates a new Imr with the same subject
  473. URI.
  474. """
  475. return self.__class__(uri=self.uri, data=self.data ^ other)
  476. def __getitem__(self, item):
  477. """
  478. Supports slicing notation.
  479. """
  480. if isinstance(item, slice):
  481. s, p, o = item.start, item.stop, item.step
  482. return self._slice(s, p, o)
  483. elif isinstance(item, Node):
  484. # If a Node is given, return all values for that predicate.
  485. return {
  486. r[2] for r in self.data
  487. if r[0] == self.uri and r[1] == item}
  488. else:
  489. raise TypeError(f'Wrong slice format: {item}.')
  490. def value(self, p, strict=False):
  491. """
  492. Get an individual value.
  493. :param rdflib.termNode p: Predicate to search for.
  494. :param bool strict: If set to ``True`` the method raises an error if
  495. more than one value is found. If ``False`` (the default) only
  496. the first found result is returned.
  497. :rtype: rdflib.term.Node
  498. """
  499. values = self[p]
  500. if strict and len(values) > 1:
  501. raise RuntimeError('More than one value found for {}, {}.'.format(
  502. self.uri, p))
  503. for ret in values:
  504. return ret
  505. return None
  506. cpdef as_rdflib(self):
  507. """
  508. Return the IMR as a RDFLib Resource.
  509. :rtype: rdflib.Resource
  510. """
  511. gr = Graph()
  512. for trp in self.data:
  513. gr.add(trp)
  514. return gr.resource(identifier=self.uri)
  515. cdef class LmdbTriplestore(BaseLmdbStore):
  516. """
  517. Low-level storage layer.
  518. This class extends the RDFLib-compatible :py:class:`BaseLmdbStore` and maps
  519. triples and contexts to key-value records in LMDB.
  520. This class uses the original LMDB C API rather than the Python bindings,
  521. because several data manipulations happen after retrieval from the store,
  522. which are more efficiently performed at the C level.
  523. """
  524. dbi_labels = [
  525. # Main data
  526. # Term key to serialized term content
  527. 't:st',
  528. # Joined triple keys to context key
  529. 'spo:c',
  530. # This has empty values and is used to keep track of empty contexts.
  531. 'c:',
  532. # Prefix to namespace
  533. 'pfx:ns',
  534. # Indices
  535. # Namespace to prefix
  536. 'ns:pfx',
  537. # Term hash to triple key
  538. 'th:t',
  539. # Lookups
  540. 's:po',
  541. 'p:so',
  542. 'o:sp',
  543. 'po:s',
  544. 'so:p',
  545. 'sp:o',
  546. 'c:spo',
  547. ]
  548. lookup_indices = [
  549. b's:po',
  550. b'p:so',
  551. b'o:sp',
  552. b'po:s',
  553. b'so:p',
  554. b'sp:o',
  555. ]
  556. dbi_flags = {
  557. 's:po': lmdb.MDB_DUPSORT | lmdb.MDB_DUPFIXED,
  558. 'p:so': lmdb.MDB_DUPSORT | lmdb.MDB_DUPFIXED,
  559. 'o:sp': lmdb.MDB_DUPSORT | lmdb.MDB_DUPFIXED,
  560. 'po:s': lmdb.MDB_DUPSORT | lmdb.MDB_DUPFIXED,
  561. 'so:p': lmdb.MDB_DUPSORT | lmdb.MDB_DUPFIXED,
  562. 'sp:o': lmdb.MDB_DUPSORT | lmdb.MDB_DUPFIXED,
  563. 'c:spo': lmdb.MDB_DUPSORT | lmdb.MDB_DUPFIXED,
  564. 'spo:c': lmdb.MDB_DUPSORT | lmdb.MDB_DUPFIXED,
  565. }
  566. flags = 0
  567. options = {
  568. 'map_size': 1024 ** 4 # 1Tb.
  569. }
  570. # DB management methods.
  571. cpdef dict stats(self):
  572. """
  573. Gather statistics about the database."""
  574. st = self._stats()
  575. st['num_triples'] = st['db_stats']['spo:c']['ms_entries']
  576. return st
  577. cpdef size_t _len(self, context=None) except -1:
  578. """
  579. Return the length of the dataset.
  580. The RDFLib interface defines `__len__` in a nonstandard way that
  581. causes a Cython compilation error, so this method is called by the
  582. `__len__` method of its Python counterpart.
  583. """
  584. cdef:
  585. size_t ct
  586. if context is not None:
  587. self._to_key(context, <Key *>key_v.mv_data)
  588. key_v.mv_size = KLEN
  589. cur = self._cur_open('c:spo')
  590. try:
  591. _check(lmdb.mdb_cursor_get(
  592. cur, &key_v, NULL, lmdb.MDB_SET))
  593. _check(lmdb.mdb_cursor_count(cur, &ct))
  594. except KeyNotFoundError:
  595. return 0
  596. else:
  597. return ct
  598. finally:
  599. #pass
  600. self._cur_close(cur)
  601. else:
  602. return self.stats()['num_triples']
  603. ## PRIVATE METHODS ##
  604. # Triple and graph methods.
  605. cpdef add(self, triple, context=None, quoted=False):
  606. """
  607. Add a triple and start indexing.
  608. :param tuple(rdflib.Identifier) triple: Tuple of three identifiers.
  609. :param context: Context identifier. ``None`` inserts in the default
  610. graph.
  611. :type context: rdflib.Identifier or None
  612. :param bool quoted: Not used.
  613. """
  614. cdef:
  615. lmdb.MDB_cursor *icur
  616. lmdb.MDB_val spo_v, c_v, null_v
  617. unsigned char i
  618. unsigned char *pk_t
  619. Hash thash
  620. # Using Key or TripleKey here breaks Cython. This might be a bug.
  621. # See https://github.com/cython/cython/issues/2517
  622. unsigned char spock[QUAD_KLEN]
  623. unsigned char nkey[KLEN]
  624. size_t term_size
  625. c = self._normalize_context(context)
  626. if c is None:
  627. c = RDFLIB_DEFAULT_GRAPH_URI
  628. # TODO: figure out how the RDFLib dispatcher is inherited
  629. # (and if there is a use for it in a first place)
  630. #Store.add(self, triple, context)
  631. s, p, o = triple
  632. #logger.debug('Trying to add a triple.')
  633. icur = self._cur_open('th:t')
  634. try:
  635. for i, term in enumerate((s, p, o, c)):
  636. serialize(term, &pk_t, &term_size)
  637. hash_(pk_t, term_size, &thash)
  638. try:
  639. key_v.mv_data = &thash
  640. key_v.mv_size = HLEN
  641. _check(lmdb.mdb_get(
  642. self.txn, self.get_dbi('th:t'), &key_v, &data_v))
  643. memcpy(spock + (i * KLEN), data_v.mv_data, KLEN)
  644. #logger.debug('Hash {} found. Not adding.'.format(thash[: HLEN]))
  645. except KeyNotFoundError:
  646. # If term is not found, add it...
  647. #logger.debug('Hash {} not found. Adding to DB.'.format(
  648. # thash[: HLEN]))
  649. self._append(pk_t, term_size, &nkey, dblabel=b't:st')
  650. free(pk_t)
  651. memcpy(spock + (i * KLEN), nkey, KLEN)
  652. # ...and index it.
  653. #logger.debug('Indexing on th:t: {}: {}'.format(
  654. # thash[: HLEN], nkey[: KLEN]))
  655. key_v.mv_data = thash
  656. key_v.mv_size = HLEN
  657. data_v.mv_data = nkey
  658. data_v.mv_size = KLEN
  659. _check(
  660. lmdb.mdb_cursor_put(icur, &key_v, &data_v, 0),
  661. 'Error setting key {}.'.format(thash))
  662. finally:
  663. #pass
  664. self._cur_close(icur)
  665. #logger.debug('Triple add action completed.')
  666. spo_v.mv_data = spock
  667. spo_v.mv_size = TRP_KLEN
  668. c_v.mv_data = spock + TRP_KLEN
  669. c_v.mv_size = KLEN
  670. null_v.mv_data = b''
  671. null_v.mv_size = 0
  672. #logger.debug('Adding context.')
  673. try:
  674. _check(lmdb.mdb_put(
  675. self.txn, self.get_dbi('c:'), &c_v, &null_v,
  676. lmdb.MDB_NOOVERWRITE))
  677. except KeyExistsError:
  678. pass
  679. #logger.debug('Added c:.')
  680. try:
  681. # Add triple:context association.
  682. _check(lmdb.mdb_put(
  683. self.txn, self.get_dbi('spo:c'), &spo_v, &c_v,
  684. lmdb.MDB_NODUPDATA))
  685. except KeyExistsError:
  686. pass
  687. #logger.debug('Added spo:c.')
  688. try:
  689. # Index context:triple association.
  690. _check(lmdb.mdb_put(
  691. self.txn, self.get_dbi('c:spo'), &c_v, &spo_v,
  692. lmdb.MDB_NODUPDATA))
  693. except KeyExistsError:
  694. pass
  695. #logger.debug('Added c:spo.')
  696. #logger.debug('All main data entered. Indexing.')
  697. self._index_triple(IDX_OP_ADD, spock[: TRP_KLEN])
  698. cpdef add_graph(self, graph):
  699. """
  700. Add a graph to the database.
  701. This creates an empty graph by associating the graph URI with the
  702. pickled `None` value. This prevents from removing the graph when all
  703. triples are removed.
  704. This may be called by read-only operations:
  705. https://github.com/RDFLib/rdflib/blob/master/rdflib/graph.py#L1623
  706. In which case it needs to open a write transaction. This is not ideal
  707. but the only way to handle datasets in RDFLib.
  708. :param rdflib.URIRef graph: URI of the named graph to add.
  709. """
  710. cdef:
  711. unsigned char *pk_c
  712. size_t pk_size
  713. if isinstance(graph, Graph):
  714. graph = graph.identifier
  715. serialize(graph, &pk_c, &pk_size)
  716. self._add_graph(pk_c, pk_size)
  717. free(pk_c)
  718. cpdef void _add_graph(
  719. self, unsigned char *pk_c, size_t pk_size) except *:
  720. """
  721. Add a graph.
  722. :param pk_c: Pickled context URIRef object.
  723. :type pk_c: unsigned char*
  724. :param pk_size: Size of pickled string.
  725. :type pk_size: size_t
  726. """
  727. cdef:
  728. Hash c_hash
  729. unsigned char ck[KLEN]
  730. lmdb.MDB_txn *tmp_txn
  731. lmdb.MDB_cursor *th_cur
  732. lmdb.MDB_cursor *pk_cur
  733. lmdb.MDB_cursor *ck_cur
  734. hash_(pk_c, pk_size, &c_hash)
  735. #logger.debug('Adding a graph.')
  736. if not self._key_exists(c_hash, HLEN, b'th:t'):
  737. # Insert context term if not existing.
  738. if self.is_txn_rw:
  739. #logger.debug('Working in existing RW transaction.')
  740. # Use existing R/W transaction.
  741. # Main entry.
  742. self._append(pk_c, pk_size, &ck, b't:st')
  743. # Index.
  744. self._put(c_hash, HLEN, ck, KLEN, b'th:t')
  745. # Add to list of contexts.
  746. self._put(ck, KLEN, b'', 0, 'c:')
  747. else:
  748. # Open new R/W transactions.
  749. #logger.debug('Opening a temporary RW transaction.')
  750. _check(lmdb.mdb_txn_begin(self.dbenv, NULL, 0, &tmp_txn))
  751. try:
  752. self._append(
  753. pk_c, pk_size, &ck, dblabel=b't:st', txn=tmp_txn)
  754. # Index.
  755. self._put(c_hash, HLEN, ck, KLEN, b'th:t', txn=tmp_txn)
  756. # Add to list of contexts.
  757. self._put(ck, KLEN, b'', 0, b'c:', txn=tmp_txn)
  758. _check(lmdb.mdb_txn_commit(tmp_txn))
  759. #logger.debug('Temp RW transaction closed.')
  760. except:
  761. lmdb.mdb_txn_abort(tmp_txn)
  762. raise
  763. cpdef void _remove(self, tuple triple_pattern, context=None) except *:
  764. cdef:
  765. unsigned char spok[TRP_KLEN]
  766. size_t i = 0
  767. Key ck
  768. lmdb.MDB_val spok_v, ck_v
  769. #logger.debug('Removing triple: {}'.format(triple_pattern))
  770. if context is not None:
  771. try:
  772. self._to_key(context, &ck)
  773. except KeyNotFoundError:
  774. # If context is specified but not found, return to avoid
  775. # deleting the wrong triples.
  776. return
  777. # Get the matching pattern.
  778. match_set = self.triple_keys(triple_pattern, context)
  779. dcur = self._cur_open('spo:c')
  780. icur = self._cur_open('c:spo')
  781. try:
  782. spok_v.mv_size = TRP_KLEN
  783. # If context was specified, remove only associations with that context.
  784. if context is not None:
  785. #logger.debug('Removing triples in matching context.')
  786. ck_v.mv_data = ck
  787. ck_v.mv_size = KLEN
  788. while i < match_set.ct:
  789. memcpy(
  790. spok, match_set.data + match_set.itemsize * i,
  791. TRP_KLEN)
  792. spok_v.mv_data = spok
  793. # Delete spo:c entry.
  794. try:
  795. _check(lmdb.mdb_cursor_get(
  796. dcur, &spok_v, &ck_v, lmdb.MDB_GET_BOTH))
  797. except KeyNotFoundError:
  798. pass
  799. else:
  800. _check(lmdb.mdb_cursor_del(dcur, 0))
  801. # Restore ck after delete.
  802. ck_v.mv_data = ck
  803. # Delete c:spo entry.
  804. try:
  805. _check(lmdb.mdb_cursor_get(
  806. icur, &ck_v, &spok_v, lmdb.MDB_GET_BOTH))
  807. except KeyNotFoundError:
  808. pass
  809. else:
  810. _check(lmdb.mdb_cursor_del(icur, 0))
  811. # Delete lookup indices, only if no other context
  812. # association is present.
  813. spok_v.mv_data = spok
  814. try:
  815. _check(lmdb.mdb_cursor_get(
  816. dcur, &spok_v, NULL, lmdb.MDB_SET))
  817. except KeyNotFoundError:
  818. self._index_triple(IDX_OP_REMOVE, spok)
  819. i += 1
  820. # If no context is specified, remove all associations.
  821. else:
  822. #logger.debug('Removing triples in all contexts.')
  823. # Loop over all SPO matching the triple pattern.
  824. while i < match_set.ct:
  825. spok = match_set.data + match_set.itemsize * i
  826. spok_v.mv_data = spok
  827. # Loop over all context associations for this SPO.
  828. try:
  829. _check(lmdb.mdb_cursor_get(
  830. dcur, &spok_v, &ck_v, lmdb.MDB_SET_KEY))
  831. except KeyNotFoundError:
  832. # Move on to the next SPO.
  833. continue
  834. else:
  835. ck = <Key>ck_v.mv_data
  836. logger.debug(f'Removing {spok[: TRP_KLEN]} from main.')
  837. while True:
  838. # Delete c:spo association.
  839. try:
  840. _check(lmdb.mdb_cursor_get(
  841. icur, &ck_v, &spok_v, lmdb.MDB_GET_BOTH))
  842. except KeyNotFoundError:
  843. pass
  844. else:
  845. lmdb.mdb_cursor_del(icur, 0)
  846. # Restore the pointer to the deleted SPO.
  847. spok_v.mv_data = spok
  848. # Move on to next associated context.
  849. try:
  850. _check(lmdb.mdb_cursor_get(
  851. dcur, &spok_v, &ck_v, lmdb.MDB_NEXT_DUP))
  852. except KeyNotFoundError:
  853. break
  854. # Then delete the spo:c association.
  855. try:
  856. _check(lmdb.mdb_cursor_get(
  857. dcur, &spok_v, &ck_v, lmdb.MDB_SET))
  858. except KeyNotFoundError:
  859. pass
  860. else:
  861. lmdb.mdb_cursor_del(dcur, lmdb.MDB_NODUPDATA)
  862. self._index_triple(IDX_OP_REMOVE, spok)
  863. #ck_v.mv_data = ck # Unnecessary?
  864. finally:
  865. i += 1
  866. finally:
  867. #pass
  868. #logger.debug('Closing spo:c in _remove.')
  869. self._cur_close(dcur)
  870. #logger.debug('Closing c:spo in _remove.')
  871. self._cur_close(icur)
  872. cdef void _index_triple(self, str op, TripleKey spok) except *:
  873. """
  874. Update index for a triple and context (add or remove).
  875. :param str op: 'add' or 'remove'.
  876. :param TripleKey spok: Triple key.
  877. """
  878. cdef:
  879. unsigned char keys[3][KLEN]
  880. unsigned char dbl_keys[3][DBL_KLEN]
  881. size_t i = 0
  882. lmdb.MDB_val key_v, dbl_key_v
  883. keys[0] = spok # sk
  884. keys[1] = spok + KLEN # pk
  885. keys[2] = spok + DBL_KLEN # ok
  886. dbl_keys[0] = spok + KLEN # pok
  887. memcpy(&dbl_keys[1], spok, KLEN) # sok, 1st part
  888. memcpy(&dbl_keys[1][KLEN], spok + DBL_KLEN, KLEN) # sok, 2nd part
  889. dbl_keys[2] = spok # spk
  890. #logger.debug('''Indices:
  891. #spok: {}
  892. #sk: {}
  893. #pk: {}
  894. #ok: {}
  895. #pok: {}
  896. #sok: {}
  897. #spk: {}
  898. #'''.format(
  899. # spok[:TRP_KLEN],
  900. # keys[0][:KLEN], keys[1][:KLEN], keys[2][:KLEN],
  901. # dbl_keys[0][:DBL_KLEN], dbl_keys[1][:DBL_KLEN], dbl_keys[2][:DBL_KLEN]))
  902. key_v.mv_size = KLEN
  903. dbl_key_v.mv_size = DBL_KLEN
  904. #logger.debug('Start indexing: {}.'.format(spok[: TRP_KLEN]))
  905. if op == IDX_OP_REMOVE:
  906. logger.debug(f'Remove {spok[ : TRP_KLEN]} from indices.')
  907. else:
  908. logger.debug(f'Add {spok[ : TRP_KLEN]} to indices.')
  909. while i < 3:
  910. cur1 = self._cur_open(self.lookup_indices[i]) # s:po, p:so, o:sp
  911. cur2 = self._cur_open(self.lookup_indices[i + 3])# po:s, so:p, sp:o
  912. try:
  913. key_v.mv_data = keys[i]
  914. dbl_key_v.mv_data = dbl_keys[i]
  915. # Removal op indexing.
  916. if op == IDX_OP_REMOVE:
  917. try:
  918. _check(lmdb.mdb_cursor_get(
  919. cur1, &key_v, &dbl_key_v, lmdb.MDB_GET_BOTH))
  920. logger.debug(f'Removed: {keys[i][: KLEN]}, '
  921. f'{dbl_keys[i][: DBL_KLEN]}')
  922. except KeyNotFoundError:
  923. logger.debug(f'Not found in index: {keys[i][: KLEN]}, '
  924. f'{dbl_keys[i][: DBL_KLEN]}')
  925. pass
  926. else:
  927. _check(lmdb.mdb_cursor_del(cur1, 0))
  928. # Restore pointers after delete.
  929. key_v.mv_data = keys[i]
  930. dbl_key_v.mv_data = dbl_keys[i]
  931. try:
  932. _check(lmdb.mdb_cursor_get(
  933. cur2, &dbl_key_v, &key_v, lmdb.MDB_GET_BOTH))
  934. logger.debug(f'Removed: {dbl_keys[i][: DBL_KLEN]}, '
  935. f'{keys[i][: KLEN]}')
  936. except KeyNotFoundError:
  937. logger.debug(f'Not found in index: '
  938. f'{dbl_keys[i][: DBL_KLEN]}, '
  939. f'{keys[i][: KLEN]}')
  940. pass
  941. else:
  942. _check(lmdb.mdb_cursor_del(cur2, 0))
  943. # Addition op indexing.
  944. elif op == IDX_OP_ADD:
  945. logger.debug('Adding to index `{}`: {}, {}'.format(
  946. self.lookup_indices[i],
  947. (<unsigned char *>key_v.mv_data)[ : key_v.mv_size],
  948. (<unsigned char *>dbl_key_v.mv_data)[ : dbl_key_v.mv_size]))
  949. try:
  950. _check(lmdb.mdb_cursor_put(
  951. cur1, &key_v, &dbl_key_v, lmdb.MDB_NODUPDATA))
  952. except KeyExistsError:
  953. logger.debug(f'Key {keys[i][: KLEN]} exists already.')
  954. pass
  955. logger.debug('Adding to index `{}`: {}, {}'.format(
  956. self.lookup_indices[i + 3],
  957. (<unsigned char *>dbl_key_v.mv_data)[ : dbl_key_v.mv_size],
  958. (<unsigned char *>key_v.mv_data)[ : key_v.mv_size]))
  959. try:
  960. _check(lmdb.mdb_cursor_put(
  961. cur2, &dbl_key_v, &key_v, lmdb.MDB_NODUPDATA))
  962. except KeyExistsError:
  963. logger.debug(f'Double key {dbl_keys[i][: DBL_KLEN]} exists already.')
  964. pass
  965. else:
  966. raise ValueError(
  967. 'Index operation \'{}\' is not supported.'.format(op))
  968. i += 1
  969. finally:
  970. #pass
  971. self._cur_close(cur1)
  972. self._cur_close(cur2)
  973. cpdef void _remove_graph(self, object gr_uri) except *:
  974. """
  975. Delete a context.
  976. """
  977. cdef:
  978. Hash chash
  979. unsigned char ck[KLEN]
  980. unsigned char *pk_c
  981. size_t c_size
  982. lmdb.MDB_val ck_v, chash_v
  983. #logger.debug('Deleting context: {}'.format(gr_uri))
  984. #logger.debug('Pickled context: {}'.format(serialize(gr_uri)))
  985. # Gather information on the graph prior to deletion.
  986. try:
  987. self._to_key(gr_uri, &ck)
  988. except KeyNotFoundError:
  989. return
  990. # Remove all triples and indices associated with the graph.
  991. self._remove((None, None, None), gr_uri)
  992. # Remove the graph if it is in triples.
  993. self._remove((gr_uri, None, None))
  994. self._remove((None, None, gr_uri))
  995. # Clean up all terms related to the graph.
  996. serialize(gr_uri, &pk_c, &c_size)
  997. hash_(pk_c, c_size, &chash)
  998. free(pk_c)
  999. ck_v.mv_size = KLEN
  1000. chash_v.mv_size = HLEN
  1001. try:
  1002. ck_v.mv_data = ck
  1003. _check(lmdb.mdb_del(self.txn, self.get_dbi(b'c:'), &ck_v, NULL))
  1004. ck_v.mv_data = ck
  1005. _check(lmdb.mdb_del(self.txn, self.get_dbi(b't:st'), &ck_v, NULL))
  1006. chash_v.mv_data = chash
  1007. _check(lmdb.mdb_del(self.txn, self.get_dbi(b'th:t'), &chash_v, NULL))
  1008. except KeyNotFoundError:
  1009. pass
  1010. # Lookup methods.
  1011. # TODO Deprecate RDFLib API?
  1012. def contexts(self, triple=None):
  1013. """
  1014. Get a list of all contexts.
  1015. :rtype: Iterator(rdflib.Graph)
  1016. """
  1017. for ctx_uri in self.all_contexts(triple):
  1018. yield Graph(identifier=self.from_key(ctx_uri), store=self)
  1019. def triples(self, triple_pattern, context=None):
  1020. """
  1021. Generator over matching triples.
  1022. :param tuple triple_pattern: 3 RDFLib terms
  1023. :param context: Context graph, if available.
  1024. :type context: rdflib.Graph or None
  1025. :rtype: Iterator
  1026. :return: Generator over triples and contexts in which each result has
  1027. the following format::
  1028. (s, p, o), generator(contexts)
  1029. Where the contexts generator lists all context that the triple appears
  1030. in.
  1031. """
  1032. cdef:
  1033. size_t i = 0, j = 0
  1034. unsigned char spok[TRP_KLEN]
  1035. unsigned char ck[KLEN]
  1036. lmdb.MDB_val key_v, data_v
  1037. # This sounds strange, RDFLib should be passing None at this point,
  1038. # but anyway...
  1039. context = self._normalize_context(context)
  1040. logger.debug(
  1041. 'Getting triples for: {}, {}'.format(triple_pattern, context))
  1042. rset = self.triple_keys(triple_pattern, context)
  1043. #logger.debug('Triple keys found: {}'.format(rset.data[:rset.size]))
  1044. cur = self._cur_open('spo:c')
  1045. try:
  1046. key_v.mv_size = TRP_KLEN
  1047. for i in range(rset.ct):
  1048. #logger.debug('Checking contexts for triples: {}'.format(
  1049. # (rset.data + i * TRP_KLEN)[:TRP_KLEN]))
  1050. key_v.mv_data = rset.data + i * TRP_KLEN
  1051. # Get contexts associated with each triple.
  1052. contexts = []
  1053. # This shall never be MDB_NOTFOUND.
  1054. _check(lmdb.mdb_cursor_get(cur, &key_v, &data_v, lmdb.MDB_SET))
  1055. while True:
  1056. c_uri = self.from_key(<Key>data_v.mv_data)
  1057. contexts.append(Graph(identifier=c_uri, store=self))
  1058. try:
  1059. _check(lmdb.mdb_cursor_get(
  1060. cur, &key_v, &data_v, lmdb.MDB_NEXT_DUP))
  1061. except KeyNotFoundError:
  1062. break
  1063. #logger.debug('Triple keys before yield: {}: {}.'.format(
  1064. # (<TripleKey>key_v.mv_data)[:TRP_KLEN], tuple(contexts)))
  1065. yield self.from_trp_key(
  1066. (<TripleKey>key_v.mv_data)[: TRP_KLEN]), tuple(contexts)
  1067. #logger.debug('After yield.')
  1068. finally:
  1069. self._cur_close(cur)
  1070. cpdef ResultSet triple_keys(self, tuple triple_pattern, context=None):
  1071. """
  1072. Top-level lookup method.
  1073. This method is used by `triples` which returns native Python tuples,
  1074. as well as by other methods that need to iterate and filter triple
  1075. keys without incurring in the overhead of converting them to triples.
  1076. :param tuple triple_pattern: 3 RDFLib terms
  1077. :param context: Context graph or URI, or None.
  1078. :type context: rdflib.term.Identifier or None
  1079. """
  1080. # TODO: Improve performance by allowing passing contexts as a tuple.
  1081. cdef:
  1082. unsigned char tk[KLEN]
  1083. unsigned char ck[KLEN]
  1084. unsigned char spok[TRP_KLEN]
  1085. #unsigned char *pk_c
  1086. size_t ct = 0, flt_j = 0, i = 0, j = 0, pg_offset = 0, c_size
  1087. lmdb.MDB_cursor *icur
  1088. lmdb.MDB_val key_v, data_v
  1089. ResultSet flt_res, ret
  1090. if context is not None:
  1091. #serialize(context, &pk_c, &c_size)
  1092. try:
  1093. self._to_key(context, &ck)
  1094. except KeyNotFoundError:
  1095. # Context not found.
  1096. return ResultSet(0, TRP_KLEN)
  1097. icur = self._cur_open('c:spo')
  1098. try:
  1099. key_v.mv_data = ck
  1100. key_v.mv_size = KLEN
  1101. # s p o c
  1102. if all(triple_pattern):
  1103. #logger.debug('Lookup: s p o c')
  1104. for i, term in enumerate(triple_pattern):
  1105. try:
  1106. self._to_key(term, &tk)
  1107. except KeyNotFoundError:
  1108. # Context not found.
  1109. return ResultSet(0, TRP_KLEN)
  1110. memcpy(spok + (KLEN * i), tk, KLEN)
  1111. if tk is NULL:
  1112. # A term in the triple is not found.
  1113. return ResultSet(0, TRP_KLEN)
  1114. data_v.mv_data = spok
  1115. data_v.mv_size = TRP_KLEN
  1116. #logger.debug(
  1117. # 'Found spok {}. Matching with context {}'.format(
  1118. # (<TripleKey>data_v.mv_data)[: TRP_KLEN],
  1119. # (<Key>key_v.mv_data)[: KLEN]))
  1120. try:
  1121. _check(lmdb.mdb_cursor_get(
  1122. icur, &key_v, &data_v, lmdb.MDB_GET_BOTH))
  1123. except KeyNotFoundError:
  1124. # Triple not found.
  1125. #logger.debug('spok / ck pair not found.')
  1126. return ResultSet(0, TRP_KLEN)
  1127. ret = ResultSet(1, TRP_KLEN)
  1128. memcpy(ret.data, spok, TRP_KLEN)
  1129. return ret
  1130. # ? ? ? c
  1131. elif not any(triple_pattern):
  1132. # Get all triples from the context
  1133. #logger.debug('Lookup: ? ? ? c')
  1134. try:
  1135. _check(lmdb.mdb_cursor_get(
  1136. icur, &key_v, &data_v, lmdb.MDB_SET))
  1137. except KeyNotFoundError:
  1138. # Triple not found.
  1139. return ResultSet(0, TRP_KLEN)
  1140. _check(lmdb.mdb_cursor_count(icur, &ct))
  1141. ret = ResultSet(ct, TRP_KLEN)
  1142. logger.debug(f'Entries in c:spo: {ct}')
  1143. logger.debug(f'Allocated {ret.size} bytes.')
  1144. logger.debug('Looking in key: {}'.format(
  1145. (<unsigned char *>key_v.mv_data)[:key_v.mv_size]))
  1146. _check(lmdb.mdb_cursor_get(
  1147. icur, &key_v, &data_v, lmdb.MDB_GET_MULTIPLE))
  1148. while True:
  1149. #logger.debug(f'Data offset: {pg_offset} Page size: {data_v.mv_size} bytes')
  1150. #logger.debug('Data page: {}'.format(
  1151. # (<unsigned char *>data_v.mv_data)[: data_v.mv_size]))
  1152. memcpy(ret.data + pg_offset, data_v.mv_data, data_v.mv_size)
  1153. pg_offset += data_v.mv_size
  1154. try:
  1155. _check(lmdb.mdb_cursor_get(
  1156. icur, &key_v, &data_v, lmdb.MDB_NEXT_MULTIPLE))
  1157. except KeyNotFoundError:
  1158. return ret
  1159. # Regular lookup. Filter _lookup() results by context.
  1160. else:
  1161. try:
  1162. res = self._lookup(triple_pattern)
  1163. except KeyNotFoundError:
  1164. return ResultSet(0, TRP_KLEN)
  1165. #logger.debug('Allocating for context filtering.')
  1166. key_v.mv_data = ck
  1167. key_v.mv_size = KLEN
  1168. data_v.mv_size = TRP_KLEN
  1169. flt_res = ResultSet(res.ct, res.itemsize)
  1170. while j < res.ct:
  1171. #logger.debug('Checking row #{}'.format(flt_j))
  1172. data_v.mv_data = res.data + j * res.itemsize
  1173. #logger.debug('Checking c:spo {}, {}'.format(
  1174. # (<unsigned char *>key_v.mv_data)[: key_v.mv_size],
  1175. # (<unsigned char *>data_v.mv_data)[: data_v.mv_size]))
  1176. try:
  1177. # Verify that the triple is associated with the
  1178. # context being searched.
  1179. _check(lmdb.mdb_cursor_get(
  1180. icur, &key_v, &data_v, lmdb.MDB_GET_BOTH))
  1181. except KeyNotFoundError:
  1182. #logger.debug('Discarding source[{}].'.format(j))
  1183. continue
  1184. else:
  1185. #logger.debug('Copying source[{}] to dest[{}].'.format(
  1186. # j, flt_j))
  1187. memcpy(
  1188. flt_res.data + res.itemsize * flt_j,
  1189. res.data + res.itemsize * j, res.itemsize)
  1190. flt_j += 1
  1191. finally:
  1192. j += 1
  1193. # Resize result set to the size of context matches.
  1194. # This crops the memory block without copying it.
  1195. flt_res.resize(flt_j)
  1196. return flt_res
  1197. finally:
  1198. self._cur_close(icur)
  1199. # Unfiltered lookup. No context checked.
  1200. else:
  1201. #logger.debug('No context in query.')
  1202. try:
  1203. res = self._lookup(triple_pattern)
  1204. except KeyNotFoundError:
  1205. return ResultSet(0, TRP_KLEN)
  1206. #logger.debug('Res data before triple_keys return: {}'.format(
  1207. # res.data[: res.size]))
  1208. return res
  1209. cdef ResultSet _lookup(self, tuple triple_pattern):
  1210. """
  1211. Look up triples in the indices based on a triple pattern.
  1212. :rtype: Iterator
  1213. :return: Matching triple keys.
  1214. """
  1215. cdef:
  1216. TripleKey spok
  1217. lmdb.MDB_stat db_stat
  1218. size_t ct = 0, i = 0
  1219. lmdb.MDB_val spok_v, ck_v
  1220. s, p, o = triple_pattern
  1221. if s is not None:
  1222. if p is not None:
  1223. # s p o
  1224. if o is not None:
  1225. spok_v.mv_data = spok
  1226. spok_v.mv_size = TRP_KLEN
  1227. try:
  1228. self._to_triple_key(triple_pattern, &spok)
  1229. _check(lmdb.mdb_get(
  1230. self.txn, self.get_dbi('spo:c'), &spok_v, &ck_v))
  1231. except KeyNotFoundError:
  1232. return ResultSet(0, TRP_KLEN)
  1233. matches = ResultSet(1, TRP_KLEN)
  1234. memcpy(matches.data, spok, TRP_KLEN)
  1235. return matches
  1236. # s p ?
  1237. else:
  1238. return self._lookup_2bound(0, s, 1, p)
  1239. else:
  1240. # s ? o
  1241. if o is not None:
  1242. return self._lookup_2bound(0, s, 2, o)
  1243. # s ? ?
  1244. else:
  1245. return self._lookup_1bound(0, s)
  1246. else:
  1247. if p is not None:
  1248. # ? p o
  1249. if o is not None:
  1250. return self._lookup_2bound(1, p, 2, o)
  1251. # ? p ?
  1252. else:
  1253. return self._lookup_1bound(1, p)
  1254. else:
  1255. # ? ? o
  1256. if o is not None:
  1257. return self._lookup_1bound(2, o)
  1258. # ? ? ?
  1259. else:
  1260. # Get all triples in the database.
  1261. logger.debug('Getting all DB triples.')
  1262. dcur = self._cur_open('spo:c')
  1263. try:
  1264. _check(lmdb.mdb_stat(
  1265. self.txn, lmdb.mdb_cursor_dbi(dcur), &db_stat),
  1266. 'Error gathering DB stats.')
  1267. ct = db_stat.ms_entries
  1268. ret = ResultSet(ct, TRP_KLEN)
  1269. logger.debug(f'Triples found: {ct}')
  1270. if ct == 0:
  1271. return ResultSet(0, TRP_KLEN)
  1272. _check(lmdb.mdb_cursor_get(
  1273. dcur, &key_v, &data_v, lmdb.MDB_FIRST))
  1274. while True:
  1275. logger.debug(f'i in 0bound: {i}')
  1276. memcpy(
  1277. ret.data + ret.itemsize * i,
  1278. key_v.mv_data, TRP_KLEN)
  1279. try:
  1280. _check(lmdb.mdb_cursor_get(
  1281. dcur, &key_v, &data_v, lmdb.MDB_NEXT_NODUP))
  1282. except KeyNotFoundError:
  1283. break
  1284. i += 1
  1285. # Size is guessed from all entries. Unique keys will be
  1286. # much less than that.
  1287. ret.resize(i + 1)
  1288. #logger.debug('Assembled data: {}'.format(ret.data[:ret.size]))
  1289. return ret
  1290. finally:
  1291. self._cur_close(dcur)
  1292. cdef ResultSet _lookup_1bound(self, unsigned char idx, term):
  1293. """
  1294. Lookup triples for a pattern with one bound term.
  1295. :param str idx_name: The index to look up as one of the keys of
  1296. ``_lookup_ordering``.
  1297. :param rdflib.URIRef term: Bound term to search for.
  1298. :rtype: Iterator(bytes)
  1299. :return: SPO keys matching the pattern.
  1300. """
  1301. cdef:
  1302. unsigned char luk[KLEN]
  1303. unsigned int dbflags
  1304. unsigned char asm_rng[3]
  1305. size_t ct, ret_offset = 0, src_pos, ret_pos
  1306. size_t j # Must be signed for older OpenMP versions
  1307. lmdb.MDB_cursor *icur
  1308. logger.debug(f'lookup 1bound: {idx}, {term}')
  1309. try:
  1310. self._to_key(term, &luk)
  1311. except KeyNotFoundError:
  1312. return ResultSet(0, TRP_KLEN)
  1313. logging.debug('luk: {}'.format(luk))
  1314. term_order = lookup_ordering[idx]
  1315. icur = self._cur_open(self.lookup_indices[idx])
  1316. logging.debug(f'DB label: {self.lookup_indices[idx]}')
  1317. logging.debug('term order: {}'.format(term_order[: 3]))
  1318. try:
  1319. key_v.mv_data = luk
  1320. key_v.mv_size = KLEN
  1321. _check(lmdb.mdb_cursor_get(icur, &key_v, &data_v, lmdb.MDB_SET))
  1322. _check(lmdb.mdb_cursor_count(icur, &ct))
  1323. # Allocate memory for results.
  1324. ret = ResultSet(ct, TRP_KLEN)
  1325. logger.debug(f'Entries for {self.lookup_indices[idx]}: {ct}')
  1326. logger.debug(f'Allocated {ret.size} bytes of data.')
  1327. #logger.debug('First row: {}'.format(
  1328. # (<unsigned char *>data_v.mv_data)[:DBL_KLEN]))
  1329. # Arrange results according to lookup order.
  1330. asm_rng = [
  1331. KLEN * term_order[0],
  1332. KLEN * term_order[1],
  1333. KLEN * term_order[2],
  1334. ]
  1335. logger.debug('asm_rng: {}'.format(asm_rng[:3]))
  1336. logger.debug('luk: {}'.format(luk))
  1337. _check(lmdb.mdb_cursor_get(icur, &key_v, &data_v, lmdb.MDB_SET))
  1338. _check(lmdb.mdb_cursor_get(
  1339. icur, &key_v, &data_v, lmdb.MDB_GET_MULTIPLE))
  1340. while True:
  1341. logger.debug('ret_offset: {}'.format(ret_offset))
  1342. logger.debug(f'Page size: {data_v.mv_size}')
  1343. #logger.debug(
  1344. # 'Got data in 1bound ({}): {}'.format(
  1345. # data_v.mv_size,
  1346. # (<unsigned char *>data_v.mv_data)[: data_v.mv_size]))
  1347. for j in prange(data_v.mv_size // DBL_KLEN, nogil=True):
  1348. src_pos = DBL_KLEN * j
  1349. ret_pos = (ret_offset + ret.itemsize * j)
  1350. memcpy(ret.data + ret_pos + asm_rng[0], luk, KLEN)
  1351. memcpy(ret.data + ret_pos + asm_rng[1],
  1352. data_v.mv_data + src_pos, KLEN)
  1353. memcpy(ret.data + ret_pos + asm_rng[2],
  1354. data_v.mv_data + src_pos + KLEN, KLEN)
  1355. # Increment MUST be done before MDB_NEXT_MULTIPLE otherwise
  1356. # data_v.mv_size will be overwritten with the *next* page size
  1357. # and cause corruption in the output data.
  1358. ret_offset += data_v.mv_size // DBL_KLEN * ret.itemsize
  1359. try:
  1360. # Get results by the page.
  1361. _check(lmdb.mdb_cursor_get(
  1362. icur, &key_v, &data_v, lmdb.MDB_NEXT_MULTIPLE))
  1363. except KeyNotFoundError:
  1364. # For testing only. Errors will be caught in triples()
  1365. # when looking for a context.
  1366. #if ret_offset + ret.itemsize < ret.size:
  1367. # raise RuntimeError(
  1368. # 'Retrieved less values than expected: {} of {}.'
  1369. # .format(src_offset, ret.size))
  1370. return ret
  1371. #logger.debug('Assembled data in 1bound ({}): {}'.format(ret.size, ret.data[: ret.size]))
  1372. finally:
  1373. self._cur_close(icur)
  1374. cdef ResultSet _lookup_2bound(
  1375. self, unsigned char idx1, term1, unsigned char idx2, term2):
  1376. """
  1377. Look up triples for a pattern with two bound terms.
  1378. :param str idx1: The index to look up as one of the keys of
  1379. ``lookup_ordering_2bound``.
  1380. :param rdflib.URIRef term1: First bound term to search for.
  1381. :rtype: Iterator(bytes)
  1382. :return: SPO keys matching the pattern.
  1383. """
  1384. cdef:
  1385. unsigned char luk1_offset, luk2_offset
  1386. unsigned char luk1[KLEN]
  1387. unsigned char luk2[KLEN]
  1388. unsigned char luk[DBL_KLEN]
  1389. unsigned int dbflags
  1390. unsigned char asm_rng[3]
  1391. unsigned char term_order[3] # Lookup ordering
  1392. size_t ct, i = 0, ret_offset = 0, ret_pos, src_pos
  1393. size_t j # Must be signed for older OpenMP versions
  1394. lmdb.MDB_cursor *icur
  1395. ResultSet ret
  1396. logging.debug(
  1397. f'2bound lookup for term {term1} at position {idx1} '
  1398. f'and term {term2} at position {idx2}.')
  1399. try:
  1400. self._to_key(term1, &luk1)
  1401. self._to_key(term2, &luk2)
  1402. except KeyNotFoundError:
  1403. return ResultSet(0, TRP_KLEN)
  1404. logging.debug('luk1: {}'.format(luk1[: KLEN]))
  1405. logging.debug('luk2: {}'.format(luk2[: KLEN]))
  1406. for i in range(3):
  1407. if (
  1408. idx1 in lookup_ordering_2bound[i][: 2]
  1409. and idx2 in lookup_ordering_2bound[i][: 2]):
  1410. term_order = lookup_ordering_2bound[i]
  1411. if term_order[0] == idx1:
  1412. luk1_offset = 0
  1413. luk2_offset = KLEN
  1414. else:
  1415. luk1_offset = KLEN
  1416. luk2_offset = 0
  1417. dblabel = self.lookup_indices[i + 3] # skip 1bound index labels
  1418. break
  1419. if i == 2:
  1420. raise ValueError(
  1421. 'Indices {} and {} not found in LU keys.'.format(
  1422. idx1, idx2))
  1423. logger.debug('Term order: {}'.format(term_order[:3]))
  1424. logger.debug('LUK offsets: {}, {}'.format(luk1_offset, luk2_offset))
  1425. # Compose terms in lookup key.
  1426. memcpy(luk + luk1_offset, luk1, KLEN)
  1427. memcpy(luk + luk2_offset, luk2, KLEN)
  1428. logger.debug('Lookup key: {}'.format(luk))
  1429. icur = self._cur_open(dblabel)
  1430. logger.debug('Database label: {}'.format(dblabel))
  1431. try:
  1432. key_v.mv_data = luk
  1433. key_v.mv_size = DBL_KLEN
  1434. # Count duplicates for key and allocate memory for result set.
  1435. _check(lmdb.mdb_cursor_get(icur, &key_v, &data_v, lmdb.MDB_SET))
  1436. _check(lmdb.mdb_cursor_count(icur, &ct))
  1437. ret = ResultSet(ct, TRP_KLEN)
  1438. #logger.debug('Entries for {}: {}'.format(self.lookup_indices[idx], ct))
  1439. #logger.debug('First row: {}'.format(
  1440. # (<unsigned char *>data_v.mv_data)[:DBL_KLEN]))
  1441. # Arrange results according to lookup order.
  1442. asm_rng = [
  1443. KLEN * term_order[0],
  1444. KLEN * term_order[1],
  1445. KLEN * term_order[2],
  1446. ]
  1447. logger.debug('asm_rng: {}'.format(asm_rng[:3]))
  1448. logger.debug('luk: {}'.format(luk))
  1449. _check(lmdb.mdb_cursor_get(icur, &key_v, &data_v, lmdb.MDB_SET))
  1450. _check(lmdb.mdb_cursor_get(
  1451. icur, &key_v, &data_v, lmdb.MDB_GET_MULTIPLE))
  1452. while True:
  1453. logger.debug('Got data in 2bound ({}): {}'.format(
  1454. data_v.mv_size,
  1455. (<unsigned char *>data_v.mv_data)[: data_v.mv_size]))
  1456. for j in prange(data_v.mv_size // KLEN, nogil=True):
  1457. src_pos = KLEN * j
  1458. ret_pos = (ret_offset + ret.itemsize * j)
  1459. #logger.debug('Page offset: {}'.format(pg_offset))
  1460. #logger.debug('Ret offset: {}'.format(ret_offset))
  1461. memcpy(ret.data + ret_pos + asm_rng[0], luk, KLEN)
  1462. memcpy(ret.data + ret_pos + asm_rng[1], luk + KLEN, KLEN)
  1463. memcpy(ret.data + ret_pos + asm_rng[2],
  1464. data_v.mv_data + src_pos, KLEN)
  1465. #logger.debug('Assembled triple: {}'.format((ret.data + ret_offset)[: TRP_KLEN]))
  1466. ret_offset += data_v.mv_size // KLEN * ret.itemsize
  1467. try:
  1468. # Get results by the page.
  1469. _check(lmdb.mdb_cursor_get(
  1470. icur, &key_v, &data_v, lmdb.MDB_NEXT_MULTIPLE))
  1471. except KeyNotFoundError:
  1472. # For testing only. Errors will be caught in triples()
  1473. # when looking for a context.
  1474. #if ret_offset + ret.itemsize < ret.size:
  1475. # raise RuntimeError(
  1476. # 'Retrieved less values than expected: {} of {}.'
  1477. # .format(pg_offset, ret.size))
  1478. #logger.debug('Assembled data in 2bound ({}): {}'.format(ret.size, ret.data[: ret.size]))
  1479. return ret
  1480. finally:
  1481. self._cur_close(icur)
  1482. cpdef ResultSet _all_term_keys(self, term_type):
  1483. """
  1484. Return all keys of a (``s:po``, ``p:so``, ``o:sp``) index.
  1485. """
  1486. cdef:
  1487. size_t i = 0
  1488. lmdb.MDB_stat stat
  1489. idx_label = self.lookup_indices['spo'.index(term_type)]
  1490. #logger.debug('Looking for all terms in index: {}'.format(idx_label))
  1491. icur = self._cur_open(idx_label)
  1492. try:
  1493. _check(lmdb.mdb_stat(self.txn, lmdb.mdb_cursor_dbi(icur), &stat))
  1494. # TODO: This may allocate memory for several times the amount
  1495. # needed. Even though it is resized later, we need to know how
  1496. # performance is affected by this.
  1497. ret = ResultSet(stat.ms_entries, KLEN)
  1498. try:
  1499. _check(lmdb.mdb_cursor_get(
  1500. icur, &key_v, NULL, lmdb.MDB_FIRST))
  1501. except KeyNotFoundError:
  1502. return ResultSet(0, DBL_KLEN)
  1503. while True:
  1504. memcpy(ret.data + ret.itemsize * i, key_v.mv_data, KLEN)
  1505. rc = lmdb.mdb_cursor_get(
  1506. icur, &key_v, NULL, lmdb.MDB_NEXT_NODUP)
  1507. try:
  1508. _check(rc)
  1509. except KeyNotFoundError:
  1510. ret.resize(i + 1)
  1511. return ret
  1512. i += 1
  1513. finally:
  1514. #pass
  1515. self._cur_close(icur)
  1516. def all_terms(self, term_type):
  1517. """
  1518. Return all terms of a type (``s``, ``p``, or ``o``) in the store.
  1519. """
  1520. for key in self._all_term_keys(term_type).to_tuple():
  1521. #logger.debug('Yielding: {}'.format(key))
  1522. yield self.from_key(key)
  1523. cpdef tuple all_namespaces(self):
  1524. """
  1525. Return all registered namespaces.
  1526. """
  1527. cdef:
  1528. size_t i = 0
  1529. lmdb.MDB_stat stat
  1530. ret = []
  1531. dcur = self._cur_open('pfx:ns')
  1532. try:
  1533. try:
  1534. _check(lmdb.mdb_cursor_get(
  1535. dcur, &key_v, &data_v, lmdb.MDB_FIRST))
  1536. except KeyNotFoundError:
  1537. return tuple()
  1538. while True:
  1539. ret.append((
  1540. (<unsigned char *>key_v.mv_data)[: key_v.mv_size].decode(),
  1541. (<unsigned char *>data_v.mv_data)[: data_v.mv_size].decode()))
  1542. #logger.debug('Found namespace: {}:{}'.format(<unsigned char *>key_v.mv_data, <unsigned char *>data_v.mv_data))
  1543. try:
  1544. _check(lmdb.mdb_cursor_get(
  1545. dcur, &key_v, &data_v, lmdb.MDB_NEXT))
  1546. except KeyNotFoundError:
  1547. return tuple(ret)
  1548. i += 1
  1549. finally:
  1550. #pass
  1551. self._cur_close(dcur)
  1552. cpdef tuple all_contexts(self, triple=None):
  1553. """
  1554. Get a list of all contexts.
  1555. :rtype: Iterator(rdflib.Graph)
  1556. """
  1557. cdef:
  1558. lmdb.MDB_stat stat
  1559. size_t i = 0
  1560. unsigned char spok[TRP_KLEN]
  1561. unsigned char ck[KLEN]
  1562. lmdb.MDB_cursor_op op
  1563. cur = (
  1564. self._cur_open('spo:c') if triple and all(triple)
  1565. else self._cur_open('c:'))
  1566. try:
  1567. if triple and all(triple):
  1568. _check(lmdb.mdb_stat(
  1569. self.txn, lmdb.mdb_cursor_dbi(cur), &stat))
  1570. ret = ResultSet(stat.ms_entries, KLEN)
  1571. self._to_triple_key(triple, &spok)
  1572. key_v.mv_data = spok
  1573. key_v.mv_size = TRP_KLEN
  1574. try:
  1575. _check(lmdb.mdb_cursor_get(
  1576. cur, &key_v, &data_v, lmdb.MDB_SET_KEY))
  1577. except KeyNotFoundError:
  1578. return tuple()
  1579. while True:
  1580. memcpy(ret.data + ret.itemsize * i, data_v.mv_data, KLEN)
  1581. try:
  1582. _check(lmdb.mdb_cursor_get(
  1583. cur, &key_v, &data_v, lmdb.MDB_NEXT_DUP))
  1584. except KeyNotFoundError:
  1585. break
  1586. i += 1
  1587. else:
  1588. _check(lmdb.mdb_stat(
  1589. self.txn, lmdb.mdb_cursor_dbi(cur), &stat))
  1590. ret = ResultSet(stat.ms_entries, KLEN)
  1591. try:
  1592. _check(lmdb.mdb_cursor_get(
  1593. cur, &key_v, &data_v, lmdb.MDB_FIRST))
  1594. except KeyNotFoundError:
  1595. return tuple()
  1596. while True:
  1597. memcpy(
  1598. ret.data + ret.itemsize * i, key_v.mv_data, KLEN)
  1599. try:
  1600. _check(lmdb.mdb_cursor_get(
  1601. cur, &key_v, NULL, lmdb.MDB_NEXT))
  1602. except KeyNotFoundError:
  1603. break
  1604. i += 1
  1605. return ret.to_tuple()
  1606. finally:
  1607. #pass
  1608. self._cur_close(cur)
  1609. # Key conversion methods.
  1610. cdef object from_key(self, Key key):
  1611. """
  1612. Convert a single or multiple key into one or more terms.
  1613. :param Key key: The key to be converted.
  1614. """
  1615. cdef:
  1616. unsigned char *pk
  1617. key_v.mv_data = key
  1618. key_v.mv_size = KLEN
  1619. _check(
  1620. lmdb.mdb_get(self.txn, self.get_dbi('t:st'), &key_v, &data_v),
  1621. 'Error getting data for key \'{}\'.'.format(key))
  1622. return deserialize(
  1623. <unsigned char *>data_v.mv_data, data_v.mv_size)
  1624. cdef tuple from_trp_key(self, TripleKey key):
  1625. """
  1626. Convert a single or multiple key into one or more terms.
  1627. :param Key key: The key to be converted.
  1628. """
  1629. #logger.debug(f'From triple key: {key[: TRP_KLEN]}')
  1630. return (
  1631. self.from_key(key),
  1632. self.from_key(key + KLEN),
  1633. self.from_key(key + DBL_KLEN))
  1634. cdef inline void _to_key(self, term, Key *key) except *:
  1635. """
  1636. Convert a triple, quad or term into a key.
  1637. The key is the checksum of the serialized object, therefore unique for
  1638. that object.
  1639. :param rdflib.Term term: An RDFLib term (URIRef, BNode, Literal).
  1640. :param Key key: Pointer to the key that will be produced.
  1641. :rtype: void
  1642. """
  1643. cdef:
  1644. unsigned char *pk_t
  1645. size_t term_size
  1646. Hash thash
  1647. serialize(term, &pk_t, &term_size)
  1648. #logger.debug('Hashing pickle: {} with lentgh: {}'.format(pk_t, term_size))
  1649. hash_(pk_t, term_size, &thash)
  1650. free(pk_t)
  1651. #logger.debug('Hash to search for: {}'.format(thash[: HLEN]))
  1652. key_v.mv_data = &thash
  1653. key_v.mv_size = HLEN
  1654. dbi = self.get_dbi('th:t')
  1655. logger.debug(f'DBI: {dbi}')
  1656. _check(lmdb.mdb_get(self.txn, dbi, &key_v, &data_v))
  1657. #logger.debug('Found key: {}'.format((<Key>data_v.mv_data)[: KLEN]))
  1658. key[0] = <Key>data_v.mv_data
  1659. cdef inline void _to_triple_key(self, tuple terms, TripleKey *tkey) except *:
  1660. """
  1661. Convert a tuple of 3 terms into a triple key.
  1662. """
  1663. cdef:
  1664. char i = 0
  1665. Key key
  1666. while i < 3:
  1667. self._to_key(terms[i], &key)
  1668. memcpy(tkey[0] + (KLEN * i), key, KLEN)
  1669. if key is NULL:
  1670. # A term in the triple is not found.
  1671. tkey = NULL
  1672. return
  1673. i += 1
  1674. cdef void _append(
  1675. self, unsigned char *value, size_t vlen, Key *nkey,
  1676. unsigned char *dblabel=b'', lmdb.MDB_txn *txn=NULL,
  1677. unsigned int flags=0) except *:
  1678. """
  1679. Append one or more keys and values to the end of a database.
  1680. :param lmdb.Cursor cur: The write cursor to act on.
  1681. :param list(bytes) values: Value(s) to append.
  1682. :rtype: list(memoryview)
  1683. :return: Last key(s) inserted.
  1684. """
  1685. cdef:
  1686. unsigned char key[KLEN]
  1687. lmdb.MDB_cursor *cur
  1688. if txn is NULL:
  1689. txn = self.txn
  1690. cur = self._cur_open(dblabel, txn=txn)
  1691. try:
  1692. _check(lmdb.mdb_cursor_get(cur, &key_v, NULL, lmdb.MDB_LAST))
  1693. except KeyNotFoundError:
  1694. memcpy(nkey[0], first_key, KLEN)
  1695. else:
  1696. memcpy(key, key_v.mv_data, KLEN)
  1697. self._next_key(key, nkey)
  1698. finally:
  1699. #pass
  1700. self._cur_close(cur)
  1701. key_v.mv_data = nkey
  1702. key_v.mv_size = KLEN
  1703. data_v.mv_data = value
  1704. data_v.mv_size = vlen
  1705. #logger.debug('Appending value {} to db {} with key: {}'.format(
  1706. # value[: vlen], dblabel.decode(), nkey[0][:KLEN]))
  1707. #logger.debug('data size: {}'.format(data_v.mv_size))
  1708. lmdb.mdb_put(
  1709. txn, self.get_dbi(dblabel), &key_v, &data_v,
  1710. flags | lmdb.MDB_APPEND)
  1711. cdef void _next_key(self, const Key key, Key *nkey) except *:
  1712. """
  1713. Calculate the next closest byte sequence in lexicographical order.
  1714. This is used to fill the next available slot after the last one in
  1715. LMDB. Keys are byte strings, which is a convenient way to keep key
  1716. lengths as small as possible since they are referenced in several
  1717. indices.
  1718. This function assumes that all the keys are padded with the `start`
  1719. value up to the `max_len` length.
  1720. :param bytes n: Current byte sequence to add to.
  1721. """
  1722. cdef:
  1723. size_t i = KLEN
  1724. memcpy(nkey[0], key, KLEN)
  1725. #logger.debug('Last key in _next_key: {}'.format(key[0]))
  1726. while i > 0:
  1727. i -= 1
  1728. if nkey[0][i] < 255:
  1729. nkey[0][i] += 1
  1730. break
  1731. # If the value exceeds 255, i.e. the current value is the last one
  1732. else:
  1733. # If we are already at the leftmost byte, and this is already
  1734. # at 255, the sequence is exhausted.
  1735. if i == 0:
  1736. raise RuntimeError(
  1737. 'BAD DAY: Sequence exhausted. No more '
  1738. 'combinations are possible.')
  1739. # Move one position up and try to increment that.
  1740. else:
  1741. nkey[0][i] = KEY_START
  1742. #logger.debug('New key: {}'.format(nkey[0][:KLEN]))