store_mdb.c 46 KB

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