store_mdb.c 40 KB

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