lmdb_triplestore.pyx 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508
  1. import logging
  2. from rdflib import Graph
  3. from rdflib.graph import DATASET_DEFAULT_GRAPH_ID as RDFLIB_DEFAULT_GRAPH_URI
  4. from lakesuperior.store.base_lmdb_store import (
  5. KeyExistsError, KeyNotFoundError, LmdbError)
  6. from lakesuperior.store.base_lmdb_store cimport _check
  7. from cython.parallel import prange
  8. from libc.stdlib cimport free
  9. from libc.string cimport memcpy
  10. cimport lakesuperior.cy_include.cylmdb as lmdb
  11. cimport lakesuperior.cy_include.cytpl as tpl
  12. from lakesuperior.store.ldp_rs.term cimport Term
  13. from lakesuperior.store.base_lmdb_store cimport (
  14. BaseLmdbStore, data_v, dbi, key_v)
  15. from lakesuperior.store.ldp_rs.keyset cimport Keyset
  16. from lakesuperior.store.ldp_rs.term cimport deserialize, serialize
  17. from lakesuperior.util.hash cimport HLEN, Hash128, hash128
  18. FIRST_KEY = <bytes>KEY_START * KLEN
  19. """First key of a sequence."""
  20. IDX_OP_ADD = '_idx_add'
  21. IDX_OP_REMOVE = '_idx_remove'
  22. lookup_rank = [0, 2, 1]
  23. """
  24. Order in which keys are looked up if two terms are bound.
  25. The indices with the smallest average number of values per key should be
  26. looked up first.
  27. 0 = s:po
  28. 1 = p:so
  29. 2 = o:sp
  30. If we want to get fancy, this can be rebalanced from time to time by
  31. looking up the number of keys in (s:po, p:so, o:sp).
  32. """
  33. lookup_ordering = [
  34. [0, 1, 2], # spo
  35. [1, 0, 2], # pso
  36. [2, 0, 1], # osp
  37. ]
  38. lookup_ordering_2bound = [
  39. [1, 2, 0], # po:s
  40. [0, 2, 1], # so:p
  41. [0, 1, 2], # sp:o
  42. ]
  43. logger = logging.getLogger(__name__)
  44. cdef class LmdbTriplestore(BaseLmdbStore):
  45. """
  46. Low-level storage layer.
  47. This class extends the RDFLib-compatible :py:class:`BaseLmdbStore` and maps
  48. triples and contexts to key-value records in LMDB.
  49. This class uses the original LMDB C API rather than the Python bindings,
  50. because several data manipulations happen after retrieval from the store,
  51. which are more efficiently performed at the C level.
  52. """
  53. dbi_labels = [
  54. # Main data
  55. # Term key to serialized term content
  56. 't:st',
  57. # Joined triple keys to context key
  58. 'spo:c',
  59. # This has empty values and is used to keep track of empty contexts.
  60. 'c:',
  61. # Prefix to namespace
  62. 'pfx:ns',
  63. # Indices
  64. # Namespace to prefix
  65. 'ns:pfx',
  66. # Term hash to triple key
  67. 'th:t',
  68. # Lookups
  69. 's:po',
  70. 'p:so',
  71. 'o:sp',
  72. 'po:s',
  73. 'so:p',
  74. 'sp:o',
  75. 'c:spo',
  76. ]
  77. lookup_indices = [
  78. b's:po',
  79. b'p:so',
  80. b'o:sp',
  81. b'po:s',
  82. b'so:p',
  83. b'sp:o',
  84. ]
  85. dbi_flags = {
  86. 's:po': lmdb.MDB_DUPSORT | lmdb.MDB_DUPFIXED,
  87. 'p:so': lmdb.MDB_DUPSORT | lmdb.MDB_DUPFIXED,
  88. 'o:sp': lmdb.MDB_DUPSORT | lmdb.MDB_DUPFIXED,
  89. 'po:s': lmdb.MDB_DUPSORT | lmdb.MDB_DUPFIXED,
  90. 'so:p': lmdb.MDB_DUPSORT | lmdb.MDB_DUPFIXED,
  91. 'sp:o': lmdb.MDB_DUPSORT | lmdb.MDB_DUPFIXED,
  92. 'c:spo': lmdb.MDB_DUPSORT | lmdb.MDB_DUPFIXED,
  93. 'spo:c': lmdb.MDB_DUPSORT | lmdb.MDB_DUPFIXED,
  94. }
  95. flags = 0
  96. options = {
  97. 'map_size': 1024 ** 4 # 1Tb.
  98. }
  99. # DB management methods.
  100. cpdef dict stats(self):
  101. """
  102. Gather statistics about the database."""
  103. st = self._stats()
  104. st['num_triples'] = st['db_stats']['spo:c']['ms_entries']
  105. return st
  106. cpdef size_t _len(self, context=None) except -1:
  107. """
  108. Return the length of the dataset.
  109. The RDFLib interface defines `__len__` in a nonstandard way that
  110. causes a Cython compilation error, so this method is called by the
  111. `__len__` method of its Python counterpart.
  112. """
  113. cdef:
  114. size_t ct
  115. if context is not None:
  116. self._to_key(context, <Key *>key_v.mv_data)
  117. key_v.mv_size = KLEN
  118. cur = self._cur_open('c:spo')
  119. try:
  120. _check(lmdb.mdb_cursor_get(
  121. cur, &key_v, NULL, lmdb.MDB_SET))
  122. _check(lmdb.mdb_cursor_count(cur, &ct))
  123. except KeyNotFoundError:
  124. return 0
  125. else:
  126. return ct
  127. finally:
  128. #pass
  129. self._cur_close(cur)
  130. else:
  131. return self.stats()['num_triples']
  132. ## PRIVATE METHODS ##
  133. # Triple and graph methods.
  134. cpdef add(self, triple, context=None, quoted=False):
  135. """
  136. Add a triple and start indexing.
  137. :param tuple(rdflib.Identifier) triple: Tuple of three identifiers.
  138. :param context: Context identifier. ``None`` inserts in the default
  139. graph.
  140. :type context: rdflib.Identifier or None
  141. :param bool quoted: Not used.
  142. """
  143. cdef:
  144. lmdb.MDB_cursor *icur
  145. lmdb.MDB_val spo_v, c_v, null_v
  146. unsigned char i
  147. unsigned char *pk_t
  148. Hash128 thash
  149. # Using Key or TripleKey here breaks Cython. This might be a bug.
  150. # See https://github.com/cython/cython/issues/2517
  151. unsigned char spock[QUAD_KLEN]
  152. unsigned char nkey[KLEN]
  153. size_t term_size
  154. c = self._normalize_context(context)
  155. if c is None:
  156. c = RDFLIB_DEFAULT_GRAPH_URI
  157. # TODO: figure out how the RDFLib dispatcher is inherited
  158. # (and if there is a use for it in a first place)
  159. #Store.add(self, triple, context)
  160. s, p, o = triple
  161. #logger.debug('Trying to add a triple.')
  162. icur = self._cur_open('th:t')
  163. try:
  164. for i, term in enumerate((s, p, o, c)):
  165. serialize(term, &pk_t, &term_size)
  166. thash = hash128(pk_t, term_size)
  167. try:
  168. key_v.mv_data = &thash
  169. key_v.mv_size = HLEN
  170. _check(lmdb.mdb_get(
  171. self.txn, self.get_dbi('th:t'), &key_v, &data_v))
  172. memcpy(spock + (i * KLEN), data_v.mv_data, KLEN)
  173. #logger.debug('Hash {} found. Not adding.'.format(thash[: HLEN]))
  174. except KeyNotFoundError:
  175. # If term is not found, add it...
  176. #logger.debug('Hash {} not found. Adding to DB.'.format(
  177. # thash[: HLEN]))
  178. self._append(pk_t, term_size, &nkey, dblabel=b't:st')
  179. free(pk_t)
  180. memcpy(spock + (i * KLEN), nkey, KLEN)
  181. # ...and index it.
  182. #logger.debug('Indexing on th:t: {}: {}'.format(
  183. # thash[: HLEN], nkey[: KLEN]))
  184. key_v.mv_data = thash
  185. key_v.mv_size = HLEN
  186. data_v.mv_data = nkey
  187. data_v.mv_size = KLEN
  188. _check(
  189. lmdb.mdb_cursor_put(icur, &key_v, &data_v, 0),
  190. 'Error setting key {}.'.format(thash))
  191. finally:
  192. #pass
  193. self._cur_close(icur)
  194. #logger.debug('Triple add action completed.')
  195. spo_v.mv_data = spock
  196. spo_v.mv_size = TRP_KLEN
  197. c_v.mv_data = spock + TRP_KLEN
  198. c_v.mv_size = KLEN
  199. null_v.mv_data = b''
  200. null_v.mv_size = 0
  201. #logger.debug('Adding context.')
  202. try:
  203. _check(lmdb.mdb_put(
  204. self.txn, self.get_dbi('c:'), &c_v, &null_v,
  205. lmdb.MDB_NOOVERWRITE))
  206. except KeyExistsError:
  207. pass
  208. #logger.debug('Added c:.')
  209. try:
  210. # Add triple:context association.
  211. _check(lmdb.mdb_put(
  212. self.txn, self.get_dbi('spo:c'), &spo_v, &c_v,
  213. lmdb.MDB_NODUPDATA))
  214. except KeyExistsError:
  215. pass
  216. #logger.debug('Added spo:c.')
  217. try:
  218. # Index context:triple association.
  219. _check(lmdb.mdb_put(
  220. self.txn, self.get_dbi('c:spo'), &c_v, &spo_v,
  221. lmdb.MDB_NODUPDATA))
  222. except KeyExistsError:
  223. pass
  224. #logger.debug('Added c:spo.')
  225. #logger.debug('All main data entered. Indexing.')
  226. self._index_triple(IDX_OP_ADD, spock[: TRP_KLEN])
  227. cpdef add_graph(self, graph):
  228. """
  229. Add a graph to the database.
  230. This creates an empty graph by associating the graph URI with the
  231. pickled `None` value. This prevents from removing the graph when all
  232. triples are removed.
  233. This may be called by read-only operations:
  234. https://github.com/RDFLib/rdflib/blob/master/rdflib/graph.py#L1623
  235. In which case it needs to open a write transaction. This is not ideal
  236. but the only way to handle datasets in RDFLib.
  237. :param rdflib.URIRef graph: URI of the named graph to add.
  238. """
  239. cdef:
  240. unsigned char *pk_c
  241. size_t pk_size
  242. if isinstance(graph, Graph):
  243. graph = graph.identifier
  244. serialize(graph, &pk_c, &pk_size)
  245. self._add_graph(pk_c, pk_size)
  246. free(pk_c)
  247. cdef void _add_graph(
  248. self, unsigned char *pk_c, size_t pk_size) except *:
  249. """
  250. Add a graph.
  251. :param pk_c: Pickled context URIRef object.
  252. :type pk_c: unsigned char*
  253. :param pk_size: Size of pickled string.
  254. :type pk_size: size_t
  255. """
  256. cdef:
  257. Hash128 chash
  258. unsigned char ck[KLEN]
  259. lmdb.MDB_txn *tmp_txn
  260. lmdb.MDB_cursor *th_cur
  261. lmdb.MDB_cursor *pk_cur
  262. lmdb.MDB_cursor *ck_cur
  263. chash = hash128(pk_c, pk_size)
  264. #logger.debug('Adding a graph.')
  265. if not self._key_exists(chash, HLEN, b'th:t'):
  266. # Insert context term if not existing.
  267. if self.is_txn_rw:
  268. #logger.debug('Working in existing RW transaction.')
  269. # Use existing R/W transaction.
  270. # Main entry.
  271. self._append(pk_c, pk_size, &ck, b't:st')
  272. # Index.
  273. self._put(chash, HLEN, ck, KLEN, b'th:t')
  274. # Add to list of contexts.
  275. self._put(ck, KLEN, b'', 0, 'c:')
  276. else:
  277. # Open new R/W transactions.
  278. #logger.debug('Opening a temporary RW transaction.')
  279. _check(lmdb.mdb_txn_begin(self.dbenv, NULL, 0, &tmp_txn))
  280. try:
  281. self._append(
  282. pk_c, pk_size, &ck, dblabel=b't:st', txn=tmp_txn)
  283. # Index.
  284. self._put(chash, HLEN, ck, KLEN, b'th:t', txn=tmp_txn)
  285. # Add to list of contexts.
  286. self._put(ck, KLEN, b'', 0, b'c:', txn=tmp_txn)
  287. _check(lmdb.mdb_txn_commit(tmp_txn))
  288. #logger.debug('Temp RW transaction closed.')
  289. except:
  290. lmdb.mdb_txn_abort(tmp_txn)
  291. raise
  292. cpdef void _remove(self, tuple triple_pattern, context=None) except *:
  293. cdef:
  294. unsigned char spok[TRP_KLEN]
  295. size_t i = 0
  296. Key ck
  297. lmdb.MDB_val spok_v, ck_v
  298. #logger.debug('Removing triple: {}'.format(triple_pattern))
  299. if context is not None:
  300. try:
  301. self._to_key(context, &ck)
  302. except KeyNotFoundError:
  303. # If context is specified but not found, return to avoid
  304. # deleting the wrong triples.
  305. return
  306. # Get the matching pattern.
  307. match_set = self.triple_keys(triple_pattern, context)
  308. dcur = self._cur_open('spo:c')
  309. icur = self._cur_open('c:spo')
  310. try:
  311. spok_v.mv_size = TRP_KLEN
  312. # If context was specified, remove only associations with that context.
  313. if context is not None:
  314. #logger.debug('Removing triples in matching context.')
  315. ck_v.mv_data = ck
  316. ck_v.mv_size = KLEN
  317. while i < match_set.ct:
  318. memcpy(
  319. spok, match_set.data + match_set.itemsize * i,
  320. TRP_KLEN)
  321. spok_v.mv_data = spok
  322. # Delete spo:c entry.
  323. try:
  324. _check(lmdb.mdb_cursor_get(
  325. dcur, &spok_v, &ck_v, lmdb.MDB_GET_BOTH))
  326. except KeyNotFoundError:
  327. pass
  328. else:
  329. _check(lmdb.mdb_cursor_del(dcur, 0))
  330. # Restore ck after delete.
  331. ck_v.mv_data = ck
  332. # Delete c:spo entry.
  333. try:
  334. _check(lmdb.mdb_cursor_get(
  335. icur, &ck_v, &spok_v, lmdb.MDB_GET_BOTH))
  336. except KeyNotFoundError:
  337. pass
  338. else:
  339. _check(lmdb.mdb_cursor_del(icur, 0))
  340. # Delete lookup indices, only if no other context
  341. # association is present.
  342. spok_v.mv_data = spok
  343. try:
  344. _check(lmdb.mdb_cursor_get(
  345. dcur, &spok_v, NULL, lmdb.MDB_SET))
  346. except KeyNotFoundError:
  347. self._index_triple(IDX_OP_REMOVE, spok)
  348. i += 1
  349. # If no context is specified, remove all associations.
  350. else:
  351. #logger.debug('Removing triples in all contexts.')
  352. # Loop over all SPO matching the triple pattern.
  353. while i < match_set.ct:
  354. spok = match_set.data + match_set.itemsize * i
  355. spok_v.mv_data = spok
  356. # Loop over all context associations for this SPO.
  357. try:
  358. _check(lmdb.mdb_cursor_get(
  359. dcur, &spok_v, &ck_v, lmdb.MDB_SET_KEY))
  360. except KeyNotFoundError:
  361. # Move on to the next SPO.
  362. continue
  363. else:
  364. ck = <Key>ck_v.mv_data
  365. logger.debug(f'Removing {spok[: TRP_KLEN]} from main.')
  366. while True:
  367. # Delete c:spo association.
  368. try:
  369. _check(lmdb.mdb_cursor_get(
  370. icur, &ck_v, &spok_v, lmdb.MDB_GET_BOTH))
  371. except KeyNotFoundError:
  372. pass
  373. else:
  374. lmdb.mdb_cursor_del(icur, 0)
  375. # Restore the pointer to the deleted SPO.
  376. spok_v.mv_data = spok
  377. # Move on to next associated context.
  378. try:
  379. _check(lmdb.mdb_cursor_get(
  380. dcur, &spok_v, &ck_v, lmdb.MDB_NEXT_DUP))
  381. except KeyNotFoundError:
  382. break
  383. # Then delete the spo:c association.
  384. try:
  385. _check(lmdb.mdb_cursor_get(
  386. dcur, &spok_v, &ck_v, lmdb.MDB_SET))
  387. except KeyNotFoundError:
  388. pass
  389. else:
  390. lmdb.mdb_cursor_del(dcur, lmdb.MDB_NODUPDATA)
  391. self._index_triple(IDX_OP_REMOVE, spok)
  392. #ck_v.mv_data = ck # Unnecessary?
  393. finally:
  394. i += 1
  395. finally:
  396. #pass
  397. #logger.debug('Closing spo:c in _remove.')
  398. self._cur_close(dcur)
  399. #logger.debug('Closing c:spo in _remove.')
  400. self._cur_close(icur)
  401. cdef void _index_triple(self, str op, TripleKey spok) except *:
  402. """
  403. Update index for a triple and context (add or remove).
  404. :param str op: 'add' or 'remove'.
  405. :param TripleKey spok: Triple key.
  406. """
  407. cdef:
  408. unsigned char keys[3][KLEN]
  409. unsigned char dbl_keys[3][DBL_KLEN]
  410. size_t i = 0
  411. lmdb.MDB_val key_v, dbl_key_v
  412. keys[0] = spok # sk
  413. keys[1] = spok + KLEN # pk
  414. keys[2] = spok + DBL_KLEN # ok
  415. dbl_keys[0] = spok + KLEN # pok
  416. memcpy(&dbl_keys[1], spok, KLEN) # sok, 1st part
  417. memcpy(&dbl_keys[1][KLEN], spok + DBL_KLEN, KLEN) # sok, 2nd part
  418. dbl_keys[2] = spok # spk
  419. #logger.debug('''Indices:
  420. #spok: {}
  421. #sk: {}
  422. #pk: {}
  423. #ok: {}
  424. #pok: {}
  425. #sok: {}
  426. #spk: {}
  427. #'''.format(
  428. # spok[:TRP_KLEN],
  429. # keys[0][:KLEN], keys[1][:KLEN], keys[2][:KLEN],
  430. # dbl_keys[0][:DBL_KLEN], dbl_keys[1][:DBL_KLEN], dbl_keys[2][:DBL_KLEN]))
  431. key_v.mv_size = KLEN
  432. dbl_key_v.mv_size = DBL_KLEN
  433. #logger.debug('Start indexing: {}.'.format(spok[: TRP_KLEN]))
  434. if op == IDX_OP_REMOVE:
  435. logger.debug(f'Remove {spok[ : TRP_KLEN]} from indices.')
  436. else:
  437. logger.debug(f'Add {spok[ : TRP_KLEN]} to indices.')
  438. while i < 3:
  439. cur1 = self._cur_open(self.lookup_indices[i]) # s:po, p:so, o:sp
  440. cur2 = self._cur_open(self.lookup_indices[i + 3])# po:s, so:p, sp:o
  441. try:
  442. key_v.mv_data = keys[i]
  443. dbl_key_v.mv_data = dbl_keys[i]
  444. # Removal op indexing.
  445. if op == IDX_OP_REMOVE:
  446. try:
  447. _check(lmdb.mdb_cursor_get(
  448. cur1, &key_v, &dbl_key_v, lmdb.MDB_GET_BOTH))
  449. logger.debug(f'Removed: {keys[i][: KLEN]}, '
  450. f'{dbl_keys[i][: DBL_KLEN]}')
  451. except KeyNotFoundError:
  452. logger.debug(f'Not found in index: {keys[i][: KLEN]}, '
  453. f'{dbl_keys[i][: DBL_KLEN]}')
  454. pass
  455. else:
  456. _check(lmdb.mdb_cursor_del(cur1, 0))
  457. # Restore pointers after delete.
  458. key_v.mv_data = keys[i]
  459. dbl_key_v.mv_data = dbl_keys[i]
  460. try:
  461. _check(lmdb.mdb_cursor_get(
  462. cur2, &dbl_key_v, &key_v, lmdb.MDB_GET_BOTH))
  463. logger.debug(f'Removed: {dbl_keys[i][: DBL_KLEN]}, '
  464. f'{keys[i][: KLEN]}')
  465. except KeyNotFoundError:
  466. logger.debug(f'Not found in index: '
  467. f'{dbl_keys[i][: DBL_KLEN]}, '
  468. f'{keys[i][: KLEN]}')
  469. pass
  470. else:
  471. _check(lmdb.mdb_cursor_del(cur2, 0))
  472. # Addition op indexing.
  473. elif op == IDX_OP_ADD:
  474. logger.debug('Adding to index `{}`: {}, {}'.format(
  475. self.lookup_indices[i],
  476. (<unsigned char *>key_v.mv_data)[ : key_v.mv_size],
  477. (<unsigned char *>dbl_key_v.mv_data)[ : dbl_key_v.mv_size]))
  478. try:
  479. _check(lmdb.mdb_cursor_put(
  480. cur1, &key_v, &dbl_key_v, lmdb.MDB_NODUPDATA))
  481. except KeyExistsError:
  482. logger.debug(f'Key {keys[i][: KLEN]} exists already.')
  483. pass
  484. logger.debug('Adding to index `{}`: {}, {}'.format(
  485. self.lookup_indices[i + 3],
  486. (<unsigned char *>dbl_key_v.mv_data)[ : dbl_key_v.mv_size],
  487. (<unsigned char *>key_v.mv_data)[ : key_v.mv_size]))
  488. try:
  489. _check(lmdb.mdb_cursor_put(
  490. cur2, &dbl_key_v, &key_v, lmdb.MDB_NODUPDATA))
  491. except KeyExistsError:
  492. logger.debug(f'Double key {dbl_keys[i][: DBL_KLEN]} exists already.')
  493. pass
  494. else:
  495. raise ValueError(
  496. 'Index operation \'{}\' is not supported.'.format(op))
  497. i += 1
  498. finally:
  499. #pass
  500. self._cur_close(cur1)
  501. self._cur_close(cur2)
  502. cpdef void _remove_graph(self, object gr_uri) except *:
  503. """
  504. Delete a context.
  505. """
  506. cdef:
  507. Hash128 chash
  508. unsigned char ck[KLEN]
  509. unsigned char *pk_c
  510. size_t c_size
  511. lmdb.MDB_val ck_v, chash_v
  512. #logger.debug('Deleting context: {}'.format(gr_uri))
  513. #logger.debug('Pickled context: {}'.format(serialize(gr_uri)))
  514. # Gather information on the graph prior to deletion.
  515. try:
  516. self._to_key(gr_uri, &ck)
  517. except KeyNotFoundError:
  518. return
  519. # Remove all triples and indices associated with the graph.
  520. self._remove((None, None, None), gr_uri)
  521. # Remove the graph if it is in triples.
  522. self._remove((gr_uri, None, None))
  523. self._remove((None, None, gr_uri))
  524. # Clean up all terms related to the graph.
  525. serialize(gr_uri, &pk_c, &c_size)
  526. chash = hash128(pk_c, c_size)
  527. free(pk_c)
  528. ck_v.mv_size = KLEN
  529. chash_v.mv_size = HLEN
  530. try:
  531. ck_v.mv_data = ck
  532. _check(lmdb.mdb_del(self.txn, self.get_dbi(b'c:'), &ck_v, NULL))
  533. ck_v.mv_data = ck
  534. _check(lmdb.mdb_del(self.txn, self.get_dbi(b't:st'), &ck_v, NULL))
  535. chash_v.mv_data = chash
  536. _check(lmdb.mdb_del(self.txn, self.get_dbi(b'th:t'), &chash_v, NULL))
  537. except KeyNotFoundError:
  538. pass
  539. # Lookup methods.
  540. # TODO Deprecate RDFLib API?
  541. def contexts(self, triple=None):
  542. """
  543. Get a list of all contexts.
  544. :rtype: Iterator(rdflib.Graph)
  545. """
  546. for ctx_uri in self.all_contexts(triple):
  547. yield Graph(identifier=self.from_key(ctx_uri), store=self)
  548. def triples(self, triple_pattern, context=None):
  549. """
  550. Generator over matching triples.
  551. :param tuple triple_pattern: 3 RDFLib terms
  552. :param context: Context graph, if available.
  553. :type context: rdflib.Graph or None
  554. :rtype: Iterator
  555. :return: Generator over triples and contexts in which each result has
  556. the following format::
  557. (s, p, o), generator(contexts)
  558. Where the contexts generator lists all context that the triple appears
  559. in.
  560. """
  561. cdef:
  562. size_t i = 0, j = 0
  563. unsigned char spok[TRP_KLEN]
  564. unsigned char ck[KLEN]
  565. lmdb.MDB_val key_v, data_v
  566. # This sounds strange, RDFLib should be passing None at this point,
  567. # but anyway...
  568. context = self._normalize_context(context)
  569. logger.debug(
  570. 'Getting triples for: {}, {}'.format(triple_pattern, context))
  571. rset = self.triple_keys(triple_pattern, context)
  572. #logger.debug('Triple keys found: {}'.format(rset.data[:rset.size]))
  573. cur = self._cur_open('spo:c')
  574. try:
  575. key_v.mv_size = TRP_KLEN
  576. for i in range(rset.ct):
  577. #logger.debug('Checking contexts for triples: {}'.format(
  578. # (rset.data + i * TRP_KLEN)[:TRP_KLEN]))
  579. key_v.mv_data = rset.data + i * TRP_KLEN
  580. # Get contexts associated with each triple.
  581. contexts = []
  582. # This shall never be MDB_NOTFOUND.
  583. _check(lmdb.mdb_cursor_get(cur, &key_v, &data_v, lmdb.MDB_SET))
  584. while True:
  585. c_uri = self.from_key(<Key>data_v.mv_data)
  586. contexts.append(Graph(identifier=c_uri, store=self))
  587. try:
  588. _check(lmdb.mdb_cursor_get(
  589. cur, &key_v, &data_v, lmdb.MDB_NEXT_DUP))
  590. except KeyNotFoundError:
  591. break
  592. #logger.debug('Triple keys before yield: {}: {}.'.format(
  593. # (<TripleKey>key_v.mv_data)[:TRP_KLEN], tuple(contexts)))
  594. yield self.from_trp_key(
  595. (<TripleKey>key_v.mv_data)[: TRP_KLEN]), tuple(contexts)
  596. #logger.debug('After yield.')
  597. finally:
  598. self._cur_close(cur)
  599. cdef Keyset triple_keys(self, tuple triple_pattern, context=None):
  600. """
  601. Top-level lookup method.
  602. This method is used by `triples` which returns native Python tuples,
  603. as well as by other methods that need to iterate and filter triple
  604. keys without incurring in the overhead of converting them to triples.
  605. :param tuple triple_pattern: 3 RDFLib terms
  606. :param context: Context graph or URI, or None.
  607. :type context: rdflib.term.Identifier or None
  608. """
  609. # TODO: Improve performance by allowing passing contexts as a tuple.
  610. cdef:
  611. unsigned char tk[KLEN]
  612. unsigned char ck[KLEN]
  613. unsigned char spok[TRP_KLEN]
  614. #unsigned char *pk_c
  615. size_t ct = 0, flt_j = 0, i = 0, j = 0, pg_offset = 0, c_size
  616. lmdb.MDB_cursor *icur
  617. lmdb.MDB_val key_v, data_v
  618. Keyset flt_res, ret
  619. if context is not None:
  620. #serialize(context, &pk_c, &c_size)
  621. try:
  622. self._to_key(context, &ck)
  623. except KeyNotFoundError:
  624. # Context not found.
  625. return Keyset(0, TRP_KLEN)
  626. icur = self._cur_open('c:spo')
  627. try:
  628. key_v.mv_data = ck
  629. key_v.mv_size = KLEN
  630. # s p o c
  631. if all(triple_pattern):
  632. #logger.debug('Lookup: s p o c')
  633. for i, term in enumerate(triple_pattern):
  634. try:
  635. self._to_key(term, &tk)
  636. except KeyNotFoundError:
  637. # Context not found.
  638. return Keyset(0, TRP_KLEN)
  639. memcpy(spok + (KLEN * i), tk, KLEN)
  640. if tk is NULL:
  641. # A term in the triple is not found.
  642. return Keyset(0, TRP_KLEN)
  643. data_v.mv_data = spok
  644. data_v.mv_size = TRP_KLEN
  645. #logger.debug(
  646. # 'Found spok {}. Matching with context {}'.format(
  647. # (<TripleKey>data_v.mv_data)[: TRP_KLEN],
  648. # (<Key>key_v.mv_data)[: KLEN]))
  649. try:
  650. _check(lmdb.mdb_cursor_get(
  651. icur, &key_v, &data_v, lmdb.MDB_GET_BOTH))
  652. except KeyNotFoundError:
  653. # Triple not found.
  654. #logger.debug('spok / ck pair not found.')
  655. return Keyset(0, TRP_KLEN)
  656. ret = Keyset(1, TRP_KLEN)
  657. memcpy(ret.data, spok, TRP_KLEN)
  658. return ret
  659. # ? ? ? c
  660. elif not any(triple_pattern):
  661. # Get all triples from the context
  662. #logger.debug('Lookup: ? ? ? c')
  663. try:
  664. _check(lmdb.mdb_cursor_get(
  665. icur, &key_v, &data_v, lmdb.MDB_SET))
  666. except KeyNotFoundError:
  667. # Triple not found.
  668. return Keyset(0, TRP_KLEN)
  669. _check(lmdb.mdb_cursor_count(icur, &ct))
  670. ret = Keyset(ct, TRP_KLEN)
  671. logger.debug(f'Entries in c:spo: {ct}')
  672. logger.debug(f'Allocated {ret.size} bytes.')
  673. logger.debug('Looking in key: {}'.format(
  674. (<unsigned char *>key_v.mv_data)[:key_v.mv_size]))
  675. _check(lmdb.mdb_cursor_get(
  676. icur, &key_v, &data_v, lmdb.MDB_GET_MULTIPLE))
  677. while True:
  678. #logger.debug(f'Data offset: {pg_offset} Page size: {data_v.mv_size} bytes')
  679. #logger.debug('Data page: {}'.format(
  680. # (<unsigned char *>data_v.mv_data)[: data_v.mv_size]))
  681. memcpy(ret.data + pg_offset, data_v.mv_data, data_v.mv_size)
  682. pg_offset += data_v.mv_size
  683. try:
  684. _check(lmdb.mdb_cursor_get(
  685. icur, &key_v, &data_v, lmdb.MDB_NEXT_MULTIPLE))
  686. except KeyNotFoundError:
  687. return ret
  688. # Regular lookup. Filter _lookup() results by context.
  689. else:
  690. try:
  691. res = self._lookup(triple_pattern)
  692. except KeyNotFoundError:
  693. return Keyset(0, TRP_KLEN)
  694. #logger.debug('Allocating for context filtering.')
  695. key_v.mv_data = ck
  696. key_v.mv_size = KLEN
  697. data_v.mv_size = TRP_KLEN
  698. flt_res = Keyset(res.ct, res.itemsize)
  699. while j < res.ct:
  700. #logger.debug('Checking row #{}'.format(flt_j))
  701. data_v.mv_data = res.data + j * res.itemsize
  702. #logger.debug('Checking c:spo {}, {}'.format(
  703. # (<unsigned char *>key_v.mv_data)[: key_v.mv_size],
  704. # (<unsigned char *>data_v.mv_data)[: data_v.mv_size]))
  705. try:
  706. # Verify that the triple is associated with the
  707. # context being searched.
  708. _check(lmdb.mdb_cursor_get(
  709. icur, &key_v, &data_v, lmdb.MDB_GET_BOTH))
  710. except KeyNotFoundError:
  711. #logger.debug('Discarding source[{}].'.format(j))
  712. continue
  713. else:
  714. #logger.debug('Copying source[{}] to dest[{}].'.format(
  715. # j, flt_j))
  716. memcpy(
  717. flt_res.data + res.itemsize * flt_j,
  718. res.data + res.itemsize * j, res.itemsize)
  719. flt_j += 1
  720. finally:
  721. j += 1
  722. # Resize result set to the size of context matches.
  723. # This crops the memory block without copying it.
  724. flt_res.resize(flt_j)
  725. return flt_res
  726. finally:
  727. self._cur_close(icur)
  728. # Unfiltered lookup. No context checked.
  729. else:
  730. #logger.debug('No context in query.')
  731. try:
  732. res = self._lookup(triple_pattern)
  733. except KeyNotFoundError:
  734. return Keyset(0, TRP_KLEN)
  735. #logger.debug('Res data before triple_keys return: {}'.format(
  736. # res.data[: res.size]))
  737. return res
  738. cdef Keyset _lookup(self, tuple triple_pattern):
  739. """
  740. Look up triples in the indices based on a triple pattern.
  741. :rtype: Iterator
  742. :return: Matching triple keys.
  743. """
  744. cdef:
  745. TripleKey spok
  746. lmdb.MDB_stat db_stat
  747. size_t ct = 0, i = 0
  748. lmdb.MDB_val spok_v, ck_v
  749. s, p, o = triple_pattern
  750. if s is not None:
  751. if p is not None:
  752. # s p o
  753. if o is not None:
  754. spok_v.mv_data = spok
  755. spok_v.mv_size = TRP_KLEN
  756. try:
  757. self._to_triple_key(triple_pattern, &spok)
  758. _check(lmdb.mdb_get(
  759. self.txn, self.get_dbi('spo:c'), &spok_v, &ck_v))
  760. except KeyNotFoundError:
  761. return Keyset(0, TRP_KLEN)
  762. matches = Keyset(1, TRP_KLEN)
  763. memcpy(matches.data, spok, TRP_KLEN)
  764. return matches
  765. # s p ?
  766. else:
  767. return self._lookup_2bound(0, s, 1, p)
  768. else:
  769. # s ? o
  770. if o is not None:
  771. return self._lookup_2bound(0, s, 2, o)
  772. # s ? ?
  773. else:
  774. return self._lookup_1bound(0, s)
  775. else:
  776. if p is not None:
  777. # ? p o
  778. if o is not None:
  779. return self._lookup_2bound(1, p, 2, o)
  780. # ? p ?
  781. else:
  782. return self._lookup_1bound(1, p)
  783. else:
  784. # ? ? o
  785. if o is not None:
  786. return self._lookup_1bound(2, o)
  787. # ? ? ?
  788. else:
  789. # Get all triples in the database.
  790. logger.debug('Getting all DB triples.')
  791. dcur = self._cur_open('spo:c')
  792. try:
  793. _check(lmdb.mdb_stat(
  794. self.txn, lmdb.mdb_cursor_dbi(dcur), &db_stat),
  795. 'Error gathering DB stats.')
  796. ct = db_stat.ms_entries
  797. ret = Keyset(ct, TRP_KLEN)
  798. logger.debug(f'Triples found: {ct}')
  799. if ct == 0:
  800. return Keyset(0, TRP_KLEN)
  801. _check(lmdb.mdb_cursor_get(
  802. dcur, &key_v, &data_v, lmdb.MDB_FIRST))
  803. while True:
  804. logger.debug(f'i in 0bound: {i}')
  805. memcpy(
  806. ret.data + ret.itemsize * i,
  807. key_v.mv_data, TRP_KLEN)
  808. try:
  809. _check(lmdb.mdb_cursor_get(
  810. dcur, &key_v, &data_v, lmdb.MDB_NEXT_NODUP))
  811. except KeyNotFoundError:
  812. break
  813. i += 1
  814. # Size is guessed from all entries. Unique keys will be
  815. # much less than that.
  816. ret.resize(i + 1)
  817. #logger.debug('Assembled data: {}'.format(ret.data[:ret.size]))
  818. return ret
  819. finally:
  820. self._cur_close(dcur)
  821. cdef Keyset _lookup_1bound(self, unsigned char idx, term):
  822. """
  823. Lookup triples for a pattern with one bound term.
  824. :param str idx_name: The index to look up as one of the keys of
  825. ``_lookup_ordering``.
  826. :param rdflib.URIRef term: Bound term to search for.
  827. :rtype: Iterator(bytes)
  828. :return: SPO keys matching the pattern.
  829. """
  830. cdef:
  831. unsigned char luk[KLEN]
  832. unsigned int dbflags
  833. unsigned char asm_rng[3]
  834. size_t ct, ret_offset = 0, src_pos, ret_pos
  835. size_t j # Must be signed for older OpenMP versions
  836. lmdb.MDB_cursor *icur
  837. logger.debug(f'lookup 1bound: {idx}, {term}')
  838. try:
  839. self._to_key(term, &luk)
  840. except KeyNotFoundError:
  841. return Keyset(0, TRP_KLEN)
  842. logging.debug('luk: {}'.format(luk))
  843. term_order = lookup_ordering[idx]
  844. icur = self._cur_open(self.lookup_indices[idx])
  845. logging.debug(f'DB label: {self.lookup_indices[idx]}')
  846. logging.debug('term order: {}'.format(term_order[: 3]))
  847. try:
  848. key_v.mv_data = luk
  849. key_v.mv_size = KLEN
  850. _check(lmdb.mdb_cursor_get(icur, &key_v, &data_v, lmdb.MDB_SET))
  851. _check(lmdb.mdb_cursor_count(icur, &ct))
  852. # Allocate memory for results.
  853. ret = Keyset(ct, TRP_KLEN)
  854. logger.debug(f'Entries for {self.lookup_indices[idx]}: {ct}')
  855. logger.debug(f'Allocated {ret.size} bytes of data.')
  856. #logger.debug('First row: {}'.format(
  857. # (<unsigned char *>data_v.mv_data)[:DBL_KLEN]))
  858. # Arrange results according to lookup order.
  859. asm_rng = [
  860. KLEN * term_order[0],
  861. KLEN * term_order[1],
  862. KLEN * term_order[2],
  863. ]
  864. logger.debug('asm_rng: {}'.format(asm_rng[:3]))
  865. logger.debug('luk: {}'.format(luk))
  866. _check(lmdb.mdb_cursor_get(icur, &key_v, &data_v, lmdb.MDB_SET))
  867. _check(lmdb.mdb_cursor_get(
  868. icur, &key_v, &data_v, lmdb.MDB_GET_MULTIPLE))
  869. while True:
  870. logger.debug('ret_offset: {}'.format(ret_offset))
  871. logger.debug(f'Page size: {data_v.mv_size}')
  872. #logger.debug(
  873. # 'Got data in 1bound ({}): {}'.format(
  874. # data_v.mv_size,
  875. # (<unsigned char *>data_v.mv_data)[: data_v.mv_size]))
  876. for j in prange(data_v.mv_size // DBL_KLEN, nogil=True):
  877. src_pos = DBL_KLEN * j
  878. ret_pos = (ret_offset + ret.itemsize * j)
  879. memcpy(ret.data + ret_pos + asm_rng[0], luk, KLEN)
  880. memcpy(ret.data + ret_pos + asm_rng[1],
  881. data_v.mv_data + src_pos, KLEN)
  882. memcpy(ret.data + ret_pos + asm_rng[2],
  883. data_v.mv_data + src_pos + KLEN, KLEN)
  884. # Increment MUST be done before MDB_NEXT_MULTIPLE otherwise
  885. # data_v.mv_size will be overwritten with the *next* page size
  886. # and cause corruption in the output data.
  887. ret_offset += data_v.mv_size // DBL_KLEN * ret.itemsize
  888. try:
  889. # Get results by the page.
  890. _check(lmdb.mdb_cursor_get(
  891. icur, &key_v, &data_v, lmdb.MDB_NEXT_MULTIPLE))
  892. except KeyNotFoundError:
  893. # For testing only. Errors will be caught in triples()
  894. # when looking for a context.
  895. #if ret_offset + ret.itemsize < ret.size:
  896. # raise RuntimeError(
  897. # 'Retrieved less values than expected: {} of {}.'
  898. # .format(src_offset, ret.size))
  899. return ret
  900. #logger.debug('Assembled data in 1bound ({}): {}'.format(ret.size, ret.data[: ret.size]))
  901. finally:
  902. self._cur_close(icur)
  903. cdef Keyset _lookup_2bound(
  904. self, unsigned char idx1, term1, unsigned char idx2, term2):
  905. """
  906. Look up triples for a pattern with two bound terms.
  907. :param str idx1: The index to look up as one of the keys of
  908. ``lookup_ordering_2bound``.
  909. :param rdflib.URIRef term1: First bound term to search for.
  910. :rtype: Iterator(bytes)
  911. :return: SPO keys matching the pattern.
  912. """
  913. cdef:
  914. unsigned char luk1_offset, luk2_offset
  915. unsigned char luk1[KLEN]
  916. unsigned char luk2[KLEN]
  917. unsigned char luk[DBL_KLEN]
  918. unsigned int dbflags
  919. unsigned char asm_rng[3]
  920. unsigned char term_order[3] # Lookup ordering
  921. size_t ct, i = 0, ret_offset = 0, ret_pos, src_pos
  922. size_t j # Must be signed for older OpenMP versions
  923. lmdb.MDB_cursor *icur
  924. Keyset ret
  925. logging.debug(
  926. f'2bound lookup for term {term1} at position {idx1} '
  927. f'and term {term2} at position {idx2}.')
  928. try:
  929. self._to_key(term1, &luk1)
  930. self._to_key(term2, &luk2)
  931. except KeyNotFoundError:
  932. return Keyset(0, TRP_KLEN)
  933. logging.debug('luk1: {}'.format(luk1[: KLEN]))
  934. logging.debug('luk2: {}'.format(luk2[: KLEN]))
  935. for i in range(3):
  936. if (
  937. idx1 in lookup_ordering_2bound[i][: 2]
  938. and idx2 in lookup_ordering_2bound[i][: 2]):
  939. term_order = lookup_ordering_2bound[i]
  940. if term_order[0] == idx1:
  941. luk1_offset = 0
  942. luk2_offset = KLEN
  943. else:
  944. luk1_offset = KLEN
  945. luk2_offset = 0
  946. dblabel = self.lookup_indices[i + 3] # skip 1bound index labels
  947. break
  948. if i == 2:
  949. raise ValueError(
  950. 'Indices {} and {} not found in LU keys.'.format(
  951. idx1, idx2))
  952. logger.debug('Term order: {}'.format(term_order[:3]))
  953. logger.debug('LUK offsets: {}, {}'.format(luk1_offset, luk2_offset))
  954. # Compose terms in lookup key.
  955. memcpy(luk + luk1_offset, luk1, KLEN)
  956. memcpy(luk + luk2_offset, luk2, KLEN)
  957. logger.debug('Lookup key: {}'.format(luk))
  958. icur = self._cur_open(dblabel)
  959. logger.debug('Database label: {}'.format(dblabel))
  960. try:
  961. key_v.mv_data = luk
  962. key_v.mv_size = DBL_KLEN
  963. # Count duplicates for key and allocate memory for result set.
  964. _check(lmdb.mdb_cursor_get(icur, &key_v, &data_v, lmdb.MDB_SET))
  965. _check(lmdb.mdb_cursor_count(icur, &ct))
  966. ret = Keyset(ct, TRP_KLEN)
  967. #logger.debug('Entries for {}: {}'.format(self.lookup_indices[idx], ct))
  968. #logger.debug('First row: {}'.format(
  969. # (<unsigned char *>data_v.mv_data)[:DBL_KLEN]))
  970. # Arrange results according to lookup order.
  971. asm_rng = [
  972. KLEN * term_order[0],
  973. KLEN * term_order[1],
  974. KLEN * term_order[2],
  975. ]
  976. logger.debug('asm_rng: {}'.format(asm_rng[:3]))
  977. logger.debug('luk: {}'.format(luk))
  978. _check(lmdb.mdb_cursor_get(icur, &key_v, &data_v, lmdb.MDB_SET))
  979. _check(lmdb.mdb_cursor_get(
  980. icur, &key_v, &data_v, lmdb.MDB_GET_MULTIPLE))
  981. while True:
  982. logger.debug('Got data in 2bound ({}): {}'.format(
  983. data_v.mv_size,
  984. (<unsigned char *>data_v.mv_data)[: data_v.mv_size]))
  985. for j in prange(data_v.mv_size // KLEN, nogil=True):
  986. src_pos = KLEN * j
  987. ret_pos = (ret_offset + ret.itemsize * j)
  988. #logger.debug('Page offset: {}'.format(pg_offset))
  989. #logger.debug('Ret offset: {}'.format(ret_offset))
  990. memcpy(ret.data + ret_pos + asm_rng[0], luk, KLEN)
  991. memcpy(ret.data + ret_pos + asm_rng[1], luk + KLEN, KLEN)
  992. memcpy(ret.data + ret_pos + asm_rng[2],
  993. data_v.mv_data + src_pos, KLEN)
  994. #logger.debug('Assembled triple: {}'.format((ret.data + ret_offset)[: TRP_KLEN]))
  995. ret_offset += data_v.mv_size // KLEN * ret.itemsize
  996. try:
  997. # Get results by the page.
  998. _check(lmdb.mdb_cursor_get(
  999. icur, &key_v, &data_v, lmdb.MDB_NEXT_MULTIPLE))
  1000. except KeyNotFoundError:
  1001. # For testing only. Errors will be caught in triples()
  1002. # when looking for a context.
  1003. #if ret_offset + ret.itemsize < ret.size:
  1004. # raise RuntimeError(
  1005. # 'Retrieved less values than expected: {} of {}.'
  1006. # .format(pg_offset, ret.size))
  1007. #logger.debug('Assembled data in 2bound ({}): {}'.format(ret.size, ret.data[: ret.size]))
  1008. return ret
  1009. finally:
  1010. self._cur_close(icur)
  1011. cdef Keyset _all_term_keys(self, term_type):
  1012. """
  1013. Return all keys of a (``s:po``, ``p:so``, ``o:sp``) index.
  1014. """
  1015. cdef:
  1016. size_t i = 0
  1017. lmdb.MDB_stat stat
  1018. idx_label = self.lookup_indices['spo'.index(term_type)]
  1019. #logger.debug('Looking for all terms in index: {}'.format(idx_label))
  1020. icur = self._cur_open(idx_label)
  1021. try:
  1022. _check(lmdb.mdb_stat(self.txn, lmdb.mdb_cursor_dbi(icur), &stat))
  1023. # TODO: This may allocate memory for several times the amount
  1024. # needed. Even though it is resized later, we need to know how
  1025. # performance is affected by this.
  1026. ret = Keyset(stat.ms_entries, KLEN)
  1027. try:
  1028. _check(lmdb.mdb_cursor_get(
  1029. icur, &key_v, NULL, lmdb.MDB_FIRST))
  1030. except KeyNotFoundError:
  1031. return Keyset(0, DBL_KLEN)
  1032. while True:
  1033. memcpy(ret.data + ret.itemsize * i, key_v.mv_data, KLEN)
  1034. rc = lmdb.mdb_cursor_get(
  1035. icur, &key_v, NULL, lmdb.MDB_NEXT_NODUP)
  1036. try:
  1037. _check(rc)
  1038. except KeyNotFoundError:
  1039. ret.resize(i + 1)
  1040. return ret
  1041. i += 1
  1042. finally:
  1043. #pass
  1044. self._cur_close(icur)
  1045. def all_terms(self, term_type):
  1046. """
  1047. Return all terms of a type (``s``, ``p``, or ``o``) in the store.
  1048. """
  1049. for key in self._all_term_keys(term_type).to_tuple():
  1050. #logger.debug('Yielding: {}'.format(key))
  1051. yield self.from_key(key)
  1052. cpdef tuple all_namespaces(self):
  1053. """
  1054. Return all registered namespaces.
  1055. """
  1056. cdef:
  1057. size_t i = 0
  1058. lmdb.MDB_stat stat
  1059. ret = []
  1060. dcur = self._cur_open('pfx:ns')
  1061. try:
  1062. try:
  1063. _check(lmdb.mdb_cursor_get(
  1064. dcur, &key_v, &data_v, lmdb.MDB_FIRST))
  1065. except KeyNotFoundError:
  1066. return tuple()
  1067. while True:
  1068. ret.append((
  1069. (<unsigned char *>key_v.mv_data)[: key_v.mv_size].decode(),
  1070. (<unsigned char *>data_v.mv_data)[: data_v.mv_size].decode()))
  1071. #logger.debug('Found namespace: {}:{}'.format(<unsigned char *>key_v.mv_data, <unsigned char *>data_v.mv_data))
  1072. try:
  1073. _check(lmdb.mdb_cursor_get(
  1074. dcur, &key_v, &data_v, lmdb.MDB_NEXT))
  1075. except KeyNotFoundError:
  1076. return tuple(ret)
  1077. i += 1
  1078. finally:
  1079. #pass
  1080. self._cur_close(dcur)
  1081. cpdef tuple all_contexts(self, triple=None):
  1082. """
  1083. Get a list of all contexts.
  1084. :rtype: Iterator(rdflib.Graph)
  1085. """
  1086. cdef:
  1087. lmdb.MDB_stat stat
  1088. size_t i = 0
  1089. unsigned char spok[TRP_KLEN]
  1090. unsigned char ck[KLEN]
  1091. lmdb.MDB_cursor_op op
  1092. cur = (
  1093. self._cur_open('spo:c') if triple and all(triple)
  1094. else self._cur_open('c:'))
  1095. try:
  1096. if triple and all(triple):
  1097. _check(lmdb.mdb_stat(
  1098. self.txn, lmdb.mdb_cursor_dbi(cur), &stat))
  1099. ret = Keyset(stat.ms_entries, KLEN)
  1100. self._to_triple_key(triple, &spok)
  1101. key_v.mv_data = spok
  1102. key_v.mv_size = TRP_KLEN
  1103. try:
  1104. _check(lmdb.mdb_cursor_get(
  1105. cur, &key_v, &data_v, lmdb.MDB_SET_KEY))
  1106. except KeyNotFoundError:
  1107. return tuple()
  1108. while True:
  1109. memcpy(ret.data + ret.itemsize * i, data_v.mv_data, KLEN)
  1110. try:
  1111. _check(lmdb.mdb_cursor_get(
  1112. cur, &key_v, &data_v, lmdb.MDB_NEXT_DUP))
  1113. except KeyNotFoundError:
  1114. break
  1115. i += 1
  1116. else:
  1117. _check(lmdb.mdb_stat(
  1118. self.txn, lmdb.mdb_cursor_dbi(cur), &stat))
  1119. ret = Keyset(stat.ms_entries, KLEN)
  1120. try:
  1121. _check(lmdb.mdb_cursor_get(
  1122. cur, &key_v, &data_v, lmdb.MDB_FIRST))
  1123. except KeyNotFoundError:
  1124. return tuple()
  1125. while True:
  1126. memcpy(
  1127. ret.data + ret.itemsize * i, key_v.mv_data, KLEN)
  1128. try:
  1129. _check(lmdb.mdb_cursor_get(
  1130. cur, &key_v, NULL, lmdb.MDB_NEXT))
  1131. except KeyNotFoundError:
  1132. break
  1133. i += 1
  1134. return ret.to_tuple()
  1135. finally:
  1136. #pass
  1137. self._cur_close(cur)
  1138. # Key conversion methods.
  1139. cdef object from_key(self, Key key):
  1140. """
  1141. Convert a single key into one term.
  1142. :param Key key: The key to be converted.
  1143. """
  1144. ser_term = self.lookup_term(key)
  1145. return deserialize(
  1146. <unsigned char *>ser_term.mv_data, ser_term.mv_size)
  1147. cdef inline lmdb.MDB_val lookup_term(self, Key key):
  1148. """
  1149. look up a term by key.
  1150. :param Key key: The key to be looked up.
  1151. :rtype: lmdb.MDB_val
  1152. :return: LMDB value structure containing the serialized term.
  1153. """
  1154. cdef:
  1155. lmdb.MDB_val key_v, data_v
  1156. key_v.mv_data = key
  1157. key_v.mv_size = KLEN
  1158. _check(
  1159. lmdb.mdb_get(self.txn, self.get_dbi('t:st'), &key_v, &data_v),
  1160. 'Error getting data for key \'{}\'.'.format(key))
  1161. return data_v
  1162. cdef tuple from_trp_key(self, TripleKey key):
  1163. """
  1164. Convert a triple key into a tuple of 3 terms.
  1165. :param TripleKey key: The triple key to be converted.
  1166. """
  1167. #logger.debug(f'From triple key: {key[: TRP_KLEN]}')
  1168. return (
  1169. self.from_key(key),
  1170. self.from_key(key + KLEN),
  1171. self.from_key(key + DBL_KLEN))
  1172. cdef inline void _to_key(self, term, Key *key) except *:
  1173. """
  1174. Convert a triple, quad or term into a key.
  1175. The key is the checksum of the serialized object, therefore unique for
  1176. that object.
  1177. :param rdflib.Term term: An RDFLib term (URIRef, BNode, Literal).
  1178. :param Key key: Pointer to the key that will be produced.
  1179. :rtype: void
  1180. """
  1181. cdef:
  1182. unsigned char *pk_t
  1183. size_t term_size
  1184. Hash128 thash
  1185. serialize(term, &pk_t, &term_size)
  1186. #logger.debug('Hashing pickle: {} with lentgh: {}'.format(pk_t, term_size))
  1187. thash = hash128(pk_t, term_size)
  1188. free(pk_t)
  1189. #logger.debug('Hash to search for: {}'.format(thash[: HLEN]))
  1190. key_v.mv_data = &thash
  1191. key_v.mv_size = HLEN
  1192. dbi = self.get_dbi('th:t')
  1193. logger.debug(f'DBI: {dbi}')
  1194. _check(lmdb.mdb_get(self.txn, dbi, &key_v, &data_v))
  1195. #logger.debug('Found key: {}'.format((<Key>data_v.mv_data)[: KLEN]))
  1196. key[0] = <Key>data_v.mv_data
  1197. cdef inline void _to_triple_key(self, tuple terms, TripleKey *tkey) except *:
  1198. """
  1199. Convert a tuple of 3 terms into a triple key.
  1200. """
  1201. cdef:
  1202. char i = 0
  1203. Key key
  1204. while i < 3:
  1205. self._to_key(terms[i], &key)
  1206. memcpy(tkey[0] + (KLEN * i), key, KLEN)
  1207. if key is NULL:
  1208. # A term in the triple is not found.
  1209. tkey = NULL
  1210. return
  1211. i += 1
  1212. cdef void _append(
  1213. self, unsigned char *value, size_t vlen, Key *nkey,
  1214. unsigned char *dblabel=b'', lmdb.MDB_txn *txn=NULL,
  1215. unsigned int flags=0) except *:
  1216. """
  1217. Append one or more keys and values to the end of a database.
  1218. :param lmdb.Cursor cur: The write cursor to act on.
  1219. :param list(bytes) values: Value(s) to append.
  1220. :rtype: list(memoryview)
  1221. :return: Last key(s) inserted.
  1222. """
  1223. cdef:
  1224. unsigned char key[KLEN]
  1225. lmdb.MDB_cursor *cur
  1226. if txn is NULL:
  1227. txn = self.txn
  1228. cur = self._cur_open(dblabel, txn=txn)
  1229. try:
  1230. _check(lmdb.mdb_cursor_get(cur, &key_v, NULL, lmdb.MDB_LAST))
  1231. except KeyNotFoundError:
  1232. memcpy(nkey[0], FIRST_KEY, KLEN)
  1233. else:
  1234. memcpy(key, key_v.mv_data, KLEN)
  1235. self._next_key(key, nkey)
  1236. finally:
  1237. #pass
  1238. self._cur_close(cur)
  1239. key_v.mv_data = nkey
  1240. key_v.mv_size = KLEN
  1241. data_v.mv_data = value
  1242. data_v.mv_size = vlen
  1243. #logger.debug('Appending value {} to db {} with key: {}'.format(
  1244. # value[: vlen], dblabel.decode(), nkey[0][:KLEN]))
  1245. #logger.debug('data size: {}'.format(data_v.mv_size))
  1246. lmdb.mdb_put(
  1247. txn, self.get_dbi(dblabel), &key_v, &data_v,
  1248. flags | lmdb.MDB_APPEND)
  1249. cdef void _next_key(self, const Key key, Key *nkey) except *:
  1250. """
  1251. Calculate the next closest byte sequence in lexicographical order.
  1252. This is used to fill the next available slot after the last one in
  1253. LMDB. Keys are byte strings, which is a convenient way to keep key
  1254. lengths as small as possible since they are referenced in several
  1255. indices.
  1256. This function assumes that all the keys are padded with the `start`
  1257. value up to the `max_len` length.
  1258. :param bytes n: Current byte sequence to add to.
  1259. """
  1260. cdef:
  1261. size_t i = KLEN
  1262. memcpy(nkey[0], key, KLEN)
  1263. #logger.debug('Last key in _next_key: {}'.format(key[0]))
  1264. while i > 0:
  1265. i -= 1
  1266. if nkey[0][i] < 255:
  1267. nkey[0][i] += 1
  1268. break
  1269. # If the value exceeds 255, i.e. the current value is the last one
  1270. else:
  1271. # If we are already at the leftmost byte, and this is already
  1272. # at 255, the sequence is exhausted.
  1273. if i == 0:
  1274. raise RuntimeError(
  1275. 'BAD DAY: Sequence exhausted. No more '
  1276. 'combinations are possible.')
  1277. # Move one position up and try to increment that.
  1278. else:
  1279. nkey[0][i] = KEY_START
  1280. #logger.debug('New key: {}'.format(nkey[0][:KLEN]))