store_mdb.c 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655
  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. // Set map size.
  346. size_t mapsize;
  347. char *env_mapsize = getenv ("LSUP_MDB_MAPSIZE");
  348. if (env_mapsize == NULL) mapsize = DEFAULT_MAPSIZE;
  349. else sscanf (env_mapsize, "%lu", &mapsize);
  350. log_info (
  351. "Setting environment map size at %s to %lu Mb.",
  352. path, mapsize / 1024 / 1024);
  353. CHECK (mdb_env_set_mapsize (store->env, mapsize), fail);
  354. CHECK (mdb_env_set_maxdbs (store->env, N_DB), fail);
  355. CHECK (mdb_env_open (store->env, path, 0, ENV_FILE_MODE), fail);
  356. // Assign DB handles to store->dbi.
  357. MDB_txn *txn = NULL;
  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. mdbstore_add_term (store, LSUP_default_ctx_buf, txn);
  371. }
  372. store->flags |= LSSTORE_OPEN;
  373. mdb_txn_commit (txn);
  374. txn = NULL;
  375. return store;
  376. fail:
  377. if (txn) mdb_txn_abort (txn);
  378. mdb_env_close (store->env);
  379. return NULL;
  380. }
  381. static void
  382. mdbstore_free (void *h)
  383. {
  384. MDBStore *store = h;
  385. if (store->flags & LSSTORE_OPEN) {
  386. const char *path;
  387. mdb_env_get_path (store->env, &path);
  388. log_info ("Closing MDB env at %s.", path);
  389. mdb_env_close (store->env);
  390. }
  391. free (store);
  392. }
  393. #if 0
  394. static char *
  395. mdbstore_id (const void *h)
  396. {
  397. const MDBStore *store = h;
  398. const char *path;
  399. mdb_env_get_path (store->env, &path);
  400. return strcat ("file://", path);
  401. }
  402. #endif
  403. static LSUP_rc
  404. mdbstore_stat (const MDBStore *store, MDB_stat *stat)
  405. {
  406. if (!(store->flags & LSSTORE_OPEN)) return 0;
  407. MDB_txn *txn;
  408. mdb_txn_begin (store->env, NULL, MDB_RDONLY, &txn);
  409. if (mdb_stat (txn, store->dbi[IDX_SPO_C], stat) != MDB_SUCCESS)
  410. return LSUP_DB_ERR;
  411. mdb_txn_abort (txn);
  412. return LSUP_OK;
  413. }
  414. static size_t
  415. mdbstore_size (const void *h)
  416. {
  417. const MDBStore *store = h;
  418. // Size is calculated outside of any pending write txn.
  419. MDB_stat stat;
  420. if (mdbstore_stat (store, &stat) != LSUP_OK) return 0;
  421. return stat.ms_entries;
  422. }
  423. static LSUP_rc
  424. mdbstore_txn_begin (void *h, int flags, void **th)
  425. {
  426. MDBStore *store = h;
  427. RCCK (mdb_txn_begin (store->env, NULL, flags, (MDB_txn **) th));
  428. return LSUP_OK;
  429. }
  430. static LSUP_rc
  431. mdbstore_txn_commit (void *th)
  432. {
  433. RCCK (mdb_txn_commit ((MDB_txn *) th));
  434. return LSUP_OK;
  435. }
  436. static void
  437. mdbstore_txn_abort (void *th)
  438. { mdb_txn_abort ((MDB_txn *) th); }
  439. static void *
  440. mdbiter_txn (void *h)
  441. { return ((MDBIterator *) h)->txn; }
  442. /** @brief Begin an add loop.
  443. *
  444. * @sa #store_add_init_fn_t
  445. *
  446. * @param[in] th Previously opened MDB_txn handle, if the add loop shall be
  447. * run within a broader transaction. The transaction must be read-write. The
  448. * operation will always open a new transaction that is closed with
  449. * #mdbstore_add_done() or #mdbstore_add_abort(). If this parameter is not
  450. * NULL, the loop transaction will have the passed txn set as its parent.
  451. */
  452. static void *
  453. mdbstore_add_init (void *h, const LSUP_Buffer *sc, void *th)
  454. {
  455. MDBStore *store = h;
  456. /* An iterator is used here. Some members are a bit misused but it does
  457. * its job without having to define a very similar struct.
  458. */
  459. MDBIterator *it;
  460. MALLOC_GUARD (it, NULL);
  461. it->store = store;
  462. it->i = 0;
  463. mdb_txn_begin (store->env, (MDB_txn *) th, 0, &it->txn);
  464. if (sc) {
  465. // Store context if it's not the default one.
  466. it->luc = LSUP_buffer_hash (sc);
  467. // Insert t:st for context.
  468. //log_debug ("Adding context: %s", sc);
  469. it->key.mv_data = &it->luc;
  470. it->key.mv_size = KLEN;
  471. it->data.mv_data = sc->addr;
  472. it->data.mv_size = sc->size;
  473. int db_rc = mdb_put(
  474. it->txn, it->store->dbi[IDX_T_ST],
  475. &it->key, &it->data, MDB_NOOVERWRITE);
  476. if (db_rc != MDB_SUCCESS && db_rc != MDB_KEYEXIST) {
  477. LOG_RC (db_rc);
  478. mdb_txn_abort (it->txn);
  479. return NULL;
  480. }
  481. } else {
  482. log_debug ("No context passed to iterator, using default.");
  483. it->luc = LSUP_buffer_hash (LSUP_default_ctx_buf);
  484. }
  485. return it;
  486. }
  487. /*
  488. * NOTE: at the moment #mdbstore_remove() or another
  489. * #mdbstore_init() cannot be called between #mdbstore_add_init and
  490. * #mdbstore_add_abort or #mdbstore_add_done. FIXME
  491. *
  492. */
  493. static LSUP_rc
  494. mdbstore_add_iter (void *h, const LSUP_BufferTriple *sspo)
  495. {
  496. if (UNLIKELY (!h)) return LSUP_VALUE_ERR;
  497. MDBIterator *it = h;
  498. int db_rc = LSUP_NOACTION;
  499. LSUP_TripleKey spok = NULL_TRP;
  500. // Add triple terms.
  501. for (int i = 0; i < 3; i++) {
  502. LSUP_Buffer *st = LSUP_btriple_pos (sspo, i);
  503. spok[i] = LSUP_buffer_hash (st);
  504. it->key.mv_data = spok + i;
  505. it->key.mv_size = KLEN;
  506. it->data.mv_data = st->addr;
  507. it->data.mv_size = st->size;
  508. db_rc = mdb_put(
  509. it->txn, it->store->dbi[IDX_T_ST],
  510. &it->key, &it->data, MDB_NOOVERWRITE);
  511. if (db_rc != MDB_SUCCESS && db_rc != MDB_KEYEXIST) {
  512. LOG_RC (db_rc);
  513. return LSUP_DB_ERR;
  514. }
  515. }
  516. log_trace ("Inserting spok: {%lx, %lx, %lx}", spok[0], spok[1], spok[2]);
  517. log_trace ("Into context: %lx", it->luc);
  518. // Insert spo:c.
  519. it->key.mv_data = spok;
  520. it->key.mv_size = TRP_KLEN;
  521. // In triple mode, data is empty (= NULL_KEY).
  522. it->data.mv_data = &it->luc;
  523. it->data.mv_size = it->luc == NULL_KEY ? 0 : KLEN;
  524. db_rc = mdb_put(
  525. it->txn, it->store->dbi[IDX_SPO_C],
  526. &it->key, &it->data, MDB_NODUPDATA);
  527. if (db_rc == MDB_KEYEXIST) return LSUP_NOACTION;
  528. if (db_rc != MDB_SUCCESS) {
  529. log_error (
  530. "MDB error while inserting triple: %s", LSUP_strerror(db_rc));
  531. return LSUP_DB_ERR;
  532. }
  533. // Index.
  534. LSUP_rc rc = index_triple (it->store, OP_ADD, spok, it->luc, it->txn);
  535. if (rc == LSUP_OK) it->i++;
  536. return rc;
  537. }
  538. static LSUP_rc
  539. mdbstore_add_done (void *h)
  540. {
  541. MDBIterator *it = h;
  542. LSUP_rc rc = LSUP_OK;
  543. if (mdb_txn_commit (it->txn) != MDB_SUCCESS) {
  544. mdb_txn_abort (it->txn);
  545. rc = LSUP_TXN_ERR;
  546. }
  547. free (it);
  548. return rc;
  549. }
  550. static void
  551. mdbstore_add_abort (void *h)
  552. {
  553. MDBIterator *it = h;
  554. mdb_txn_abort (it->txn);
  555. free (it);
  556. }
  557. #if 0
  558. /* TODO deprecate. Use low-level instead and abstract at graph level. */
  559. static LSUP_rc
  560. mdbstore_add (
  561. void *h, const LSUP_Buffer *sc,
  562. const LSUP_BufferTriple strp[], const size_t ct, size_t *inserted)
  563. {
  564. MDBStore *store = h;
  565. MDBIterator *it = mdbstore_add_init (store, sc);
  566. if (UNLIKELY (!it)) return LSUP_DB_ERR;
  567. for (size_t i = 0; i < ct; i++) {
  568. LSUP_rc rc = mdbstore_add_iter (it, strp + i);
  569. if (UNLIKELY (rc < 0)) {
  570. mdbstore_add_abort (it);
  571. return rc;
  572. }
  573. }
  574. *inserted = it->i;
  575. return mdbstore_add_done (it);
  576. }
  577. #endif
  578. static LSUP_rc
  579. key_to_sterm (MDBIterator *it, const LSUP_Key key, LSUP_Buffer *sterm)
  580. {
  581. LSUP_rc rc = LSUP_NORESULT;
  582. int db_rc;
  583. MDB_val key_v, data_v;
  584. key_v.mv_data = (void*)&key;
  585. key_v.mv_size = KLEN;
  586. db_rc = mdb_get (it->txn, it->store->dbi[IDX_T_ST], &key_v, &data_v);
  587. if (db_rc == MDB_SUCCESS) {
  588. sterm->addr = data_v.mv_data;
  589. sterm->size = data_v.mv_size;
  590. rc = LSUP_OK;
  591. } else if (db_rc == MDB_NOTFOUND) {
  592. sterm->addr = NULL;
  593. sterm->size = 0;
  594. } else rc = LSUP_DB_ERR;
  595. return rc;
  596. }
  597. static void *
  598. mdbstore_lookup (
  599. void *h, const LSUP_Buffer *ss, const LSUP_Buffer *sp,
  600. const LSUP_Buffer *so, const LSUP_Buffer *sc, void *th, size_t *ct)
  601. {
  602. LSUP_TripleKey spok = {
  603. LSUP_buffer_hash (ss),
  604. LSUP_buffer_hash (sp),
  605. LSUP_buffer_hash (so),
  606. };
  607. MDBIterator *it;
  608. CALLOC_GUARD (it, NULL);
  609. it->store = h;
  610. it->luc = LSUP_buffer_hash (sc);
  611. log_debug ("Lookup context: %lx", it->luc);
  612. if (ct) *ct = 0;
  613. uint8_t idx0, idx1;
  614. // Start RO transaction if not in a write txn already.
  615. if (th) it->txn = th;
  616. else {
  617. it->rc = mdb_txn_begin (it->store->env, NULL, MDB_RDONLY, &it->txn);
  618. if (it->rc != MDB_SUCCESS) {
  619. log_error ("Database error: %s", LSUP_strerror (it->rc));
  620. return NULL;
  621. }
  622. it->flags |= ITER_OPEN_TXN;
  623. }
  624. // Context index loop.
  625. if (UNLIKELY (mdb_cursor_open (
  626. it->txn, it->store->dbi[IDX_SPO_C], &it->ctx_cur) != MDB_SUCCESS))
  627. return NULL;
  628. /*
  629. * Lookup decision tree.
  630. */
  631. // s p o (all terms bound)
  632. if (spok[0] != NULL_KEY && spok[1] != NULL_KEY && spok[2] != NULL_KEY) {
  633. it->luk[0] = spok[0];
  634. it->luk[1] = spok[1];
  635. it->luk[2] = spok[2];
  636. PRCNL (lookup_3bound (it, ct));
  637. } else if (spok[0] != NULL_KEY) {
  638. it->luk[0] = spok[0];
  639. idx0 = 0;
  640. // s p ?
  641. if (spok[1] != NULL_KEY) {
  642. it->luk[1] = spok[1];
  643. idx1 = 1;
  644. PRCNL (lookup_2bound (idx0, idx1, it, ct));
  645. // s ? o
  646. } else if (spok[2] != NULL_KEY) {
  647. it->luk[1] = spok[2];
  648. idx1 = 2;
  649. PRCNL (lookup_2bound (idx0, idx1, it, ct));
  650. // s ? ?
  651. } else PRCNL (lookup_1bound (idx0, it, ct));
  652. } else if (spok[1] != NULL_KEY) {
  653. it->luk[0] = spok[1];
  654. idx0 = 1;
  655. // ? p o
  656. if (spok[2] != NULL_KEY) {
  657. it->luk[1] = spok[2];
  658. idx1 = 2;
  659. PRCNL (lookup_2bound (idx0, idx1, it, ct));
  660. // ? p ?
  661. } else PRCNL (lookup_1bound (idx0, it, ct));
  662. // ? ? o
  663. } else if (spok[2] != NULL_KEY) {
  664. it->luk[0] = spok[2];
  665. idx0 = 2;
  666. PRCNL (lookup_1bound (idx0, it, ct));
  667. // ? ? ? (all terms unbound)
  668. } else PRCNL (lookup_0bound (it, ct));
  669. return it;
  670. }
  671. /** @brief Get next iterator key.
  672. *
  673. * ckset is filled with an array of contexts that the triple appears
  674. * in, if not NULL.
  675. */
  676. static LSUP_rc
  677. mdbiter_next_key (MDBIterator *it)
  678. {
  679. if (UNLIKELY (!it)) return LSUP_VALUE_ERR;
  680. // Only advance if the previous it->rc wasn't already at the end.
  681. if (it->rc == MDB_NOTFOUND) return LSUP_END;
  682. if (UNLIKELY (it->rc != MDB_SUCCESS)) {
  683. log_error ("Database error: %s", LSUP_strerror (it->rc));
  684. return LSUP_DB_ERR;
  685. }
  686. LSUP_rc rc;
  687. /* Retrieve current value and advance cursor to the next result.
  688. * it->rc is set to the result of the next iteration.
  689. */
  690. it->iter_op_fn (it);
  691. log_trace (
  692. "Found spok: {%lx, %lx, %lx}",
  693. it->spok[0], it->spok[1], it->spok[2]);
  694. MDB_val key, data;
  695. int db_rc;
  696. key.mv_size = TRP_KLEN;
  697. data.mv_data = &it->luc;
  698. data.mv_size = KLEN;
  699. if (it->luc) {
  700. rc = LSUP_NORESULT; // Intermediary value, will never be returned.
  701. while (rc == LSUP_NORESULT) {
  702. //log_debug ("begin ctx loop.");
  703. // If ctx is specified, look if the matching triple is associated
  704. // with it. If not, move on to the next triple.
  705. // The loop normally exits when a triple with matching ctx is found
  706. // (LSUP_OK), if there are no more triples (LSUP_END), or if there
  707. // is an error (LSUP_DB_ERR).
  708. key.mv_data = it->spok;
  709. db_rc = mdb_cursor_get (it->ctx_cur, &key, &data, MDB_GET_BOTH);
  710. if (db_rc == MDB_SUCCESS) {
  711. rc = LSUP_OK;
  712. log_trace ("Triple found for context.");
  713. } else if (db_rc == MDB_NOTFOUND) {
  714. log_trace ("No triples found for context.");
  715. if (it->rc == MDB_NOTFOUND) rc = LSUP_END;
  716. else it->iter_op_fn (it);
  717. } else {
  718. log_error ("Database error: %s", LSUP_strerror (db_rc));
  719. rc = LSUP_DB_ERR;
  720. }
  721. }
  722. } else rc = LSUP_OK;
  723. // Get all contexts for a triple.
  724. key.mv_data = it->spok;
  725. db_rc = mdb_cursor_get (it->ctx_cur, &key, &data, MDB_SET_KEY);
  726. if (db_rc != MDB_SUCCESS) {
  727. log_error ("No context found for triple!");
  728. return LSUP_DB_ERR;
  729. }
  730. size_t ct;
  731. db_rc = mdb_cursor_count (it->ctx_cur, &ct);
  732. if (db_rc != MDB_SUCCESS) return LSUP_DB_ERR;
  733. // 1 spare for sentinel. Always allocated even on zero matches.
  734. LSUP_Key *tmp_ck = realloc (it->ck, sizeof (*it->ck) * (ct + 1));
  735. if (!tmp_ck) return LSUP_MEM_ERR;
  736. it->ck = tmp_ck;
  737. size_t i = 0;
  738. do {
  739. //log_trace("Copying to slot #%lu @%p", i, it->ck + i);
  740. memcpy (it->ck + i++, data.mv_data, sizeof (*it->ck));
  741. } while (
  742. mdb_cursor_get (it->ctx_cur, &key, &data, MDB_NEXT_DUP)
  743. == MDB_SUCCESS);
  744. //log_trace ("setting sentinel @%p", it->ck + i);
  745. it->ck[i] = NULL_KEY;
  746. return rc;
  747. }
  748. static LSUP_rc
  749. mdbiter_next (
  750. void *h, LSUP_BufferTriple *sspo, LSUP_Buffer **ctx_p)
  751. {
  752. MDBIterator *it = h;
  753. LSUP_rc rc = mdbiter_next_key (it);
  754. if (rc == LSUP_OK) {
  755. if (sspo) {
  756. key_to_sterm (it, it->spok[0], sspo->s);
  757. key_to_sterm (it, it->spok[1], sspo->p);
  758. key_to_sterm (it, it->spok[2], sspo->o);
  759. // TODO error handling.
  760. }
  761. // Contexts for current triple.
  762. if (ctx_p) {
  763. // Preallocate.
  764. size_t i = 0;
  765. while (it->ck[i++]); // Include sentinel in count.
  766. LSUP_Buffer *ctx;
  767. log_trace("Allocating %lu context buffers.", i);
  768. ctx = malloc(i * sizeof (*ctx));
  769. if (!ctx) return LSUP_MEM_ERR;
  770. for (i = 0; it->ck[i]; i++)
  771. key_to_sterm (it, it->ck[i], ctx + i);
  772. memset (ctx + i, 0, sizeof (*ctx)); // Sentinel
  773. // TODO error handling.
  774. *ctx_p = ctx;
  775. }
  776. }
  777. return rc;
  778. }
  779. static void
  780. mdbiter_free (void *h)
  781. {
  782. MDBIterator *it = h;
  783. if (!it) return;
  784. if (it->cur) mdb_cursor_close (it->cur);
  785. if (it->ctx_cur) mdb_cursor_close (it->ctx_cur);
  786. if (it->flags & ITER_OPEN_TXN) mdb_txn_abort (it->txn);
  787. free (it->ck);
  788. free (it);
  789. }
  790. static LSUP_rc
  791. mdbstore_remove (
  792. void *h, const LSUP_Buffer *ss, const LSUP_Buffer *sp,
  793. const LSUP_Buffer *so, const LSUP_Buffer *sc, void *th, size_t *ct)
  794. {
  795. MDBStore *store = h;
  796. LSUP_rc rc = LSUP_NOACTION, db_rc;
  797. LSUP_Key ck = NULL_KEY;
  798. if (sc == NULL) sc = LSUP_default_ctx_buf;
  799. ck = LSUP_buffer_hash (sc);
  800. MDB_txn *txn;
  801. mdb_txn_begin (store->env, (MDB_txn *) th, 0, &txn);
  802. MDB_cursor *dcur, *icur;
  803. mdb_cursor_open (txn, store->dbi[IDX_SPO_C], &dcur);
  804. mdb_cursor_open (txn, store->dbi[IDX_C_SPO], &icur);
  805. MDB_val spok_v, ck_v;
  806. spok_v.mv_size = TRP_KLEN;
  807. ck_v.mv_size = KLEN;
  808. ck_v.mv_data = &ck;
  809. // The lookup operates within the current (bottom) write transaction.
  810. MDBIterator *it = mdbstore_lookup (store, ss, sp, so, sc, txn, ct);
  811. if (UNLIKELY (!it)) return LSUP_DB_ERR;
  812. if (ct) log_debug ("Found %lu triples to remove.", *ct);
  813. while (mdbiter_next_key (it) == LSUP_OK) {
  814. spok_v.mv_data = it->spok;
  815. db_rc = mdb_cursor_get (dcur, &spok_v, &ck_v, MDB_GET_BOTH);
  816. if (db_rc == MDB_NOTFOUND) continue;
  817. if (UNLIKELY (db_rc != MDB_SUCCESS)) goto fail;
  818. log_trace (
  819. "Removing {%lx, %lx, %lx}",
  820. it->spok[0], it->spok[1], it->spok[2]);
  821. // Delete spo:c entry.
  822. db_rc = mdb_cursor_del (dcur, 0);
  823. if (UNLIKELY (db_rc != MDB_SUCCESS)) goto fail;
  824. // Restore ck address after each delete.
  825. spok_v.mv_data = it->spok;
  826. ck_v.mv_data = &ck;
  827. // Delete c:spo entry.
  828. db_rc = mdb_cursor_get (icur, &ck_v, &spok_v, MDB_GET_BOTH);
  829. if (db_rc == MDB_NOTFOUND) continue;
  830. if (UNLIKELY (db_rc != MDB_SUCCESS)) goto fail;
  831. db_rc = mdb_cursor_del (icur, 0);
  832. if (UNLIKELY (db_rc != MDB_SUCCESS)) goto fail;
  833. spok_v.mv_data = it->spok;
  834. ck_v.mv_data = &ck;
  835. // If there are no more contexts associated with this triple,
  836. // remove from indices.
  837. db_rc = mdb_cursor_get (dcur, &spok_v, NULL, MDB_SET);
  838. if (db_rc == MDB_SUCCESS) continue;
  839. if (UNLIKELY (db_rc != MDB_NOTFOUND)) goto fail;
  840. rc = index_triple (store, OP_REMOVE, it->spok, ck, txn);
  841. }
  842. mdbiter_free (it);
  843. if (UNLIKELY (mdb_txn_commit (txn) != MDB_SUCCESS)) {
  844. rc = LSUP_TXN_ERR;
  845. goto fail;
  846. }
  847. return rc;
  848. fail:
  849. mdb_txn_abort (txn);
  850. log_error ("Database error: %s", LSUP_strerror (db_rc));
  851. return rc == LSUP_TXN_ERR ? rc : LSUP_DB_ERR;
  852. }
  853. #if 0
  854. static int
  855. mdbstore_tkey_exists (MDBStore *store, LSUP_Key tkey)
  856. {
  857. int db_rc, rc;
  858. MDB_val key, data;
  859. key.mv_data = &tkey;
  860. key.mv_size = KLEN;
  861. MDB_txn *txn = NULL;
  862. mdb_txn_begin (store->env, NULL, MDB_RDONLY, &txn);
  863. MDB_cursor *cur = NULL;
  864. mdb_cursor_open (txn, store->dbi[IDX_T_ST], &cur);
  865. db_rc = mdb_cursor_get (cur, &key, &data, MDB_SET);
  866. if (db_rc == MDB_SUCCESS) rc = 1;
  867. else if (db_rc == MDB_NOTFOUND) rc = 0;
  868. else {
  869. log_error ("DB error: %s", LSUP_strerror (db_rc));
  870. rc = LSUP_DB_ERR;
  871. }
  872. if (cur) mdb_cursor_close (cur);
  873. if (txn) mdb_txn_abort (txn);
  874. return rc;
  875. }
  876. #endif
  877. static LSUP_rc
  878. mdbstore_add_term (void *h, const LSUP_Buffer *sterm, void *th)
  879. {
  880. MDBStore *store = h;
  881. int db_rc;
  882. MDB_val key, data;
  883. MDB_txn *txn;
  884. // If store->txn exists, open a child txn, otherwise reuse the same txn.
  885. if (th) txn = th;
  886. else RCCK (mdb_txn_begin (store->env, NULL, 0, &txn));
  887. MDB_cursor *cur;
  888. CHECK (mdb_cursor_open (txn, store->dbi[IDX_T_ST], &cur), fail);
  889. LSUP_Key k = LSUP_buffer_hash (sterm);
  890. key.mv_data = &k;
  891. key.mv_size = sizeof (k);
  892. data.mv_data = sterm->addr;
  893. data.mv_size = sterm->size;
  894. db_rc = mdb_cursor_put (cur, &key, &data, MDB_NOOVERWRITE);
  895. if (db_rc != MDB_KEYEXIST) CHECK (db_rc, fail);
  896. if (!th) CHECK (db_rc = mdb_txn_commit (txn), fail);
  897. return LSUP_OK;
  898. fail:
  899. if (!th) mdb_txn_abort (txn);
  900. return LSUP_DB_ERR;
  901. }
  902. const LSUP_StoreInt mdbstore_int = {
  903. .name = "MDB Store",
  904. .features = LSUP_STORE_PERM | LSUP_STORE_CTX | LSUP_STORE_IDX
  905. | LSUP_STORE_TXN | LSUP_STORE_COW,
  906. .setup_fn = mdbstore_setup,
  907. .new_fn = mdbstore_new,
  908. .free_fn = mdbstore_free,
  909. .size_fn = mdbstore_size,
  910. .txn_begin_fn = mdbstore_txn_begin,
  911. .txn_commit_fn = mdbstore_txn_commit,
  912. .txn_abort_fn = mdbstore_txn_abort,
  913. .iter_txn_fn = mdbiter_txn,
  914. .add_init_fn = mdbstore_add_init,
  915. .add_iter_fn = mdbstore_add_iter,
  916. .add_abort_fn = mdbstore_add_abort,
  917. .add_done_fn = mdbstore_add_done,
  918. .add_term_fn = mdbstore_add_term,
  919. .lookup_fn = mdbstore_lookup,
  920. .lu_next_fn = mdbiter_next,
  921. .lu_free_fn = mdbiter_free,
  922. .remove_fn = mdbstore_remove,
  923. .nsm_put_fn = mdbstore_nsm_put,
  924. .nsm_get_fn = mdbstore_nsm_get,
  925. };
  926. /* * * Static functions. * * */
  927. /** @brief Index an added or removed triple.
  928. *
  929. * @param store[in] MDB store to index.
  930. * @param op[in] Store operation. One of OP_ADD or OP_REMOVE.
  931. * @param spok[in] Triple key to index.
  932. * @param ck[in] Context to index, may be NULL.
  933. * @param[in] th Transaction handle. This MUST be a valid pointer to an open
  934. * RW transaction.
  935. */
  936. static LSUP_rc
  937. index_triple(
  938. MDBStore *store, StoreOp op, LSUP_TripleKey spok, LSUP_Key ck,
  939. MDB_txn *txn)
  940. {
  941. int db_rc;
  942. LSUP_rc rc = LSUP_NOACTION;
  943. MDB_val v1, v2;
  944. log_trace ("Indexing triple: {%lx %lx %lx}", spok[0], spok[1], spok[2]);
  945. // Index c:spo.
  946. if (op == OP_REMOVE) {
  947. log_trace ("Indexing op: REMOVE");
  948. if (ck != NULL_KEY) {
  949. MDB_cursor *cur;
  950. v1.mv_data = &ck;
  951. v1.mv_size = KLEN;
  952. v2.mv_data = spok;
  953. v2.mv_size = TRP_KLEN;
  954. mdb_cursor_open (txn, store->dbi[IDX_C_SPO], &cur);
  955. if (mdb_cursor_get (cur, &v1, &v2, MDB_GET_BOTH) == MDB_SUCCESS) {
  956. db_rc = mdb_cursor_del (cur, 0);
  957. if (db_rc != MDB_SUCCESS) return LSUP_DB_ERR;
  958. rc = LSUP_OK;
  959. }
  960. mdb_cursor_close (cur);
  961. }
  962. } else if (op == OP_ADD) {
  963. log_trace ("Indexing op: ADD");
  964. if (ck != NULL_KEY) {
  965. v1.mv_data = &ck;
  966. v1.mv_size = KLEN;
  967. v2.mv_data = spok;
  968. v2.mv_size = TRP_KLEN;
  969. db_rc = mdb_put(
  970. txn, store->dbi[IDX_C_SPO],
  971. &v1, &v2, MDB_NODUPDATA);
  972. if (db_rc != MDB_SUCCESS) return LSUP_DB_ERR;
  973. if (db_rc != MDB_KEYEXIST) rc = LSUP_OK;
  974. }
  975. } else return LSUP_VALUE_ERR;
  976. LSUP_DoubleKey dbl_keys[3] = {
  977. {spok[1], spok[2]}, // po
  978. {spok[0], spok[2]}, // so
  979. {spok[0], spok[1]}, // sp
  980. };
  981. // Add terms to index.
  982. v1.mv_size = KLEN;
  983. v2.mv_size = DBL_KLEN;
  984. for (int i = 0; i < 3; i++) {
  985. MDB_dbi db1 = store->dbi[lookup_indices[i]]; // s:po, p:so, o:sp
  986. MDB_dbi db2 = store->dbi[lookup_indices[i + 3]]; // po:s, so:p, sp:o
  987. v1.mv_data = spok + i;
  988. v2.mv_data = dbl_keys[i];
  989. if (op == OP_REMOVE) {
  990. MDB_cursor *cur1, *cur2;
  991. mdb_cursor_open(txn, store->dbi[lookup_indices[i]], &cur1);
  992. db_rc = mdb_cursor_get (cur1, &v1, &v2, MDB_GET_BOTH);
  993. if (db_rc == MDB_SUCCESS) mdb_cursor_del (cur1, 0);
  994. mdb_cursor_close (cur1);
  995. // Restore pointers invalidated after delete.
  996. v1.mv_data = spok + i;
  997. v2.mv_data = dbl_keys[i];
  998. mdb_cursor_open(txn, store->dbi[lookup_indices[i + 3]], &cur2);
  999. db_rc = mdb_cursor_get (cur2, &v2, &v1, MDB_GET_BOTH);
  1000. if (db_rc == MDB_SUCCESS) mdb_cursor_del (cur2, 0);
  1001. // TODO error handling.
  1002. rc = LSUP_OK;
  1003. mdb_cursor_close (cur2);
  1004. } else { // OP_ADD is guaranteed.
  1005. // 1-bound index.
  1006. log_trace ("Indexing in %s: ", db_labels[lookup_indices[i]]);
  1007. log_trace (
  1008. "%lx: %lx %lx", *(size_t*)(v1.mv_data),
  1009. *(size_t*)(v2.mv_data), *(size_t*)(v2.mv_data) + 1);
  1010. db_rc = mdb_put (txn, db1, &v1, &v2, MDB_NODUPDATA);
  1011. if (db_rc == MDB_SUCCESS) rc = LSUP_OK;
  1012. else if (db_rc != MDB_KEYEXIST) return LSUP_DB_ERR;
  1013. // 2-bound index.
  1014. log_trace ("Indexing in %s: ", db_labels[lookup_indices[i + 3]]);
  1015. log_trace (
  1016. "%lx %lx: %lx", *(size_t*)(v2.mv_data),
  1017. *(size_t*)(v2.mv_data) + 1, *(size_t*)(v1.mv_data));
  1018. db_rc = mdb_put (txn, db2, &v2, &v1, MDB_NODUPDATA);
  1019. if (db_rc == MDB_SUCCESS) rc = LSUP_OK;
  1020. else if (db_rc != MDB_KEYEXIST) return LSUP_DB_ERR;
  1021. }
  1022. }
  1023. return rc;
  1024. }
  1025. /* * * Term-specific iterators. * * */
  1026. /** @brief Advance 0-bound iterator.
  1027. *
  1028. * Cursor: spo:c
  1029. */
  1030. inline static void
  1031. it_next_0bound (MDBIterator *it)
  1032. {
  1033. memcpy (it->spok, it->key.mv_data, sizeof (LSUP_TripleKey));
  1034. it->rc = mdb_cursor_get (it->cur, &it->key, &it->data, MDB_NEXT);
  1035. }
  1036. /** @brief Advance 1-bound iterator.
  1037. *
  1038. * Uses paged data in a nested loop.
  1039. *
  1040. * Cursor: s:po, p:so, or o:sp.
  1041. */
  1042. inline static void
  1043. it_next_1bound (MDBIterator *it)
  1044. {
  1045. LSUP_DoubleKey *lu_dset = it->data.mv_data;
  1046. it->spok[it->term_order[0]] = it->luk[0];
  1047. it->spok[it->term_order[1]] = lu_dset[it->i][0];
  1048. it->spok[it->term_order[2]] = lu_dset[it->i][1];
  1049. log_trace (
  1050. "Composed triple: {%lx %lx %lx}",
  1051. it->spok[0], it->spok[1], it->spok[2]);
  1052. // Ensure next block within the same page is not beyond the last.
  1053. if (it->i < it->data.mv_size / DBL_KLEN - 1) {
  1054. it->i ++;
  1055. //log_debug ("Increasing page cursor to %lu.", it->i);
  1056. //log_debug ("it->rc: %d", it->rc);
  1057. } else {
  1058. // If the last block in the page is being yielded,
  1059. // move cursor to beginning of next page.
  1060. it->i = 0;
  1061. //log_debug ("Reset page cursor to %lu.", it->i);
  1062. it->rc = mdb_cursor_get (
  1063. it->cur, &it->key, &it->data, MDB_NEXT_MULTIPLE);
  1064. }
  1065. }
  1066. /** @brief Advance 2-bound iterator.
  1067. *
  1068. * Uses paged data in a nested loop.
  1069. *
  1070. * Cursor: po:s, so:p, or sp:o.
  1071. */
  1072. inline static void
  1073. it_next_2bound (MDBIterator *it)
  1074. {
  1075. LSUP_Key *lu_dset = it->data.mv_data;
  1076. it->spok[it->term_order[0]] = it->luk[0];
  1077. it->spok[it->term_order[1]] = it->luk[1];
  1078. it->spok[it->term_order[2]] = lu_dset[it->i];
  1079. // Ensure next block within the same page is not beyond the last.
  1080. if (it->i < it->data.mv_size / KLEN - 1)
  1081. it->i ++;
  1082. else {
  1083. // If the last block in the page is being yielded,
  1084. // move cursor to beginning of next page.
  1085. it->i = 0;
  1086. it->rc = mdb_cursor_get (it->cur, &it->key, &it->data, MDB_NEXT_MULTIPLE);
  1087. }
  1088. }
  1089. /** @brief Advance 3-bound iterator.
  1090. *
  1091. * This is a special case of 0÷1 results; either there was one matching triple,
  1092. * which was already set in the first result, or there was none, i.e. it->rc is
  1093. * already MDB_NOTFOUND and this function will not be called.
  1094. */
  1095. inline static void
  1096. it_next_3bound (MDBIterator *it)
  1097. {
  1098. it->rc = MDB_NOTFOUND;
  1099. }
  1100. /* * * Term-specific lookups. * * */
  1101. inline static LSUP_rc
  1102. lookup_0bound (MDBIterator *it, size_t *ct)
  1103. {
  1104. log_debug ("Looking up 0 bound terms.");
  1105. if (ct) {
  1106. if (it->luc != NULL_KEY) {
  1107. // Look up by given context.
  1108. it->rc = mdb_cursor_open (
  1109. it->txn, it->store->dbi[IDX_C_SPO], &it->cur);
  1110. it->key.mv_data = &it->luc;
  1111. it->key.mv_size = KLEN;
  1112. it->rc = mdb_cursor_get (it->cur, &it->key, &it->data, MDB_SET);
  1113. if (it->rc == MDB_SUCCESS) mdb_cursor_count (it->cur, ct);
  1114. mdb_cursor_close (it->cur);
  1115. it->cur = NULL;
  1116. } else {
  1117. // Look up all contexts.
  1118. MDB_stat stat;
  1119. mdb_stat (it->txn, it->store->dbi[IDX_S_PO], &stat);
  1120. *ct = stat.ms_entries;
  1121. }
  1122. log_debug ("Found %lu keys.", *ct);
  1123. }
  1124. it->rc = mdb_cursor_open (it->txn, it->store->dbi[IDX_SPO_C], &it->cur);
  1125. if (it->rc != MDB_SUCCESS) {
  1126. log_error ("Database error: %s", LSUP_strerror (it->rc));
  1127. return LSUP_DB_ERR;
  1128. }
  1129. it->rc = mdb_cursor_get (it->cur, &it->key, &it->data, MDB_FIRST);
  1130. /*
  1131. mdb_cursor_close (it->cur);
  1132. it->cur = NULL;
  1133. */
  1134. it->iter_op_fn = it_next_0bound;
  1135. if (it->rc != MDB_SUCCESS && it->rc != MDB_NOTFOUND) {
  1136. log_error ("Database error: %s", LSUP_strerror (it->rc));
  1137. return LSUP_DB_ERR;
  1138. }
  1139. return LSUP_OK;
  1140. }
  1141. inline static LSUP_rc
  1142. lookup_1bound (uint8_t idx0, MDBIterator *it, size_t *ct)
  1143. {
  1144. it->term_order = (const uint8_t*)lookup_ordering_1bound[idx0];
  1145. log_debug ("Looking up 1 bound term: %lx", it->luk[0]);
  1146. mdb_cursor_open (it->txn, it->store->dbi[lookup_indices[idx0]], &it->cur);
  1147. it->key.mv_data = it->luk;
  1148. it->key.mv_size = KLEN;
  1149. if (ct) {
  1150. // If a context is specified, the only way to count triples matching
  1151. // the context is to loop over them.
  1152. if (it->luc != NULL_KEY) {
  1153. log_debug ("Counting in context: %lx", it->luc);
  1154. MDBIterator *ct_it;
  1155. MALLOC_GUARD (ct_it, LSUP_MEM_ERR);
  1156. /*
  1157. memcpy (ct_it, it, sizeof (*ct_it));
  1158. */
  1159. ct_it->store = it->store;
  1160. ct_it->txn = it->txn;
  1161. ct_it->ctx_cur = it->ctx_cur;
  1162. ct_it->key = it->key;
  1163. ct_it->data = it->data;
  1164. ct_it->ck = NULL;
  1165. ct_it->luk[0] = it->luk[0];
  1166. ct_it->luc = it->luc;
  1167. ct_it->i = 0;
  1168. LSUP_rc rc = lookup_1bound (idx0, ct_it, NULL);
  1169. if (rc < 0) return rc;
  1170. LSUP_rc db_rc;
  1171. while (LSUP_END != (db_rc = mdbiter_next_key (ct_it))) {
  1172. if (UNLIKELY (db_rc < 0)) return db_rc;
  1173. (*ct)++;
  1174. }
  1175. // Free the counter iterator without freeing the shared txn.
  1176. if (ct_it->cur) mdb_cursor_close (ct_it->cur);
  1177. free (ct_it->ck);
  1178. free (ct_it);
  1179. } else {
  1180. it->rc = mdb_cursor_get (it->cur, &it->key, &it->data, MDB_SET);
  1181. if (it->rc == MDB_SUCCESS) mdb_cursor_count (it->cur, ct);
  1182. }
  1183. }
  1184. it->i = 0;
  1185. it->iter_op_fn = it_next_1bound;
  1186. it->rc = mdb_cursor_get (it->cur, &it->key, &it->data, MDB_SET);
  1187. if (it->rc == MDB_SUCCESS)
  1188. it->rc = mdb_cursor_get (it->cur, &it->key, &it->data, MDB_GET_MULTIPLE);
  1189. if (it->rc != MDB_SUCCESS && it->rc != MDB_NOTFOUND) {
  1190. log_error ("Database error: %s", LSUP_strerror (it->rc));
  1191. return LSUP_DB_ERR;
  1192. }
  1193. return LSUP_OK;
  1194. }
  1195. inline static LSUP_rc
  1196. lookup_2bound(uint8_t idx0, uint8_t idx1, MDBIterator *it, size_t *ct)
  1197. {
  1198. uint8_t luk1_offset, luk2_offset;
  1199. MDB_dbi dbi = 0;
  1200. // Establish lookup ordering with some awkward offset math.
  1201. for (int i = 0; i < 3; i++) {
  1202. if (
  1203. (
  1204. idx0 == lookup_ordering_2bound[i][0] &&
  1205. idx1 == lookup_ordering_2bound[i][1]
  1206. ) || (
  1207. idx0 == lookup_ordering_2bound[i][1] &&
  1208. idx1 == lookup_ordering_2bound[i][0]
  1209. )
  1210. ) {
  1211. it->term_order = (const uint8_t*)lookup_ordering_2bound[i];
  1212. if (it->term_order[0] == idx0) {
  1213. luk1_offset = 0;
  1214. luk2_offset = 1;
  1215. } else {
  1216. luk1_offset = 1;
  1217. luk2_offset = 0;
  1218. }
  1219. dbi = it->store->dbi[lookup_indices[i + 3]];
  1220. log_debug (
  1221. "Looking up 2 bound in %s",
  1222. db_labels[lookup_indices[i + 3]]);
  1223. break;
  1224. }
  1225. }
  1226. if (dbi == 0) {
  1227. log_error (
  1228. "Values %d and %d not found in lookup keys.",
  1229. idx0, idx1);
  1230. return LSUP_VALUE_ERR;
  1231. }
  1232. // Compose term keys in lookup key.
  1233. LSUP_DoubleKey luk;
  1234. luk[luk1_offset] = it->luk[0];
  1235. luk[luk2_offset] = it->luk[1];
  1236. it->key.mv_data = luk;
  1237. it->key.mv_size = DBL_KLEN;
  1238. mdb_cursor_open (it->txn, dbi, &it->cur);
  1239. it->rc = mdb_cursor_get (it->cur, &it->key, &it->data, MDB_SET);
  1240. if (ct) {
  1241. // If a context is specified, the only way to count triples matching
  1242. // the context is to loop over them.
  1243. if (it->luc != NULL_KEY) {
  1244. MDBIterator *ct_it;
  1245. MALLOC_GUARD (ct_it, LSUP_MEM_ERR);
  1246. ct_it->store = it->store;
  1247. ct_it->txn = it->txn;
  1248. ct_it->ctx_cur = it->ctx_cur;
  1249. ct_it->ck = NULL;
  1250. ct_it->luk[0] = it->luk[0];
  1251. ct_it->luk[1] = it->luk[1];
  1252. ct_it->luc = it->luc;
  1253. ct_it->i = 0;
  1254. lookup_2bound (idx0, idx1, ct_it, NULL);
  1255. while (mdbiter_next_key (ct_it) != LSUP_END) (*ct) ++;
  1256. // Free the counter iterator without freeing the shared txn.
  1257. if (ct_it->cur) mdb_cursor_close (ct_it->cur);
  1258. free (ct_it->ck);
  1259. free (ct_it);
  1260. } else {
  1261. it->rc = mdb_cursor_get (it->cur, &it->key, &it->data, MDB_SET);
  1262. if (it->rc == MDB_SUCCESS) mdb_cursor_count (it->cur, ct);
  1263. }
  1264. }
  1265. it->i = 0;
  1266. it->iter_op_fn = it_next_2bound;
  1267. it->rc = mdb_cursor_get (it->cur, &it->key, &it->data, MDB_SET);
  1268. if (it->rc == MDB_SUCCESS)
  1269. it->rc = mdb_cursor_get (it->cur, &it->key, &it->data, MDB_GET_MULTIPLE);
  1270. if (it->rc != MDB_SUCCESS && it->rc != MDB_NOTFOUND) {
  1271. log_error ("Database error: %s", LSUP_strerror (it->rc));
  1272. return LSUP_DB_ERR;
  1273. }
  1274. return LSUP_OK;
  1275. }
  1276. inline static LSUP_rc
  1277. lookup_3bound (MDBIterator *it, size_t *ct)
  1278. {
  1279. log_debug (
  1280. "Looking up 3 bound: {%lx, %lx, %lx}",
  1281. it->luk[0], it->luk[1], it->luk[2]);
  1282. it->key.mv_data = it->luk;
  1283. if (it->luc != NULL_KEY) {
  1284. it->rc = mdb_cursor_open (
  1285. it->txn, it->store->dbi[IDX_SPO_C], &it->cur);
  1286. it->key.mv_size = TRP_KLEN;
  1287. it->data.mv_data = &it->luc;
  1288. it->data.mv_size = KLEN;
  1289. } else {
  1290. it->rc = mdb_cursor_open (it->txn, it->store->dbi[IDX_S_PO], &it->cur);
  1291. it->key.mv_size = KLEN;
  1292. it->data.mv_data = it->luk + 1;
  1293. it->data.mv_size = DBL_KLEN;
  1294. }
  1295. it->rc = mdb_cursor_get (it->cur, &it->key, &it->data, MDB_GET_BOTH);
  1296. if (it->rc != MDB_SUCCESS && it->rc != MDB_NOTFOUND) {
  1297. log_error ("Database error: %s", LSUP_strerror (it->rc));
  1298. return LSUP_DB_ERR;
  1299. }
  1300. mdb_cursor_close (it->cur);
  1301. it->cur = NULL;
  1302. if (ct && it->rc == MDB_SUCCESS) *ct = 1;
  1303. it->iter_op_fn = it_next_3bound;
  1304. memcpy (it->spok, it->luk, sizeof (LSUP_TripleKey));
  1305. return LSUP_OK;
  1306. }