store_mdb.c 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679
  1. #include "store_mdb.h"
  2. /**
  3. * Number of DBs defined. See MAIN_TABLE and LOOKUP_TABLE defines below.
  4. */
  5. #define N_DB 13
  6. /**
  7. * Memory map size.
  8. */
  9. #if (defined DEBUG || defined TESTING)
  10. #define DEFAULT_MAPSIZE 1<<24 // 16Mb (limit for Valgrind)
  11. #elif !(defined __LP64__ || defined __LLP64__) || \
  12. defined _WIN32 && !defined _WIN64
  13. #define DEFAULT_MAPSIZE 1<<31 // 2Gb (limit for 32-bit systems)
  14. #else
  15. #define DEFAULT_MAPSIZE 1UL<<40 // 1Tb
  16. #endif
  17. #define ENV_DIR_MODE 0750
  18. #define ENV_FILE_MODE 0640
  19. /*
  20. * Data types.
  21. */
  22. typedef char DbLabel[8];
  23. typedef struct mdbstore_iter_t MDBIterator;
  24. /// Store state flags.
  25. typedef enum {
  26. LSSTORE_OPEN = 1<<0, ///< Env is open.
  27. } StoreFlags;
  28. /// Iterator state flags.
  29. typedef enum {
  30. ITER_OPEN_TXN = 1<<0, /**< A transaction is open.
  31. *
  32. * The iterator has begun a new
  33. * transaction on initialization
  34. * which needs to be closed. If
  35. * false, the iterator is using an
  36. * existing transaction which will
  37. * not be closed with
  38. * #mdbiter_free().
  39. */
  40. } IterFlags;
  41. typedef enum {
  42. OP_ADD,
  43. OP_REMOVE,
  44. } StoreOp;
  45. typedef struct mdbstore_t {
  46. MDB_env * env; ///< Environment handle.
  47. MDB_dbi dbi[N_DB]; ///< DB handles. Refer to DbIdx enum.
  48. StoreFlags flags; ///< Store state flags.
  49. } MDBStore;
  50. /** @brief Iterator operation.
  51. *
  52. * Function executed for each iteration of a #MDBIterator. It assumes that a
  53. * result triple has already been found and is ready to be composed and
  54. * yielded.
  55. *
  56. * Upon call, the rc value of the iterator structure is set to the MDB_* rc
  57. * value for the next result. It is up to the caller to evaluate this value
  58. * and decide whether to call the function again.
  59. */
  60. typedef void (*iter_op_fn_t)(MDBIterator *it);
  61. /// Triple iterator.
  62. typedef struct mdbstore_iter_t {
  63. MDBStore * store; ///< MDB store handle.
  64. IterFlags flags; ///< Iterator flags.
  65. MDB_txn * txn; ///< MDB transaction.
  66. MDB_cursor * cur; ///< MDB cursor.
  67. MDB_cursor * ctx_cur; ///< MDB c:spo index cursor.
  68. MDB_val key; ///< Internal data handler.
  69. MDB_val data; ///< Internal data handler.
  70. LSUP_TripleKey spok; ///< Triple to be populated with match.
  71. LSUP_Key * ck; /**< Context array.
  72. *
  73. * This shall be populated for each
  74. * matching triple if requested. */
  75. iter_op_fn_t iter_op_fn; ///< Function used to look up next match.
  76. const uint8_t * term_order; ///< Term order used in 1-2bound look-ups.
  77. LSUP_Key luk[3]; ///< 0÷3 lookup keys.
  78. LSUP_Key luc; ///< Ctx key to filter by. May be NULL_KEY.
  79. size_t i; ///< Internal counter for paged lookups.
  80. size_t ct; ///< Current count of records inserted or
  81. ///< results found.
  82. int rc; ///< MDB_* return code for the next result.
  83. } MDBIterator;
  84. /*
  85. * Static variables.
  86. */
  87. #define DUPSORT_MASK MDB_DUPSORT
  88. #define DUPFIXED_MASK MDB_DUPSORT | MDB_DUPFIXED
  89. /**
  90. * Main DBs. These are the master information containers.
  91. *
  92. * The number of entries must match the N_DB constant defined above.
  93. */
  94. #define MAIN_TABLE \
  95. /* #ID pfx #DB label #Flags */ \
  96. ENTRY( T_ST, "t:st", 0 ) /* Key to ser. term */ \
  97. ENTRY( SPO_C, "spo:c", DUPFIXED_MASK ) /* Triple to context */ \
  98. ENTRY( C_, "c:", 0 ) /* Track empty ctx */ \
  99. ENTRY( PFX_NS, "pfx:ns", 0 ) /* Prefix to NS */ \
  100. ENTRY( IDK_ID, "idk:id", 0 ) /* ID key to ID */ \
  101. /**
  102. * Lookup DBs. These are indices and may be destroyed and rebuilt.
  103. */
  104. #define LOOKUP_TABLE \
  105. /* #ID pfx #DB label #Flags */ \
  106. ENTRY( S_PO, "s:po", DUPFIXED_MASK ) /* 1-bound lookup */ \
  107. ENTRY( P_SO, "p:so", DUPFIXED_MASK ) /* 1-bound lookup */ \
  108. ENTRY( O_SP, "o:sp", DUPFIXED_MASK ) /* 1-bound lookup */ \
  109. ENTRY( PO_S, "po:s", DUPFIXED_MASK ) /* 2-bound lookup */ \
  110. ENTRY( SO_P, "so:p", DUPFIXED_MASK ) /* 2-bound lookup */ \
  111. ENTRY( SP_O, "sp:o", DUPFIXED_MASK ) /* 2-bound lookup */ \
  112. ENTRY( C_SPO, "c:spo", DUPFIXED_MASK ) /* Context lookup */ \
  113. ENTRY( NS_PFX, "ns:pfx", DUPSORT_MASK ) /* NS to prefix */ \
  114. /**
  115. * DB labels. They are prefixed with DB_
  116. */
  117. #define ENTRY(a, b, c) static const DbLabel DB_##a = b;
  118. MAIN_TABLE
  119. LOOKUP_TABLE
  120. #undef ENTRY
  121. /*
  122. * Numeric index of each DB. Prefixed with IDX_
  123. *
  124. * These index numbers are referred to in all the arrays defeined below. They
  125. * are independent from the LMDB dbi values which are considered opaque here.
  126. */
  127. typedef enum {
  128. #define ENTRY(a, b, c) IDX_##a,
  129. MAIN_TABLE
  130. LOOKUP_TABLE
  131. #undef ENTRY
  132. } DBIdx;
  133. /**
  134. * DB labels.
  135. */
  136. static const char *db_labels[N_DB] = {
  137. #define ENTRY(a, b, c) DB_##a,
  138. MAIN_TABLE
  139. LOOKUP_TABLE
  140. #undef ENTRY
  141. };
  142. /*
  143. * DB flags. These are aligned with the dbi_labels index.
  144. */
  145. static const unsigned int db_flags[N_DB] = {
  146. #define ENTRY(a, b, c) c,
  147. MAIN_TABLE
  148. LOOKUP_TABLE
  149. #undef ENTRY
  150. };
  151. /*
  152. * 1-bound and 2-bound lookup indices.
  153. *
  154. * N.B. Only the first 6 (1-bound and 2-bound term lookup) are used.
  155. * The others are added just because they belong logically to the lookup table.
  156. */
  157. static DBIdx lookup_indices[9] = {
  158. #define ENTRY(a, b, c) IDX_##a,
  159. LOOKUP_TABLE
  160. #undef ENTRY
  161. };
  162. static const uint8_t lookup_ordering_1bound[3][3] = {
  163. {0, 1, 2}, // s:po
  164. {1, 0, 2}, // p:so
  165. {2, 0, 1}, // o:sp
  166. };
  167. static const uint8_t lookup_ordering_2bound[3][3] = {
  168. {1, 2, 0}, // po:s
  169. {0, 2, 1}, // so:p
  170. {0, 1, 2}, // sp:o
  171. };
  172. /*
  173. * Static prototypes.
  174. */
  175. static int index_triple(
  176. MDBStore *store, StoreOp op, LSUP_TripleKey spok, LSUP_Key ck,
  177. MDB_txn *txn);
  178. static LSUP_rc mdbstore_add_term (void *h, const LSUP_Buffer *sterm, void *th);
  179. inline static LSUP_rc lookup_0bound (MDBIterator *it, size_t *ct);
  180. inline static LSUP_rc lookup_1bound (
  181. uint8_t idx0, MDBIterator *it, size_t *ct);
  182. inline static LSUP_rc lookup_2bound (
  183. uint8_t idx0, uint8_t idx1, MDBIterator *it, size_t *ct);
  184. inline static LSUP_rc lookup_3bound(MDBIterator *it, size_t *ct);
  185. /**
  186. * Store interface.
  187. */
  188. static LSUP_NSMap *
  189. mdbstore_nsm_get (void *h)
  190. {
  191. MDBStore *store = h;
  192. LSUP_NSMap *nsm = LSUP_nsmap_new();
  193. if (UNLIKELY (!nsm)) return NULL;
  194. MDB_txn *txn;
  195. mdb_txn_begin (store->env, NULL, MDB_RDONLY, &txn);
  196. MDB_cursor *cur;
  197. if (mdb_cursor_open (txn, store->dbi[IDX_PFX_NS], &cur) != MDB_SUCCESS) {
  198. mdb_txn_abort (txn);
  199. return NULL;
  200. }
  201. MDB_val ns_v, pfx_v;
  202. if (mdb_cursor_get (cur, &pfx_v, &ns_v, MDB_FIRST) != MDB_SUCCESS)
  203. goto finally;
  204. do {
  205. ns_pfx pfx;
  206. char *ns = malloc (ns_v.mv_size);
  207. strncpy (pfx, pfx_v.mv_data, pfx_v.mv_size);
  208. strncpy (ns, ns_v.mv_data, ns_v.mv_size);
  209. LSUP_nsmap_add (nsm, pfx, ns);
  210. free (ns);
  211. } while (mdb_cursor_get (
  212. cur, &pfx_v, &ns_v, MDB_NEXT_NODUP) == MDB_SUCCESS);
  213. finally:
  214. mdb_cursor_close (cur);
  215. mdb_txn_abort (txn);
  216. return nsm;
  217. }
  218. static LSUP_rc
  219. mdbstore_nsm_put (void *h, const LSUP_NSMap *nsm, void *th)
  220. {
  221. MDBStore *store = h;
  222. MDB_txn *txn;
  223. RCCK (mdb_txn_begin (store->env, (MDB_txn *) th, 0, &txn));
  224. LSUP_rc rc = LSUP_NOACTION;
  225. int db_rc;
  226. MDB_cursor *dcur = NULL, *icur = NULL;
  227. if (
  228. mdb_cursor_open (txn, store->dbi[IDX_PFX_NS], &dcur) != MDB_SUCCESS
  229. ||
  230. mdb_cursor_open (txn, store->dbi[IDX_NS_PFX], &icur) != MDB_SUCCESS
  231. ) {
  232. mdb_txn_abort (txn);
  233. return LSUP_DB_ERR;
  234. }
  235. MDB_val pfx_v, ns_v;
  236. const char ***nsm_data = LSUP_nsmap_dump (nsm);
  237. for (size_t i = 0; nsm_data[i] != NULL; i++) {
  238. // At least 1 action. If not OK, it will change during the iteration.
  239. if (i == 0) rc = LSUP_OK;
  240. // On previous error, just clean up the NSM data array.
  241. if (rc < 0) goto loop_end;
  242. pfx_v.mv_data = (void *) nsm_data[i][0];
  243. pfx_v.mv_size = strlen (nsm_data[i][0]) + 1;
  244. ns_v.mv_data = (void *) nsm_data[i][1];
  245. ns_v.mv_size = strlen (nsm_data[i][1]) + 1;
  246. // If either ns or pfx exist, skip.
  247. if (
  248. mdb_cursor_get (dcur, &pfx_v, &ns_v, MDB_SET) != MDB_NOTFOUND
  249. ||
  250. mdb_cursor_get (icur, &ns_v, &pfx_v, MDB_SET) != MDB_NOTFOUND
  251. ) {
  252. rc = LSUP_CONFLICT;
  253. goto loop_end;
  254. }
  255. db_rc = mdb_cursor_put (dcur, &pfx_v, &ns_v, 0);
  256. db_rc |= mdb_cursor_put (icur, &ns_v, &pfx_v, 0);
  257. if (db_rc != MDB_SUCCESS) {
  258. log_error ("DB error: %s", LSUP_strerror (db_rc));
  259. rc = LSUP_DB_ERR;
  260. }
  261. loop_end:
  262. free (nsm_data[i]);
  263. }
  264. free (nsm_data);
  265. if (UNLIKELY (rc != LSUP_OK)) mdb_txn_abort (txn);
  266. else if (UNLIKELY (mdb_txn_commit (txn) != MDB_SUCCESS)) {
  267. mdb_txn_abort (txn);
  268. rc = LSUP_TXN_ERR;
  269. }
  270. return rc;
  271. }
  272. static const char *
  273. mdbstore_path_from_id (const char *id)
  274. {
  275. // Set environment path.
  276. if (!id) id = getenv ("LSUP_MDB_STORE_URN");
  277. if (!id) {
  278. id = LSUP_MDB_STORE_URN;
  279. log_info (
  280. "`LSUP_MDB_STORE_URN' environment variable is not "
  281. "set. The default URN %s has been set as the store ID.", id
  282. );
  283. }
  284. if (strncmp ("file://", id, 7) != 0) {
  285. log_error ("MDB store ID must be in the `file://<abs_path>` format.");
  286. return NULL;
  287. }
  288. return id + 7;
  289. }
  290. /** @brief Create the MDB environment and databases on disk.
  291. *
  292. * This function takes care of creaating the environment path if not existing,
  293. * and checking that it's a writable directory. If the path is not specified
  294. * in the LSUP_MDB_STORE_URN environment variable, a default directory is used.
  295. */
  296. static LSUP_rc
  297. mdbstore_setup (const char *id, bool clear)
  298. {
  299. const char *path = mdbstore_path_from_id (id);
  300. if (!path) return LSUP_VALUE_ERR;
  301. // If the directory exists (unless clear == true), do nothing.
  302. if (clear) rm_r (path);
  303. LSUP_rc rc = mkdir_p (path, ENV_DIR_MODE);
  304. log_info ("Create dir rc: %d", rc);
  305. log_info ("LSUP Create dir rc: %d", rc);
  306. RCCK (rc);
  307. // Open a temporary environment and txn to create the DBs.
  308. MDB_env *env;
  309. RCCK (mdb_env_create (&env));
  310. RCCK (mdb_env_set_maxdbs (env, N_DB));
  311. RCCK (mdb_env_open (env, path, 0, ENV_FILE_MODE));
  312. log_debug ("Environment opened at %s.", path);
  313. MDB_txn *txn;
  314. RCCK (mdb_txn_begin (env, NULL, 0, &txn));
  315. for (int i = 0; i < N_DB; i++) {
  316. log_trace ("Creating DB %s", db_labels[i]);
  317. MDB_dbi dbi;
  318. RCCK (
  319. mdb_dbi_open (txn, db_labels[i], db_flags[i] | MDB_CREATE, &dbi)
  320. );
  321. }
  322. mdb_txn_commit (txn);
  323. mdb_env_close (env);
  324. return LSUP_OK;
  325. }
  326. /** @brief Open an MDB store.
  327. *
  328. * The store must have been set up with #mdbstore_setup.
  329. *
  330. * Some environment variables affect various store parameters:
  331. *
  332. * - LSUP_MDB_MAPSIZE Long int specifying the size of the memory map. Usually
  333. * it is not necessary to modify this, unless one is operating under memory
  334. * and disk constraints. The default map size is 1Tb.
  335. */
  336. static void *
  337. mdbstore_new (const char *id, size_t _unused)
  338. {
  339. (void) _unused;
  340. const char *path = mdbstore_path_from_id (id);
  341. if (!path) return NULL;
  342. MDBStore *store;
  343. CALLOC_GUARD (store, NULL);
  344. RCNL (mdb_env_create (&store->env));
  345. MDB_txn *txn = NULL;
  346. // Set map size.
  347. size_t mapsize;
  348. char *env_mapsize = getenv ("LSUP_MDB_MAPSIZE");
  349. if (env_mapsize == NULL) mapsize = DEFAULT_MAPSIZE;
  350. else sscanf (env_mapsize, "%lu", &mapsize);
  351. log_info (
  352. "Setting environment map size at %s to %lu Mb.",
  353. path, mapsize / 1024 / 1024);
  354. CHECK (mdb_env_set_mapsize (store->env, mapsize), fail);
  355. CHECK (mdb_env_set_maxdbs (store->env, N_DB), fail);
  356. CHECK (mdb_env_open (store->env, path, 0, ENV_FILE_MODE), fail);
  357. // Assign DB handles to store->dbi.
  358. CHECK (mdb_txn_begin (store->env, NULL, 0, &txn), fail);
  359. for (int i = 0; i < N_DB; i++)
  360. CHECK (mdb_dbi_open (
  361. txn, db_labels[i], db_flags[i], store->dbi + i), fail);
  362. // Bootstrap the permanent store with initial data.
  363. MDB_stat stat;
  364. CHECK (mdb_stat (txn, store->dbi[IDX_PFX_NS], &stat), fail);
  365. if (stat.ms_entries == 0) {
  366. log_debug ("Loading initial data into %s", path);
  367. // Load initial NS map.
  368. mdbstore_nsm_put (store, LSUP_default_nsm, txn);
  369. // Index default context.
  370. // Create a dummy iterator just to use the current txn.
  371. MDBIterator *it;
  372. CALLOC_GUARD (it, NULL);
  373. it->txn = txn;
  374. mdbstore_add_term (store, LSUP_default_ctx_buf, it);
  375. free (it);
  376. }
  377. store->flags |= LSSTORE_OPEN;
  378. mdb_txn_commit (txn);
  379. txn = NULL;
  380. return store;
  381. fail:
  382. if (txn) mdb_txn_abort (txn);
  383. mdb_env_close (store->env);
  384. return NULL;
  385. }
  386. static void
  387. mdbstore_free (void *h)
  388. {
  389. MDBStore *store = h;
  390. if (store->flags & LSSTORE_OPEN) {
  391. const char *path;
  392. mdb_env_get_path (store->env, &path);
  393. log_info ("Closing MDB env at %s.", path);
  394. mdb_env_close (store->env);
  395. }
  396. free (store);
  397. }
  398. #if 0
  399. static char *
  400. mdbstore_id (const void *h)
  401. {
  402. const MDBStore *store = h;
  403. const char *path;
  404. mdb_env_get_path (store->env, &path);
  405. return strcat ("file://", path);
  406. }
  407. #endif
  408. static LSUP_rc
  409. mdbstore_stat (const MDBStore *store, MDB_stat *stat)
  410. {
  411. if (!(store->flags & LSSTORE_OPEN)) return 0;
  412. MDB_txn *txn;
  413. mdb_txn_begin (store->env, NULL, MDB_RDONLY, &txn);
  414. if (mdb_stat (txn, store->dbi[IDX_SPO_C], stat) != MDB_SUCCESS)
  415. return LSUP_DB_ERR;
  416. mdb_txn_abort (txn);
  417. return LSUP_OK;
  418. }
  419. static size_t
  420. mdbstore_size (const void *h)
  421. {
  422. const MDBStore *store = h;
  423. // Size is calculated outside of any pending write txn.
  424. MDB_stat stat;
  425. if (mdbstore_stat (store, &stat) != LSUP_OK) return 0;
  426. return stat.ms_entries;
  427. }
  428. static LSUP_rc
  429. mdbstore_txn_begin (void *h, int flags, void **th)
  430. {
  431. MDBStore *store = h;
  432. RCCK (mdb_txn_begin (store->env, NULL, flags, (MDB_txn **) th));
  433. return LSUP_OK;
  434. }
  435. static LSUP_rc
  436. mdbstore_txn_commit (void *th)
  437. {
  438. RCCK (mdb_txn_commit ((MDB_txn *) th));
  439. return LSUP_OK;
  440. }
  441. static void
  442. mdbstore_txn_abort (void *th)
  443. { mdb_txn_abort ((MDB_txn *) th); }
  444. static void *
  445. mdbiter_txn (void *h)
  446. { return ((MDBIterator *) h)->txn; }
  447. /** @brief Begin an add loop.
  448. *
  449. * @sa #store_add_init_fn_t
  450. *
  451. * @param[in] th Previously opened MDB_txn handle, if the add loop shall be
  452. * run within an enclosing transaction. The transaction must be read-write.
  453. * The operation will always open a new transaction that is closed with
  454. * #mdbstore_add_done() or #mdbstore_add_abort(). If this parameter is not
  455. * NULL, the loop transaction will have the passed txn set as its parent.
  456. */
  457. static void *
  458. mdbstore_add_init (void *h, const LSUP_Buffer *sc, void *th)
  459. {
  460. MDBStore *store = h;
  461. /* An iterator is used here. Some members are a bit misused but it does
  462. * its job without having to define a very similar struct.
  463. */
  464. MDBIterator *it;
  465. MALLOC_GUARD (it, NULL);
  466. it->store = store;
  467. it->i = 0;
  468. mdb_txn_begin (store->env, (MDB_txn *) th, 0, &it->txn);
  469. if (sc) {
  470. // Store context if it's not the default one.
  471. it->luc = LSUP_buffer_hash (sc);
  472. // Insert t:st for context.
  473. //log_debug ("Adding context: %s", sc);
  474. it->key.mv_data = &it->luc;
  475. it->key.mv_size = KLEN;
  476. it->data.mv_data = sc->addr;
  477. it->data.mv_size = sc->size;
  478. int db_rc = mdb_put (
  479. it->txn, it->store->dbi[IDX_T_ST],
  480. &it->key, &it->data, MDB_NOOVERWRITE);
  481. if (db_rc != MDB_SUCCESS && db_rc != MDB_KEYEXIST) {
  482. log_error (LSUP_strerror (db_rc));
  483. mdb_txn_abort (it->txn);
  484. return NULL;
  485. }
  486. } else {
  487. log_debug ("No context passed to iterator, using default.");
  488. it->luc = LSUP_buffer_hash (LSUP_default_ctx_buf);
  489. }
  490. return it;
  491. }
  492. /*
  493. * NOTE: at the moment #mdbstore_remove() or another
  494. * #mdbstore_init() cannot be called between #mdbstore_add_init and
  495. * #mdbstore_add_abort or #mdbstore_add_done. FIXME
  496. *
  497. */
  498. static LSUP_rc
  499. mdbstore_add_iter (void *h, const LSUP_BufferTriple *sspo)
  500. {
  501. if (UNLIKELY (!h)) return LSUP_VALUE_ERR;
  502. MDBIterator *it = h;
  503. int db_rc = LSUP_NOACTION;
  504. LSUP_TripleKey spok = NULL_TRP;
  505. // Add triple terms.
  506. for (int i = 0; i < 3; i++) {
  507. LSUP_Buffer *st = LSUP_btriple_pos (sspo, i);
  508. spok[i] = LSUP_buffer_hash (st);
  509. it->key.mv_data = spok + i;
  510. it->key.mv_size = KLEN;
  511. it->data.mv_data = st->addr;
  512. it->data.mv_size = st->size;
  513. db_rc = mdb_put(
  514. it->txn, it->store->dbi[IDX_T_ST],
  515. &it->key, &it->data, MDB_NOOVERWRITE);
  516. if (db_rc != MDB_SUCCESS && db_rc != MDB_KEYEXIST) {
  517. LOG_RC (db_rc);
  518. return LSUP_DB_ERR;
  519. }
  520. }
  521. log_trace ("Inserting spok: {%lx, %lx, %lx}", spok[0], spok[1], spok[2]);
  522. log_trace ("Into context: %lx", it->luc);
  523. // Insert spo:c.
  524. it->key.mv_data = spok;
  525. it->key.mv_size = TRP_KLEN;
  526. // In triple mode, data is empty (= NULL_KEY).
  527. it->data.mv_data = &it->luc;
  528. it->data.mv_size = it->luc == NULL_KEY ? 0 : KLEN;
  529. db_rc = mdb_put(
  530. it->txn, it->store->dbi[IDX_SPO_C],
  531. &it->key, &it->data, MDB_NODUPDATA);
  532. if (db_rc == MDB_KEYEXIST) return LSUP_NOACTION;
  533. if (db_rc != MDB_SUCCESS) {
  534. log_error (
  535. "MDB error while inserting triple: %s", LSUP_strerror(db_rc));
  536. return LSUP_DB_ERR;
  537. }
  538. // Index.
  539. LSUP_rc rc = index_triple (it->store, OP_ADD, spok, it->luc, it->txn);
  540. if (rc == LSUP_OK) it->i++;
  541. return rc;
  542. }
  543. static LSUP_rc
  544. mdbstore_add_done (void *h)
  545. {
  546. MDBIterator *it = h;
  547. LSUP_rc rc = LSUP_OK;
  548. if (mdb_txn_commit (it->txn) != MDB_SUCCESS) {
  549. mdb_txn_abort (it->txn);
  550. rc = LSUP_TXN_ERR;
  551. }
  552. free (it);
  553. return rc;
  554. }
  555. static void
  556. mdbstore_add_abort (void *h)
  557. {
  558. MDBIterator *it = h;
  559. mdb_txn_abort (it->txn);
  560. free (it);
  561. }
  562. #if 0
  563. /* TODO deprecate. Use low-level instead and abstract at graph level. */
  564. static LSUP_rc
  565. mdbstore_add (
  566. void *h, const LSUP_Buffer *sc,
  567. const LSUP_BufferTriple strp[], const size_t ct, size_t *inserted)
  568. {
  569. MDBStore *store = h;
  570. MDBIterator *it = mdbstore_add_init (store, sc);
  571. if (UNLIKELY (!it)) return LSUP_DB_ERR;
  572. for (size_t i = 0; i < ct; i++) {
  573. LSUP_rc rc = mdbstore_add_iter (it, strp + i);
  574. if (UNLIKELY (rc < 0)) {
  575. mdbstore_add_abort (it);
  576. return rc;
  577. }
  578. }
  579. *inserted = it->i;
  580. return mdbstore_add_done (it);
  581. }
  582. #endif
  583. static LSUP_rc
  584. key_to_sterm (MDBIterator *it, const LSUP_Key key, LSUP_Buffer *sterm)
  585. {
  586. LSUP_rc rc = LSUP_NORESULT;
  587. int db_rc;
  588. MDB_val key_v, data_v;
  589. key_v.mv_data = (void*)&key;
  590. key_v.mv_size = KLEN;
  591. db_rc = mdb_get (it->txn, it->store->dbi[IDX_T_ST], &key_v, &data_v);
  592. if (db_rc == MDB_SUCCESS) {
  593. sterm->addr = data_v.mv_data;
  594. sterm->size = data_v.mv_size;
  595. rc = LSUP_OK;
  596. } else if (db_rc == MDB_NOTFOUND) {
  597. sterm->addr = NULL;
  598. sterm->size = 0;
  599. } else rc = LSUP_DB_ERR;
  600. return rc;
  601. }
  602. static void *
  603. mdbstore_lookup (
  604. void *h, const LSUP_Buffer *ss, const LSUP_Buffer *sp,
  605. const LSUP_Buffer *so, const LSUP_Buffer *sc, void *th, size_t *ct)
  606. {
  607. LSUP_TripleKey spok = {
  608. LSUP_buffer_hash (ss),
  609. LSUP_buffer_hash (sp),
  610. LSUP_buffer_hash (so),
  611. };
  612. MDBIterator *it;
  613. CALLOC_GUARD (it, NULL);
  614. it->store = h;
  615. it->luc = LSUP_buffer_hash (sc);
  616. log_debug ("Lookup context: %lx", it->luc);
  617. if (ct) *ct = 0;
  618. uint8_t idx0, idx1;
  619. // Start RO transaction if not in a write txn already.
  620. if (th) it->txn = th;
  621. else {
  622. it->rc = mdb_txn_begin (it->store->env, NULL, MDB_RDONLY, &it->txn);
  623. if (it->rc != MDB_SUCCESS) {
  624. log_error ("Database error: %s", LSUP_strerror (it->rc));
  625. return NULL;
  626. }
  627. it->flags |= ITER_OPEN_TXN;
  628. }
  629. // Context index loop.
  630. if (UNLIKELY (mdb_cursor_open (
  631. it->txn, it->store->dbi[IDX_SPO_C], &it->ctx_cur) != MDB_SUCCESS))
  632. return NULL;
  633. /*
  634. * Lookup decision tree.
  635. */
  636. // s p o (all terms bound)
  637. if (spok[0] != NULL_KEY && spok[1] != NULL_KEY && spok[2] != NULL_KEY) {
  638. it->luk[0] = spok[0];
  639. it->luk[1] = spok[1];
  640. it->luk[2] = spok[2];
  641. PRCNL (lookup_3bound (it, ct));
  642. } else if (spok[0] != NULL_KEY) {
  643. it->luk[0] = spok[0];
  644. idx0 = 0;
  645. // s p ?
  646. if (spok[1] != NULL_KEY) {
  647. it->luk[1] = spok[1];
  648. idx1 = 1;
  649. PRCNL (lookup_2bound (idx0, idx1, it, ct));
  650. // s ? o
  651. } else if (spok[2] != NULL_KEY) {
  652. it->luk[1] = spok[2];
  653. idx1 = 2;
  654. PRCNL (lookup_2bound (idx0, idx1, it, ct));
  655. // s ? ?
  656. } else PRCNL (lookup_1bound (idx0, it, ct));
  657. } else if (spok[1] != NULL_KEY) {
  658. it->luk[0] = spok[1];
  659. idx0 = 1;
  660. // ? p o
  661. if (spok[2] != NULL_KEY) {
  662. it->luk[1] = spok[2];
  663. idx1 = 2;
  664. PRCNL (lookup_2bound (idx0, idx1, it, ct));
  665. // ? p ?
  666. } else PRCNL (lookup_1bound (idx0, it, ct));
  667. // ? ? o
  668. } else if (spok[2] != NULL_KEY) {
  669. it->luk[0] = spok[2];
  670. idx0 = 2;
  671. PRCNL (lookup_1bound (idx0, it, ct));
  672. // ? ? ? (all terms unbound)
  673. } else PRCNL (lookup_0bound (it, ct));
  674. return it;
  675. }
  676. /** @brief Get next iterator key.
  677. *
  678. * ckset is filled with an array of contexts that the triple appears
  679. * in, if not NULL.
  680. */
  681. static LSUP_rc
  682. mdbiter_next_key (MDBIterator *it)
  683. {
  684. if (UNLIKELY (!it)) return LSUP_VALUE_ERR;
  685. // Only advance if the previous it->rc wasn't already at the end.
  686. if (it->rc == MDB_NOTFOUND) return LSUP_END;
  687. if (UNLIKELY (it->rc != MDB_SUCCESS)) {
  688. log_error ("Database error: %s", LSUP_strerror (it->rc));
  689. return LSUP_DB_ERR;
  690. }
  691. LSUP_rc rc;
  692. /* Retrieve current value and advance cursor to the next result.
  693. * it->rc is set to the result of the next iteration.
  694. */
  695. it->iter_op_fn (it);
  696. log_trace (
  697. "Found spok: {%lx, %lx, %lx}",
  698. it->spok[0], it->spok[1], it->spok[2]);
  699. MDB_val key, data;
  700. int db_rc;
  701. key.mv_size = TRP_KLEN;
  702. data.mv_data = &it->luc;
  703. data.mv_size = KLEN;
  704. if (it->luc) {
  705. rc = LSUP_NORESULT; // Intermediary value, will never be returned.
  706. while (rc == LSUP_NORESULT) {
  707. //log_debug ("begin ctx loop.");
  708. // If ctx is specified, look if the matching triple is associated
  709. // with it. If not, move on to the next triple.
  710. // The loop normally exits when a triple with matching ctx is found
  711. // (LSUP_OK), if there are no more triples (LSUP_END), or if there
  712. // is an error (LSUP_DB_ERR).
  713. key.mv_data = it->spok;
  714. db_rc = mdb_cursor_get (it->ctx_cur, &key, &data, MDB_GET_BOTH);
  715. if (db_rc == MDB_SUCCESS) {
  716. rc = LSUP_OK;
  717. log_trace ("Triple found for context.");
  718. } else if (db_rc == MDB_NOTFOUND) {
  719. log_trace ("No triples found for context.");
  720. if (it->rc == MDB_NOTFOUND) rc = LSUP_END;
  721. else it->iter_op_fn (it);
  722. } else {
  723. log_error ("Database error: %s", LSUP_strerror (db_rc));
  724. rc = LSUP_DB_ERR;
  725. }
  726. }
  727. } else rc = LSUP_OK;
  728. // Get all contexts for a triple.
  729. key.mv_data = it->spok;
  730. db_rc = mdb_cursor_get (it->ctx_cur, &key, &data, MDB_SET_KEY);
  731. if (db_rc != MDB_SUCCESS) {
  732. log_error ("No context found for triple!");
  733. return LSUP_DB_ERR;
  734. }
  735. size_t ct;
  736. db_rc = mdb_cursor_count (it->ctx_cur, &ct);
  737. if (db_rc != MDB_SUCCESS) return LSUP_DB_ERR;
  738. // 1 spare for sentinel. Always allocated even on zero matches.
  739. LSUP_Key *tmp_ck = realloc (it->ck, sizeof (*it->ck) * (ct + 1));
  740. if (!tmp_ck) return LSUP_MEM_ERR;
  741. it->ck = tmp_ck;
  742. size_t i = 0;
  743. do {
  744. //log_trace("Copying to slot #%lu @%p", i, it->ck + i);
  745. memcpy (it->ck + i++, data.mv_data, sizeof (*it->ck));
  746. } while (
  747. mdb_cursor_get (it->ctx_cur, &key, &data, MDB_NEXT_DUP)
  748. == MDB_SUCCESS);
  749. //log_trace ("setting sentinel @%p", it->ck + i);
  750. it->ck[i] = NULL_KEY;
  751. return rc;
  752. }
  753. static LSUP_rc
  754. mdbiter_next (
  755. void *h, LSUP_BufferTriple *sspo, LSUP_Buffer **ctx_p)
  756. {
  757. MDBIterator *it = h;
  758. LSUP_rc rc = mdbiter_next_key (it);
  759. if (rc == LSUP_OK) {
  760. if (sspo) {
  761. key_to_sterm (it, it->spok[0], sspo->s);
  762. key_to_sterm (it, it->spok[1], sspo->p);
  763. key_to_sterm (it, it->spok[2], sspo->o);
  764. // TODO error handling.
  765. }
  766. // Contexts for current triple.
  767. if (ctx_p) {
  768. // Preallocate.
  769. size_t i = 0;
  770. while (it->ck[i++]); // Include sentinel in count.
  771. LSUP_Buffer *ctx;
  772. log_trace("Allocating %lu context buffers.", i);
  773. ctx = malloc(i * sizeof (*ctx));
  774. if (!ctx) return LSUP_MEM_ERR;
  775. for (i = 0; it->ck[i]; i++)
  776. key_to_sterm (it, it->ck[i], ctx + i);
  777. memset (ctx + i, 0, sizeof (*ctx)); // Sentinel
  778. // TODO error handling.
  779. *ctx_p = ctx;
  780. }
  781. }
  782. return rc;
  783. }
  784. static void
  785. mdbiter_free (void *h)
  786. {
  787. MDBIterator *it = h;
  788. if (!it) return;
  789. if (it->cur) mdb_cursor_close (it->cur);
  790. if (it->ctx_cur) mdb_cursor_close (it->ctx_cur);
  791. if (it->flags & ITER_OPEN_TXN) mdb_txn_abort (it->txn);
  792. free (it->ck);
  793. free (it);
  794. }
  795. static LSUP_rc
  796. mdbstore_remove (
  797. void *h, const LSUP_Buffer *ss, const LSUP_Buffer *sp,
  798. const LSUP_Buffer *so, const LSUP_Buffer *sc, void *th, size_t *ct)
  799. {
  800. MDBStore *store = h;
  801. LSUP_rc
  802. rc = LSUP_NOACTION,
  803. db_rc = 0;
  804. LSUP_Key ck = NULL_KEY;
  805. if (sc == NULL) sc = LSUP_default_ctx_buf;
  806. ck = LSUP_buffer_hash (sc);
  807. MDB_txn *txn;
  808. mdb_txn_begin (store->env, (MDB_txn *) th, 0, &txn);
  809. MDB_cursor *dcur, *icur;
  810. mdb_cursor_open (txn, store->dbi[IDX_SPO_C], &dcur);
  811. mdb_cursor_open (txn, store->dbi[IDX_C_SPO], &icur);
  812. MDB_val spok_v, ck_v;
  813. spok_v.mv_size = TRP_KLEN;
  814. ck_v.mv_size = KLEN;
  815. ck_v.mv_data = &ck;
  816. // The lookup operates within the current (bottom) write transaction.
  817. MDBIterator *it = mdbstore_lookup (store, ss, sp, so, sc, txn, ct);
  818. if (UNLIKELY (!it)) return LSUP_DB_ERR;
  819. if (ct) log_debug ("Found %lu triples to remove.", *ct);
  820. while (mdbiter_next_key (it) == LSUP_OK) {
  821. spok_v.mv_data = it->spok;
  822. db_rc = mdb_cursor_get (dcur, &spok_v, &ck_v, MDB_GET_BOTH);
  823. if (db_rc == MDB_NOTFOUND) continue;
  824. if (UNLIKELY (db_rc != MDB_SUCCESS)) goto fail;
  825. log_trace (
  826. "Removing {%lx, %lx, %lx}",
  827. it->spok[0], it->spok[1], it->spok[2]);
  828. // Delete spo:c entry.
  829. db_rc = mdb_cursor_del (dcur, 0);
  830. if (UNLIKELY (db_rc != MDB_SUCCESS)) goto fail;
  831. // Restore ck address after each delete.
  832. spok_v.mv_data = it->spok;
  833. ck_v.mv_data = &ck;
  834. // Delete c:spo entry.
  835. db_rc = mdb_cursor_get (icur, &ck_v, &spok_v, MDB_GET_BOTH);
  836. if (db_rc == MDB_NOTFOUND) continue;
  837. if (UNLIKELY (db_rc != MDB_SUCCESS)) goto fail;
  838. db_rc = mdb_cursor_del (icur, 0);
  839. if (UNLIKELY (db_rc != MDB_SUCCESS)) goto fail;
  840. spok_v.mv_data = it->spok;
  841. ck_v.mv_data = &ck;
  842. // If there are no more contexts associated with this triple,
  843. // remove from indices.
  844. db_rc = mdb_cursor_get (dcur, &spok_v, NULL, MDB_SET);
  845. if (db_rc == MDB_SUCCESS) continue;
  846. if (UNLIKELY (db_rc != MDB_NOTFOUND)) goto fail;
  847. rc = index_triple (store, OP_REMOVE, it->spok, ck, txn);
  848. }
  849. mdbiter_free (it);
  850. if (UNLIKELY (mdb_txn_commit (txn) != MDB_SUCCESS)) {
  851. rc = LSUP_TXN_ERR;
  852. goto fail;
  853. }
  854. return rc;
  855. fail:
  856. mdb_txn_abort (txn);
  857. log_error ("Database error: %s", LSUP_strerror (db_rc));
  858. return rc == LSUP_TXN_ERR ? rc : LSUP_DB_ERR;
  859. }
  860. #if 0
  861. static int
  862. mdbstore_tkey_exists (MDBStore *store, LSUP_Key tkey)
  863. {
  864. int db_rc, rc;
  865. MDB_val key, data;
  866. key.mv_data = &tkey;
  867. key.mv_size = KLEN;
  868. MDB_txn *txn = NULL;
  869. mdb_txn_begin (store->env, NULL, MDB_RDONLY, &txn);
  870. MDB_cursor *cur = NULL;
  871. mdb_cursor_open (txn, store->dbi[IDX_T_ST], &cur);
  872. db_rc = mdb_cursor_get (cur, &key, &data, MDB_SET);
  873. if (db_rc == MDB_SUCCESS) rc = 1;
  874. else if (db_rc == MDB_NOTFOUND) rc = 0;
  875. else {
  876. log_error ("DB error: %s", LSUP_strerror (db_rc));
  877. rc = LSUP_DB_ERR;
  878. }
  879. if (cur) mdb_cursor_close (cur);
  880. if (txn) mdb_txn_abort (txn);
  881. return rc;
  882. }
  883. #endif
  884. /** @brief Add a term to the store.
  885. *
  886. * @param[in] h #MDBStore handle.
  887. *
  888. * @param[in] sterm Serialized term to store.
  889. *
  890. * @param[in] ith #MDBIterator handle. Only the transaction handle inside this
  891. * is used. It may be NULL, in which case a new transaction is opened and
  892. * closed for the operation.
  893. *
  894. * @return LSUP_OK on success; <0 on error.
  895. */
  896. static LSUP_rc
  897. mdbstore_add_term (void *h, const LSUP_Buffer *sterm, void *ith)
  898. {
  899. //log_trace ("Adding term to MDB store: %s", sterm->addr);
  900. MDBStore *store = h;
  901. int db_rc;
  902. MDB_val key, data;
  903. MDBIterator *it = ith;
  904. MDB_txn *txn;
  905. // If a transaction is active in the iterator, use it, otherwise open and
  906. // close a new one.
  907. bool borrowed_txn = (it && it->txn);
  908. if (borrowed_txn) txn = it->txn;
  909. else RCCK (mdb_txn_begin (store->env, NULL, 0, &txn));
  910. MDB_cursor *cur;
  911. CHECK (mdb_cursor_open (txn, store->dbi[IDX_T_ST], &cur), fail);
  912. LSUP_Key k = LSUP_buffer_hash (sterm);
  913. key.mv_data = &k;
  914. key.mv_size = sizeof (k);
  915. data.mv_data = sterm->addr;
  916. data.mv_size = sterm->size;
  917. db_rc = mdb_cursor_put (cur, &key, &data, MDB_NOOVERWRITE);
  918. if (db_rc != MDB_KEYEXIST) CHECK (db_rc, fail);
  919. if (!borrowed_txn) CHECK (db_rc = mdb_txn_commit (txn), fail);
  920. return LSUP_OK;
  921. fail:
  922. if (!borrowed_txn) mdb_txn_abort (txn);
  923. log_trace ("Aborted txn for adding term.");
  924. return LSUP_DB_ERR;
  925. }
  926. const LSUP_StoreInt mdbstore_int = {
  927. .name = "MDB Store",
  928. .features = LSUP_STORE_PERM | LSUP_STORE_CTX | LSUP_STORE_IDX
  929. | LSUP_STORE_TXN | LSUP_STORE_COW,
  930. .setup_fn = mdbstore_setup,
  931. .new_fn = mdbstore_new,
  932. .free_fn = mdbstore_free,
  933. .size_fn = mdbstore_size,
  934. .txn_begin_fn = mdbstore_txn_begin,
  935. .txn_commit_fn = mdbstore_txn_commit,
  936. .txn_abort_fn = mdbstore_txn_abort,
  937. .iter_txn_fn = mdbiter_txn,
  938. .add_init_fn = mdbstore_add_init,
  939. .add_iter_fn = mdbstore_add_iter,
  940. .add_abort_fn = mdbstore_add_abort,
  941. .add_done_fn = mdbstore_add_done,
  942. .add_term_fn = mdbstore_add_term,
  943. .lookup_fn = mdbstore_lookup,
  944. .lu_next_fn = mdbiter_next,
  945. .lu_free_fn = mdbiter_free,
  946. .remove_fn = mdbstore_remove,
  947. .nsm_put_fn = mdbstore_nsm_put,
  948. .nsm_get_fn = mdbstore_nsm_get,
  949. };
  950. /* * * Static functions. * * */
  951. /** @brief Index an added or removed triple.
  952. *
  953. * @param store[in] MDB store to index.
  954. * @param op[in] Store operation. One of OP_ADD or OP_REMOVE.
  955. * @param spok[in] Triple key to index.
  956. * @param ck[in] Context to index, may be NULL.
  957. * @param[in] th Transaction handle. This MUST be a valid pointer to an open
  958. * RW transaction.
  959. */
  960. static LSUP_rc
  961. index_triple(
  962. MDBStore *store, StoreOp op, LSUP_TripleKey spok, LSUP_Key ck,
  963. MDB_txn *txn)
  964. {
  965. int db_rc;
  966. LSUP_rc rc = LSUP_NOACTION;
  967. MDB_val v1, v2;
  968. log_trace ("Indexing triple: {%lx %lx %lx}", spok[0], spok[1], spok[2]);
  969. // Index c:spo.
  970. if (op == OP_REMOVE) {
  971. log_trace ("Indexing op: REMOVE");
  972. if (ck != NULL_KEY) {
  973. MDB_cursor *cur;
  974. v1.mv_data = &ck;
  975. v1.mv_size = KLEN;
  976. v2.mv_data = spok;
  977. v2.mv_size = TRP_KLEN;
  978. mdb_cursor_open (txn, store->dbi[IDX_C_SPO], &cur);
  979. if (mdb_cursor_get (cur, &v1, &v2, MDB_GET_BOTH) == MDB_SUCCESS) {
  980. db_rc = mdb_cursor_del (cur, 0);
  981. if (db_rc != MDB_SUCCESS) return LSUP_DB_ERR;
  982. rc = LSUP_OK;
  983. }
  984. mdb_cursor_close (cur);
  985. }
  986. } else if (op == OP_ADD) {
  987. log_trace ("Indexing op: ADD");
  988. if (ck != NULL_KEY) {
  989. v1.mv_data = &ck;
  990. v1.mv_size = KLEN;
  991. v2.mv_data = spok;
  992. v2.mv_size = TRP_KLEN;
  993. db_rc = mdb_put(
  994. txn, store->dbi[IDX_C_SPO],
  995. &v1, &v2, MDB_NODUPDATA);
  996. if (db_rc != MDB_SUCCESS) return LSUP_DB_ERR;
  997. if (db_rc != MDB_KEYEXIST) rc = LSUP_OK;
  998. }
  999. } else return LSUP_VALUE_ERR;
  1000. LSUP_DoubleKey dbl_keys[3] = {
  1001. {spok[1], spok[2]}, // po
  1002. {spok[0], spok[2]}, // so
  1003. {spok[0], spok[1]}, // sp
  1004. };
  1005. // Add terms to index.
  1006. v1.mv_size = KLEN;
  1007. v2.mv_size = DBL_KLEN;
  1008. for (int i = 0; i < 3; i++) {
  1009. MDB_dbi db1 = store->dbi[lookup_indices[i]]; // s:po, p:so, o:sp
  1010. MDB_dbi db2 = store->dbi[lookup_indices[i + 3]]; // po:s, so:p, sp:o
  1011. v1.mv_data = spok + i;
  1012. v2.mv_data = dbl_keys[i];
  1013. if (op == OP_REMOVE) {
  1014. MDB_cursor *cur1, *cur2;
  1015. mdb_cursor_open(txn, store->dbi[lookup_indices[i]], &cur1);
  1016. db_rc = mdb_cursor_get (cur1, &v1, &v2, MDB_GET_BOTH);
  1017. if (db_rc == MDB_SUCCESS) mdb_cursor_del (cur1, 0);
  1018. mdb_cursor_close (cur1);
  1019. // Restore pointers invalidated after delete.
  1020. v1.mv_data = spok + i;
  1021. v2.mv_data = dbl_keys[i];
  1022. mdb_cursor_open(txn, store->dbi[lookup_indices[i + 3]], &cur2);
  1023. db_rc = mdb_cursor_get (cur2, &v2, &v1, MDB_GET_BOTH);
  1024. if (db_rc == MDB_SUCCESS) mdb_cursor_del (cur2, 0);
  1025. // TODO error handling.
  1026. rc = LSUP_OK;
  1027. mdb_cursor_close (cur2);
  1028. } else { // OP_ADD is guaranteed.
  1029. // 1-bound index.
  1030. log_trace ("Indexing in %s: ", db_labels[lookup_indices[i]]);
  1031. log_trace (
  1032. "%lx: %lx %lx", *(size_t*)(v1.mv_data),
  1033. *(size_t*)(v2.mv_data), *(size_t*)(v2.mv_data) + 1);
  1034. db_rc = mdb_put (txn, db1, &v1, &v2, MDB_NODUPDATA);
  1035. if (db_rc == MDB_SUCCESS) rc = LSUP_OK;
  1036. else if (db_rc != MDB_KEYEXIST) return LSUP_DB_ERR;
  1037. // 2-bound index.
  1038. log_trace ("Indexing in %s: ", db_labels[lookup_indices[i + 3]]);
  1039. log_trace (
  1040. "%lx %lx: %lx", *(size_t*)(v2.mv_data),
  1041. *(size_t*)(v2.mv_data) + 1, *(size_t*)(v1.mv_data));
  1042. db_rc = mdb_put (txn, db2, &v2, &v1, MDB_NODUPDATA);
  1043. if (db_rc == MDB_SUCCESS) rc = LSUP_OK;
  1044. else if (db_rc != MDB_KEYEXIST) return LSUP_DB_ERR;
  1045. }
  1046. }
  1047. return rc;
  1048. }
  1049. /* * * Term-specific iterators. * * */
  1050. /** @brief Advance 0-bound iterator.
  1051. *
  1052. * Cursor: spo:c
  1053. */
  1054. inline static void
  1055. it_next_0bound (MDBIterator *it)
  1056. {
  1057. memcpy (it->spok, it->key.mv_data, sizeof (LSUP_TripleKey));
  1058. it->rc = mdb_cursor_get (it->cur, &it->key, &it->data, MDB_NEXT);
  1059. }
  1060. /** @brief Advance 1-bound iterator.
  1061. *
  1062. * Uses paged data in a nested loop.
  1063. *
  1064. * Cursor: s:po, p:so, or o:sp.
  1065. */
  1066. inline static void
  1067. it_next_1bound (MDBIterator *it)
  1068. {
  1069. LSUP_DoubleKey *lu_dset = it->data.mv_data;
  1070. it->spok[it->term_order[0]] = it->luk[0];
  1071. it->spok[it->term_order[1]] = lu_dset[it->i][0];
  1072. it->spok[it->term_order[2]] = lu_dset[it->i][1];
  1073. log_trace (
  1074. "Composed triple: {%lx %lx %lx}",
  1075. it->spok[0], it->spok[1], it->spok[2]);
  1076. // Ensure next block within the same page is not beyond the last.
  1077. if (it->i < it->data.mv_size / DBL_KLEN - 1) {
  1078. it->i ++;
  1079. //log_debug ("Increasing page cursor to %lu.", it->i);
  1080. //log_debug ("it->rc: %d", it->rc);
  1081. } else {
  1082. // If the last block in the page is being yielded,
  1083. // move cursor to beginning of next page.
  1084. it->i = 0;
  1085. //log_debug ("Reset page cursor to %lu.", it->i);
  1086. it->rc = mdb_cursor_get (
  1087. it->cur, &it->key, &it->data, MDB_NEXT_MULTIPLE);
  1088. }
  1089. }
  1090. /** @brief Advance 2-bound iterator.
  1091. *
  1092. * Uses paged data in a nested loop.
  1093. *
  1094. * Cursor: po:s, so:p, or sp:o.
  1095. */
  1096. inline static void
  1097. it_next_2bound (MDBIterator *it)
  1098. {
  1099. LSUP_Key *lu_dset = it->data.mv_data;
  1100. it->spok[it->term_order[0]] = it->luk[0];
  1101. it->spok[it->term_order[1]] = it->luk[1];
  1102. it->spok[it->term_order[2]] = lu_dset[it->i];
  1103. // Ensure next block within the same page is not beyond the last.
  1104. if (it->i < it->data.mv_size / KLEN - 1)
  1105. it->i ++;
  1106. else {
  1107. // If the last block in the page is being yielded,
  1108. // move cursor to beginning of next page.
  1109. it->i = 0;
  1110. it->rc = mdb_cursor_get (it->cur, &it->key, &it->data, MDB_NEXT_MULTIPLE);
  1111. }
  1112. }
  1113. /** @brief Advance 3-bound iterator.
  1114. *
  1115. * This is a special case of 0÷1 results; either there was one matching triple,
  1116. * which was already set in the first result, or there was none, i.e. it->rc is
  1117. * already MDB_NOTFOUND and this function will not be called.
  1118. */
  1119. inline static void
  1120. it_next_3bound (MDBIterator *it)
  1121. {
  1122. it->rc = MDB_NOTFOUND;
  1123. }
  1124. /* * * Term-specific lookups. * * */
  1125. inline static LSUP_rc
  1126. lookup_0bound (MDBIterator *it, size_t *ct)
  1127. {
  1128. log_debug ("Looking up 0 bound terms.");
  1129. if (ct) {
  1130. if (it->luc != NULL_KEY) {
  1131. // Look up by given context.
  1132. it->rc = mdb_cursor_open (
  1133. it->txn, it->store->dbi[IDX_C_SPO], &it->cur);
  1134. it->key.mv_data = &it->luc;
  1135. it->key.mv_size = KLEN;
  1136. it->rc = mdb_cursor_get (it->cur, &it->key, &it->data, MDB_SET);
  1137. if (it->rc == MDB_SUCCESS) mdb_cursor_count (it->cur, ct);
  1138. mdb_cursor_close (it->cur);
  1139. it->cur = NULL;
  1140. } else {
  1141. // Look up all contexts.
  1142. MDB_stat stat;
  1143. mdb_stat (it->txn, it->store->dbi[IDX_S_PO], &stat);
  1144. *ct = stat.ms_entries;
  1145. }
  1146. log_debug ("Found %lu keys.", *ct);
  1147. }
  1148. it->rc = mdb_cursor_open (it->txn, it->store->dbi[IDX_SPO_C], &it->cur);
  1149. if (it->rc != MDB_SUCCESS) {
  1150. log_error ("Database error: %s", LSUP_strerror (it->rc));
  1151. return LSUP_DB_ERR;
  1152. }
  1153. it->rc = mdb_cursor_get (it->cur, &it->key, &it->data, MDB_FIRST);
  1154. /*
  1155. mdb_cursor_close (it->cur);
  1156. it->cur = NULL;
  1157. */
  1158. it->iter_op_fn = it_next_0bound;
  1159. if (it->rc != MDB_SUCCESS && it->rc != MDB_NOTFOUND) {
  1160. log_error ("Database error: %s", LSUP_strerror (it->rc));
  1161. return LSUP_DB_ERR;
  1162. }
  1163. return LSUP_OK;
  1164. }
  1165. inline static LSUP_rc
  1166. lookup_1bound (uint8_t idx0, MDBIterator *it, size_t *ct)
  1167. {
  1168. it->term_order = (const uint8_t*)lookup_ordering_1bound[idx0];
  1169. log_debug ("Looking up 1 bound term: %lx", it->luk[0]);
  1170. mdb_cursor_open (it->txn, it->store->dbi[lookup_indices[idx0]], &it->cur);
  1171. it->key.mv_data = it->luk;
  1172. it->key.mv_size = KLEN;
  1173. if (ct) {
  1174. // If a context is specified, the only way to count triples matching
  1175. // the context is to loop over them.
  1176. if (it->luc != NULL_KEY) {
  1177. log_debug ("Counting in context: %lx", it->luc);
  1178. MDBIterator *ct_it;
  1179. MALLOC_GUARD (ct_it, LSUP_MEM_ERR);
  1180. /*
  1181. memcpy (ct_it, it, sizeof (*ct_it));
  1182. */
  1183. ct_it->store = it->store;
  1184. ct_it->txn = it->txn;
  1185. ct_it->ctx_cur = it->ctx_cur;
  1186. ct_it->key = it->key;
  1187. ct_it->data = it->data;
  1188. ct_it->ck = NULL;
  1189. ct_it->luk[0] = it->luk[0];
  1190. ct_it->luc = it->luc;
  1191. ct_it->i = 0;
  1192. LSUP_rc rc = lookup_1bound (idx0, ct_it, NULL);
  1193. if (rc < 0) return rc;
  1194. LSUP_rc db_rc;
  1195. while (LSUP_END != (db_rc = mdbiter_next_key (ct_it))) {
  1196. if (UNLIKELY (db_rc < 0)) return db_rc;
  1197. (*ct)++;
  1198. }
  1199. // Free the counter iterator without freeing the shared txn.
  1200. if (ct_it->cur) mdb_cursor_close (ct_it->cur);
  1201. free (ct_it->ck);
  1202. free (ct_it);
  1203. } else {
  1204. it->rc = mdb_cursor_get (it->cur, &it->key, &it->data, MDB_SET);
  1205. if (it->rc == MDB_SUCCESS) mdb_cursor_count (it->cur, ct);
  1206. }
  1207. }
  1208. it->i = 0;
  1209. it->iter_op_fn = it_next_1bound;
  1210. it->rc = mdb_cursor_get (it->cur, &it->key, &it->data, MDB_SET);
  1211. if (it->rc == MDB_SUCCESS)
  1212. it->rc = mdb_cursor_get (it->cur, &it->key, &it->data, MDB_GET_MULTIPLE);
  1213. if (it->rc != MDB_SUCCESS && it->rc != MDB_NOTFOUND) {
  1214. log_error ("Database error: %s", LSUP_strerror (it->rc));
  1215. return LSUP_DB_ERR;
  1216. }
  1217. return LSUP_OK;
  1218. }
  1219. inline static LSUP_rc
  1220. lookup_2bound(uint8_t idx0, uint8_t idx1, MDBIterator *it, size_t *ct)
  1221. {
  1222. uint8_t luk1_offset, luk2_offset;
  1223. MDB_dbi dbi = 0;
  1224. // Establish lookup ordering with some awkward offset math.
  1225. for (int i = 0; i < 3; i++) {
  1226. if (
  1227. (
  1228. idx0 == lookup_ordering_2bound[i][0] &&
  1229. idx1 == lookup_ordering_2bound[i][1]
  1230. ) || (
  1231. idx0 == lookup_ordering_2bound[i][1] &&
  1232. idx1 == lookup_ordering_2bound[i][0]
  1233. )
  1234. ) {
  1235. it->term_order = (const uint8_t*)lookup_ordering_2bound[i];
  1236. if (it->term_order[0] == idx0) {
  1237. luk1_offset = 0;
  1238. luk2_offset = 1;
  1239. } else {
  1240. luk1_offset = 1;
  1241. luk2_offset = 0;
  1242. }
  1243. dbi = it->store->dbi[lookup_indices[i + 3]];
  1244. log_debug (
  1245. "Looking up 2 bound in %s",
  1246. db_labels[lookup_indices[i + 3]]);
  1247. break;
  1248. }
  1249. }
  1250. if (dbi == 0) {
  1251. log_error (
  1252. "Values %d and %d not found in lookup keys.",
  1253. idx0, idx1);
  1254. return LSUP_VALUE_ERR;
  1255. }
  1256. // Compose term keys in lookup key.
  1257. LSUP_DoubleKey luk;
  1258. luk[luk1_offset] = it->luk[0];
  1259. luk[luk2_offset] = it->luk[1];
  1260. it->key.mv_data = luk;
  1261. it->key.mv_size = DBL_KLEN;
  1262. mdb_cursor_open (it->txn, dbi, &it->cur);
  1263. it->rc = mdb_cursor_get (it->cur, &it->key, &it->data, MDB_SET);
  1264. if (ct) {
  1265. // If a context is specified, the only way to count triples matching
  1266. // the context is to loop over them.
  1267. if (it->luc != NULL_KEY) {
  1268. MDBIterator *ct_it;
  1269. MALLOC_GUARD (ct_it, LSUP_MEM_ERR);
  1270. ct_it->store = it->store;
  1271. ct_it->txn = it->txn;
  1272. ct_it->ctx_cur = it->ctx_cur;
  1273. ct_it->ck = NULL;
  1274. ct_it->luk[0] = it->luk[0];
  1275. ct_it->luk[1] = it->luk[1];
  1276. ct_it->luc = it->luc;
  1277. ct_it->i = 0;
  1278. lookup_2bound (idx0, idx1, ct_it, NULL);
  1279. while (mdbiter_next_key (ct_it) != LSUP_END) (*ct) ++;
  1280. // Free the counter iterator without freeing the shared txn.
  1281. if (ct_it->cur) mdb_cursor_close (ct_it->cur);
  1282. free (ct_it->ck);
  1283. free (ct_it);
  1284. } else {
  1285. it->rc = mdb_cursor_get (it->cur, &it->key, &it->data, MDB_SET);
  1286. if (it->rc == MDB_SUCCESS) mdb_cursor_count (it->cur, ct);
  1287. }
  1288. }
  1289. it->i = 0;
  1290. it->iter_op_fn = it_next_2bound;
  1291. it->rc = mdb_cursor_get (it->cur, &it->key, &it->data, MDB_SET);
  1292. if (it->rc == MDB_SUCCESS)
  1293. it->rc = mdb_cursor_get (it->cur, &it->key, &it->data, MDB_GET_MULTIPLE);
  1294. if (it->rc != MDB_SUCCESS && it->rc != MDB_NOTFOUND) {
  1295. log_error ("Database error: %s", LSUP_strerror (it->rc));
  1296. return LSUP_DB_ERR;
  1297. }
  1298. return LSUP_OK;
  1299. }
  1300. inline static LSUP_rc
  1301. lookup_3bound (MDBIterator *it, size_t *ct)
  1302. {
  1303. log_debug (
  1304. "Looking up 3 bound: {%lx, %lx, %lx}",
  1305. it->luk[0], it->luk[1], it->luk[2]);
  1306. it->key.mv_data = it->luk;
  1307. if (it->luc != NULL_KEY) {
  1308. it->rc = mdb_cursor_open (
  1309. it->txn, it->store->dbi[IDX_SPO_C], &it->cur);
  1310. it->key.mv_size = TRP_KLEN;
  1311. it->data.mv_data = &it->luc;
  1312. it->data.mv_size = KLEN;
  1313. } else {
  1314. it->rc = mdb_cursor_open (it->txn, it->store->dbi[IDX_S_PO], &it->cur);
  1315. it->key.mv_size = KLEN;
  1316. it->data.mv_data = it->luk + 1;
  1317. it->data.mv_size = DBL_KLEN;
  1318. }
  1319. it->rc = mdb_cursor_get (it->cur, &it->key, &it->data, MDB_GET_BOTH);
  1320. if (it->rc != MDB_SUCCESS && it->rc != MDB_NOTFOUND) {
  1321. log_error ("Database error: %s", LSUP_strerror (it->rc));
  1322. return LSUP_DB_ERR;
  1323. }
  1324. mdb_cursor_close (it->cur);
  1325. it->cur = NULL;
  1326. if (ct && it->rc == MDB_SUCCESS) *ct = 1;
  1327. it->iter_op_fn = it_next_3bound;
  1328. memcpy (it->spok, it->luk, sizeof (LSUP_TripleKey));
  1329. return LSUP_OK;
  1330. }