store_mdb.c 44 KB

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