lmdb_triplestore.pyx 69 KB

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