store_mdb.c 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657
  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
  797. rc = LSUP_NOACTION,
  798. db_rc = 0;
  799. LSUP_Key ck = NULL_KEY;
  800. if (sc == NULL) sc = LSUP_default_ctx_buf;
  801. ck = LSUP_buffer_hash (sc);
  802. MDB_txn *txn;
  803. mdb_txn_begin (store->env, (MDB_txn *) th, 0, &txn);
  804. MDB_cursor *dcur, *icur;
  805. mdb_cursor_open (txn, store->dbi[IDX_SPO_C], &dcur);
  806. mdb_cursor_open (txn, store->dbi[IDX_C_SPO], &icur);
  807. MDB_val spok_v, ck_v;
  808. spok_v.mv_size = TRP_KLEN;
  809. ck_v.mv_size = KLEN;
  810. ck_v.mv_data = &ck;
  811. // The lookup operates within the current (bottom) write transaction.
  812. MDBIterator *it = mdbstore_lookup (store, ss, sp, so, sc, txn, ct);
  813. if (UNLIKELY (!it)) return LSUP_DB_ERR;
  814. if (ct) log_debug ("Found %lu triples to remove.", *ct);
  815. while (mdbiter_next_key (it) == LSUP_OK) {
  816. spok_v.mv_data = it->spok;
  817. db_rc = mdb_cursor_get (dcur, &spok_v, &ck_v, MDB_GET_BOTH);
  818. if (db_rc == MDB_NOTFOUND) continue;
  819. if (UNLIKELY (db_rc != MDB_SUCCESS)) goto fail;
  820. log_trace (
  821. "Removing {%lx, %lx, %lx}",
  822. it->spok[0], it->spok[1], it->spok[2]);
  823. // Delete spo:c entry.
  824. db_rc = mdb_cursor_del (dcur, 0);
  825. if (UNLIKELY (db_rc != MDB_SUCCESS)) goto fail;
  826. // Restore ck address after each delete.
  827. spok_v.mv_data = it->spok;
  828. ck_v.mv_data = &ck;
  829. // Delete c:spo entry.
  830. db_rc = mdb_cursor_get (icur, &ck_v, &spok_v, MDB_GET_BOTH);
  831. if (db_rc == MDB_NOTFOUND) continue;
  832. if (UNLIKELY (db_rc != MDB_SUCCESS)) goto fail;
  833. db_rc = mdb_cursor_del (icur, 0);
  834. if (UNLIKELY (db_rc != MDB_SUCCESS)) goto fail;
  835. spok_v.mv_data = it->spok;
  836. ck_v.mv_data = &ck;
  837. // If there are no more contexts associated with this triple,
  838. // remove from indices.
  839. db_rc = mdb_cursor_get (dcur, &spok_v, NULL, MDB_SET);
  840. if (db_rc == MDB_SUCCESS) continue;
  841. if (UNLIKELY (db_rc != MDB_NOTFOUND)) goto fail;
  842. rc = index_triple (store, OP_REMOVE, it->spok, ck, txn);
  843. }
  844. mdbiter_free (it);
  845. if (UNLIKELY (mdb_txn_commit (txn) != MDB_SUCCESS)) {
  846. rc = LSUP_TXN_ERR;
  847. goto fail;
  848. }
  849. return rc;
  850. fail:
  851. mdb_txn_abort (txn);
  852. log_error ("Database error: %s", LSUP_strerror (db_rc));
  853. return rc == LSUP_TXN_ERR ? rc : LSUP_DB_ERR;
  854. }
  855. #if 0
  856. static int
  857. mdbstore_tkey_exists (MDBStore *store, LSUP_Key tkey)
  858. {
  859. int db_rc, rc;
  860. MDB_val key, data;
  861. key.mv_data = &tkey;
  862. key.mv_size = KLEN;
  863. MDB_txn *txn = NULL;
  864. mdb_txn_begin (store->env, NULL, MDB_RDONLY, &txn);
  865. MDB_cursor *cur = NULL;
  866. mdb_cursor_open (txn, store->dbi[IDX_T_ST], &cur);
  867. db_rc = mdb_cursor_get (cur, &key, &data, MDB_SET);
  868. if (db_rc == MDB_SUCCESS) rc = 1;
  869. else if (db_rc == MDB_NOTFOUND) rc = 0;
  870. else {
  871. log_error ("DB error: %s", LSUP_strerror (db_rc));
  872. rc = LSUP_DB_ERR;
  873. }
  874. if (cur) mdb_cursor_close (cur);
  875. if (txn) mdb_txn_abort (txn);
  876. return rc;
  877. }
  878. #endif
  879. static LSUP_rc
  880. mdbstore_add_term (void *h, const LSUP_Buffer *sterm, void *th)
  881. {
  882. MDBStore *store = h;
  883. int db_rc;
  884. MDB_val key, data;
  885. MDB_txn *txn;
  886. // If store->txn exists, open a child txn, otherwise reuse the same txn.
  887. if (th) txn = th;
  888. else RCCK (mdb_txn_begin (store->env, NULL, 0, &txn));
  889. MDB_cursor *cur;
  890. CHECK (mdb_cursor_open (txn, store->dbi[IDX_T_ST], &cur), fail);
  891. LSUP_Key k = LSUP_buffer_hash (sterm);
  892. key.mv_data = &k;
  893. key.mv_size = sizeof (k);
  894. data.mv_data = sterm->addr;
  895. data.mv_size = sterm->size;
  896. db_rc = mdb_cursor_put (cur, &key, &data, MDB_NOOVERWRITE);
  897. if (db_rc != MDB_KEYEXIST) CHECK (db_rc, fail);
  898. if (!th) CHECK (db_rc = mdb_txn_commit (txn), fail);
  899. return LSUP_OK;
  900. fail:
  901. if (!th) mdb_txn_abort (txn);
  902. return LSUP_DB_ERR;
  903. }
  904. const LSUP_StoreInt mdbstore_int = {
  905. .name = "MDB Store",
  906. .features = LSUP_STORE_PERM | LSUP_STORE_CTX | LSUP_STORE_IDX
  907. | LSUP_STORE_TXN | LSUP_STORE_COW,
  908. .setup_fn = mdbstore_setup,
  909. .new_fn = mdbstore_new,
  910. .free_fn = mdbstore_free,
  911. .size_fn = mdbstore_size,
  912. .txn_begin_fn = mdbstore_txn_begin,
  913. .txn_commit_fn = mdbstore_txn_commit,
  914. .txn_abort_fn = mdbstore_txn_abort,
  915. .iter_txn_fn = mdbiter_txn,
  916. .add_init_fn = mdbstore_add_init,
  917. .add_iter_fn = mdbstore_add_iter,
  918. .add_abort_fn = mdbstore_add_abort,
  919. .add_done_fn = mdbstore_add_done,
  920. .add_term_fn = mdbstore_add_term,
  921. .lookup_fn = mdbstore_lookup,
  922. .lu_next_fn = mdbiter_next,
  923. .lu_free_fn = mdbiter_free,
  924. .remove_fn = mdbstore_remove,
  925. .nsm_put_fn = mdbstore_nsm_put,
  926. .nsm_get_fn = mdbstore_nsm_get,
  927. };
  928. /* * * Static functions. * * */
  929. /** @brief Index an added or removed triple.
  930. *
  931. * @param store[in] MDB store to index.
  932. * @param op[in] Store operation. One of OP_ADD or OP_REMOVE.
  933. * @param spok[in] Triple key to index.
  934. * @param ck[in] Context to index, may be NULL.
  935. * @param[in] th Transaction handle. This MUST be a valid pointer to an open
  936. * RW transaction.
  937. */
  938. static LSUP_rc
  939. index_triple(
  940. MDBStore *store, StoreOp op, LSUP_TripleKey spok, LSUP_Key ck,
  941. MDB_txn *txn)
  942. {
  943. int db_rc;
  944. LSUP_rc rc = LSUP_NOACTION;
  945. MDB_val v1, v2;
  946. log_trace ("Indexing triple: {%lx %lx %lx}", spok[0], spok[1], spok[2]);
  947. // Index c:spo.
  948. if (op == OP_REMOVE) {
  949. log_trace ("Indexing op: REMOVE");
  950. if (ck != NULL_KEY) {
  951. MDB_cursor *cur;
  952. v1.mv_data = &ck;
  953. v1.mv_size = KLEN;
  954. v2.mv_data = spok;
  955. v2.mv_size = TRP_KLEN;
  956. mdb_cursor_open (txn, store->dbi[IDX_C_SPO], &cur);
  957. if (mdb_cursor_get (cur, &v1, &v2, MDB_GET_BOTH) == MDB_SUCCESS) {
  958. db_rc = mdb_cursor_del (cur, 0);
  959. if (db_rc != MDB_SUCCESS) return LSUP_DB_ERR;
  960. rc = LSUP_OK;
  961. }
  962. mdb_cursor_close (cur);
  963. }
  964. } else if (op == OP_ADD) {
  965. log_trace ("Indexing op: ADD");
  966. if (ck != NULL_KEY) {
  967. v1.mv_data = &ck;
  968. v1.mv_size = KLEN;
  969. v2.mv_data = spok;
  970. v2.mv_size = TRP_KLEN;
  971. db_rc = mdb_put(
  972. txn, store->dbi[IDX_C_SPO],
  973. &v1, &v2, MDB_NODUPDATA);
  974. if (db_rc != MDB_SUCCESS) return LSUP_DB_ERR;
  975. if (db_rc != MDB_KEYEXIST) rc = LSUP_OK;
  976. }
  977. } else return LSUP_VALUE_ERR;
  978. LSUP_DoubleKey dbl_keys[3] = {
  979. {spok[1], spok[2]}, // po
  980. {spok[0], spok[2]}, // so
  981. {spok[0], spok[1]}, // sp
  982. };
  983. // Add terms to index.
  984. v1.mv_size = KLEN;
  985. v2.mv_size = DBL_KLEN;
  986. for (int i = 0; i < 3; i++) {
  987. MDB_dbi db1 = store->dbi[lookup_indices[i]]; // s:po, p:so, o:sp
  988. MDB_dbi db2 = store->dbi[lookup_indices[i + 3]]; // po:s, so:p, sp:o
  989. v1.mv_data = spok + i;
  990. v2.mv_data = dbl_keys[i];
  991. if (op == OP_REMOVE) {
  992. MDB_cursor *cur1, *cur2;
  993. mdb_cursor_open(txn, store->dbi[lookup_indices[i]], &cur1);
  994. db_rc = mdb_cursor_get (cur1, &v1, &v2, MDB_GET_BOTH);
  995. if (db_rc == MDB_SUCCESS) mdb_cursor_del (cur1, 0);
  996. mdb_cursor_close (cur1);
  997. // Restore pointers invalidated after delete.
  998. v1.mv_data = spok + i;
  999. v2.mv_data = dbl_keys[i];
  1000. mdb_cursor_open(txn, store->dbi[lookup_indices[i + 3]], &cur2);
  1001. db_rc = mdb_cursor_get (cur2, &v2, &v1, MDB_GET_BOTH);
  1002. if (db_rc == MDB_SUCCESS) mdb_cursor_del (cur2, 0);
  1003. // TODO error handling.
  1004. rc = LSUP_OK;
  1005. mdb_cursor_close (cur2);
  1006. } else { // OP_ADD is guaranteed.
  1007. // 1-bound index.
  1008. log_trace ("Indexing in %s: ", db_labels[lookup_indices[i]]);
  1009. log_trace (
  1010. "%lx: %lx %lx", *(size_t*)(v1.mv_data),
  1011. *(size_t*)(v2.mv_data), *(size_t*)(v2.mv_data) + 1);
  1012. db_rc = mdb_put (txn, db1, &v1, &v2, MDB_NODUPDATA);
  1013. if (db_rc == MDB_SUCCESS) rc = LSUP_OK;
  1014. else if (db_rc != MDB_KEYEXIST) return LSUP_DB_ERR;
  1015. // 2-bound index.
  1016. log_trace ("Indexing in %s: ", db_labels[lookup_indices[i + 3]]);
  1017. log_trace (
  1018. "%lx %lx: %lx", *(size_t*)(v2.mv_data),
  1019. *(size_t*)(v2.mv_data) + 1, *(size_t*)(v1.mv_data));
  1020. db_rc = mdb_put (txn, db2, &v2, &v1, MDB_NODUPDATA);
  1021. if (db_rc == MDB_SUCCESS) rc = LSUP_OK;
  1022. else if (db_rc != MDB_KEYEXIST) return LSUP_DB_ERR;
  1023. }
  1024. }
  1025. return rc;
  1026. }
  1027. /* * * Term-specific iterators. * * */
  1028. /** @brief Advance 0-bound iterator.
  1029. *
  1030. * Cursor: spo:c
  1031. */
  1032. inline static void
  1033. it_next_0bound (MDBIterator *it)
  1034. {
  1035. memcpy (it->spok, it->key.mv_data, sizeof (LSUP_TripleKey));
  1036. it->rc = mdb_cursor_get (it->cur, &it->key, &it->data, MDB_NEXT);
  1037. }
  1038. /** @brief Advance 1-bound iterator.
  1039. *
  1040. * Uses paged data in a nested loop.
  1041. *
  1042. * Cursor: s:po, p:so, or o:sp.
  1043. */
  1044. inline static void
  1045. it_next_1bound (MDBIterator *it)
  1046. {
  1047. LSUP_DoubleKey *lu_dset = it->data.mv_data;
  1048. it->spok[it->term_order[0]] = it->luk[0];
  1049. it->spok[it->term_order[1]] = lu_dset[it->i][0];
  1050. it->spok[it->term_order[2]] = lu_dset[it->i][1];
  1051. log_trace (
  1052. "Composed triple: {%lx %lx %lx}",
  1053. it->spok[0], it->spok[1], it->spok[2]);
  1054. // Ensure next block within the same page is not beyond the last.
  1055. if (it->i < it->data.mv_size / DBL_KLEN - 1) {
  1056. it->i ++;
  1057. //log_debug ("Increasing page cursor to %lu.", it->i);
  1058. //log_debug ("it->rc: %d", it->rc);
  1059. } else {
  1060. // If the last block in the page is being yielded,
  1061. // move cursor to beginning of next page.
  1062. it->i = 0;
  1063. //log_debug ("Reset page cursor to %lu.", it->i);
  1064. it->rc = mdb_cursor_get (
  1065. it->cur, &it->key, &it->data, MDB_NEXT_MULTIPLE);
  1066. }
  1067. }
  1068. /** @brief Advance 2-bound iterator.
  1069. *
  1070. * Uses paged data in a nested loop.
  1071. *
  1072. * Cursor: po:s, so:p, or sp:o.
  1073. */
  1074. inline static void
  1075. it_next_2bound (MDBIterator *it)
  1076. {
  1077. LSUP_Key *lu_dset = it->data.mv_data;
  1078. it->spok[it->term_order[0]] = it->luk[0];
  1079. it->spok[it->term_order[1]] = it->luk[1];
  1080. it->spok[it->term_order[2]] = lu_dset[it->i];
  1081. // Ensure next block within the same page is not beyond the last.
  1082. if (it->i < it->data.mv_size / KLEN - 1)
  1083. it->i ++;
  1084. else {
  1085. // If the last block in the page is being yielded,
  1086. // move cursor to beginning of next page.
  1087. it->i = 0;
  1088. it->rc = mdb_cursor_get (it->cur, &it->key, &it->data, MDB_NEXT_MULTIPLE);
  1089. }
  1090. }
  1091. /** @brief Advance 3-bound iterator.
  1092. *
  1093. * This is a special case of 0÷1 results; either there was one matching triple,
  1094. * which was already set in the first result, or there was none, i.e. it->rc is
  1095. * already MDB_NOTFOUND and this function will not be called.
  1096. */
  1097. inline static void
  1098. it_next_3bound (MDBIterator *it)
  1099. {
  1100. it->rc = MDB_NOTFOUND;
  1101. }
  1102. /* * * Term-specific lookups. * * */
  1103. inline static LSUP_rc
  1104. lookup_0bound (MDBIterator *it, size_t *ct)
  1105. {
  1106. log_debug ("Looking up 0 bound terms.");
  1107. if (ct) {
  1108. if (it->luc != NULL_KEY) {
  1109. // Look up by given context.
  1110. it->rc = mdb_cursor_open (
  1111. it->txn, it->store->dbi[IDX_C_SPO], &it->cur);
  1112. it->key.mv_data = &it->luc;
  1113. it->key.mv_size = KLEN;
  1114. it->rc = mdb_cursor_get (it->cur, &it->key, &it->data, MDB_SET);
  1115. if (it->rc == MDB_SUCCESS) mdb_cursor_count (it->cur, ct);
  1116. mdb_cursor_close (it->cur);
  1117. it->cur = NULL;
  1118. } else {
  1119. // Look up all contexts.
  1120. MDB_stat stat;
  1121. mdb_stat (it->txn, it->store->dbi[IDX_S_PO], &stat);
  1122. *ct = stat.ms_entries;
  1123. }
  1124. log_debug ("Found %lu keys.", *ct);
  1125. }
  1126. it->rc = mdb_cursor_open (it->txn, it->store->dbi[IDX_SPO_C], &it->cur);
  1127. if (it->rc != MDB_SUCCESS) {
  1128. log_error ("Database error: %s", LSUP_strerror (it->rc));
  1129. return LSUP_DB_ERR;
  1130. }
  1131. it->rc = mdb_cursor_get (it->cur, &it->key, &it->data, MDB_FIRST);
  1132. /*
  1133. mdb_cursor_close (it->cur);
  1134. it->cur = NULL;
  1135. */
  1136. it->iter_op_fn = it_next_0bound;
  1137. if (it->rc != MDB_SUCCESS && it->rc != MDB_NOTFOUND) {
  1138. log_error ("Database error: %s", LSUP_strerror (it->rc));
  1139. return LSUP_DB_ERR;
  1140. }
  1141. return LSUP_OK;
  1142. }
  1143. inline static LSUP_rc
  1144. lookup_1bound (uint8_t idx0, MDBIterator *it, size_t *ct)
  1145. {
  1146. it->term_order = (const uint8_t*)lookup_ordering_1bound[idx0];
  1147. log_debug ("Looking up 1 bound term: %lx", it->luk[0]);
  1148. mdb_cursor_open (it->txn, it->store->dbi[lookup_indices[idx0]], &it->cur);
  1149. it->key.mv_data = it->luk;
  1150. it->key.mv_size = KLEN;
  1151. if (ct) {
  1152. // If a context is specified, the only way to count triples matching
  1153. // the context is to loop over them.
  1154. if (it->luc != NULL_KEY) {
  1155. log_debug ("Counting in context: %lx", it->luc);
  1156. MDBIterator *ct_it;
  1157. MALLOC_GUARD (ct_it, LSUP_MEM_ERR);
  1158. /*
  1159. memcpy (ct_it, it, sizeof (*ct_it));
  1160. */
  1161. ct_it->store = it->store;
  1162. ct_it->txn = it->txn;
  1163. ct_it->ctx_cur = it->ctx_cur;
  1164. ct_it->key = it->key;
  1165. ct_it->data = it->data;
  1166. ct_it->ck = NULL;
  1167. ct_it->luk[0] = it->luk[0];
  1168. ct_it->luc = it->luc;
  1169. ct_it->i = 0;
  1170. LSUP_rc rc = lookup_1bound (idx0, ct_it, NULL);
  1171. if (rc < 0) return rc;
  1172. LSUP_rc db_rc;
  1173. while (LSUP_END != (db_rc = mdbiter_next_key (ct_it))) {
  1174. if (UNLIKELY (db_rc < 0)) return db_rc;
  1175. (*ct)++;
  1176. }
  1177. // Free the counter iterator without freeing the shared txn.
  1178. if (ct_it->cur) mdb_cursor_close (ct_it->cur);
  1179. free (ct_it->ck);
  1180. free (ct_it);
  1181. } else {
  1182. it->rc = mdb_cursor_get (it->cur, &it->key, &it->data, MDB_SET);
  1183. if (it->rc == MDB_SUCCESS) mdb_cursor_count (it->cur, ct);
  1184. }
  1185. }
  1186. it->i = 0;
  1187. it->iter_op_fn = it_next_1bound;
  1188. it->rc = mdb_cursor_get (it->cur, &it->key, &it->data, MDB_SET);
  1189. if (it->rc == MDB_SUCCESS)
  1190. it->rc = mdb_cursor_get (it->cur, &it->key, &it->data, MDB_GET_MULTIPLE);
  1191. if (it->rc != MDB_SUCCESS && it->rc != MDB_NOTFOUND) {
  1192. log_error ("Database error: %s", LSUP_strerror (it->rc));
  1193. return LSUP_DB_ERR;
  1194. }
  1195. return LSUP_OK;
  1196. }
  1197. inline static LSUP_rc
  1198. lookup_2bound(uint8_t idx0, uint8_t idx1, MDBIterator *it, size_t *ct)
  1199. {
  1200. uint8_t luk1_offset, luk2_offset;
  1201. MDB_dbi dbi = 0;
  1202. // Establish lookup ordering with some awkward offset math.
  1203. for (int i = 0; i < 3; i++) {
  1204. if (
  1205. (
  1206. idx0 == lookup_ordering_2bound[i][0] &&
  1207. idx1 == lookup_ordering_2bound[i][1]
  1208. ) || (
  1209. idx0 == lookup_ordering_2bound[i][1] &&
  1210. idx1 == lookup_ordering_2bound[i][0]
  1211. )
  1212. ) {
  1213. it->term_order = (const uint8_t*)lookup_ordering_2bound[i];
  1214. if (it->term_order[0] == idx0) {
  1215. luk1_offset = 0;
  1216. luk2_offset = 1;
  1217. } else {
  1218. luk1_offset = 1;
  1219. luk2_offset = 0;
  1220. }
  1221. dbi = it->store->dbi[lookup_indices[i + 3]];
  1222. log_debug (
  1223. "Looking up 2 bound in %s",
  1224. db_labels[lookup_indices[i + 3]]);
  1225. break;
  1226. }
  1227. }
  1228. if (dbi == 0) {
  1229. log_error (
  1230. "Values %d and %d not found in lookup keys.",
  1231. idx0, idx1);
  1232. return LSUP_VALUE_ERR;
  1233. }
  1234. // Compose term keys in lookup key.
  1235. LSUP_DoubleKey luk;
  1236. luk[luk1_offset] = it->luk[0];
  1237. luk[luk2_offset] = it->luk[1];
  1238. it->key.mv_data = luk;
  1239. it->key.mv_size = DBL_KLEN;
  1240. mdb_cursor_open (it->txn, dbi, &it->cur);
  1241. it->rc = mdb_cursor_get (it->cur, &it->key, &it->data, MDB_SET);
  1242. if (ct) {
  1243. // If a context is specified, the only way to count triples matching
  1244. // the context is to loop over them.
  1245. if (it->luc != NULL_KEY) {
  1246. MDBIterator *ct_it;
  1247. MALLOC_GUARD (ct_it, LSUP_MEM_ERR);
  1248. ct_it->store = it->store;
  1249. ct_it->txn = it->txn;
  1250. ct_it->ctx_cur = it->ctx_cur;
  1251. ct_it->ck = NULL;
  1252. ct_it->luk[0] = it->luk[0];
  1253. ct_it->luk[1] = it->luk[1];
  1254. ct_it->luc = it->luc;
  1255. ct_it->i = 0;
  1256. lookup_2bound (idx0, idx1, ct_it, NULL);
  1257. while (mdbiter_next_key (ct_it) != LSUP_END) (*ct) ++;
  1258. // Free the counter iterator without freeing the shared txn.
  1259. if (ct_it->cur) mdb_cursor_close (ct_it->cur);
  1260. free (ct_it->ck);
  1261. free (ct_it);
  1262. } else {
  1263. it->rc = mdb_cursor_get (it->cur, &it->key, &it->data, MDB_SET);
  1264. if (it->rc == MDB_SUCCESS) mdb_cursor_count (it->cur, ct);
  1265. }
  1266. }
  1267. it->i = 0;
  1268. it->iter_op_fn = it_next_2bound;
  1269. it->rc = mdb_cursor_get (it->cur, &it->key, &it->data, MDB_SET);
  1270. if (it->rc == MDB_SUCCESS)
  1271. it->rc = mdb_cursor_get (it->cur, &it->key, &it->data, MDB_GET_MULTIPLE);
  1272. if (it->rc != MDB_SUCCESS && it->rc != MDB_NOTFOUND) {
  1273. log_error ("Database error: %s", LSUP_strerror (it->rc));
  1274. return LSUP_DB_ERR;
  1275. }
  1276. return LSUP_OK;
  1277. }
  1278. inline static LSUP_rc
  1279. lookup_3bound (MDBIterator *it, size_t *ct)
  1280. {
  1281. log_debug (
  1282. "Looking up 3 bound: {%lx, %lx, %lx}",
  1283. it->luk[0], it->luk[1], it->luk[2]);
  1284. it->key.mv_data = it->luk;
  1285. if (it->luc != NULL_KEY) {
  1286. it->rc = mdb_cursor_open (
  1287. it->txn, it->store->dbi[IDX_SPO_C], &it->cur);
  1288. it->key.mv_size = TRP_KLEN;
  1289. it->data.mv_data = &it->luc;
  1290. it->data.mv_size = KLEN;
  1291. } else {
  1292. it->rc = mdb_cursor_open (it->txn, it->store->dbi[IDX_S_PO], &it->cur);
  1293. it->key.mv_size = KLEN;
  1294. it->data.mv_data = it->luk + 1;
  1295. it->data.mv_size = DBL_KLEN;
  1296. }
  1297. it->rc = mdb_cursor_get (it->cur, &it->key, &it->data, MDB_GET_BOTH);
  1298. if (it->rc != MDB_SUCCESS && it->rc != MDB_NOTFOUND) {
  1299. log_error ("Database error: %s", LSUP_strerror (it->rc));
  1300. return LSUP_DB_ERR;
  1301. }
  1302. mdb_cursor_close (it->cur);
  1303. it->cur = NULL;
  1304. if (ct && it->rc == MDB_SUCCESS) *ct = 1;
  1305. it->iter_op_fn = it_next_3bound;
  1306. memcpy (it->spok, it->luk, sizeof (LSUP_TripleKey));
  1307. return LSUP_OK;
  1308. }