From ef4b74960718bd492dc8f2e49f61ff9d3e5bd10a Mon Sep 17 00:00:00 2001 From: Christian Mollekopf Date: Thu, 4 Dec 2014 01:15:40 +0100 Subject: ReadTransaction to read stuff. --- store/database.cpp | 74 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ store/database.h | 18 +++++++++++++ 2 files changed, 92 insertions(+) diff --git a/store/database.cpp b/store/database.cpp index 7e2019e..2d93266 100644 --- a/store/database.cpp +++ b/store/database.cpp @@ -101,3 +101,77 @@ void Database::read(const std::string &sKey, const std::function &resultHandler) +{ + int rc; + MDB_val key; + MDB_val data; + MDB_cursor *cursor; + + key.mv_size = sKey.size(); + key.mv_data = (void*)sKey.data(); + + { + //A write transaction is at least required the first time + rc = mdb_txn_begin(env, nullptr, 0, &txn); + //Open the database + //With this we could open multiple named databases if we wanted to + rc = mdb_dbi_open(txn, nullptr, 0, &dbi); + mdb_txn_abort(txn); + } + + rc = mdb_txn_begin(env, nullptr, MDB_RDONLY, &txn); + rc = mdb_cursor_open(txn, dbi, &cursor); + if (rc) { + std::cerr << "mdb_cursor_open: " << rc << mdb_strerror(rc) << std::endl; + } + if (sKey.empty()) { + std::cout << "Iterating over all values of store!" << std::endl; + rc = mdb_cursor_get(cursor, &key, &data, MDB_FIRST); + while ((rc = mdb_cursor_get(cursor, &key, &data, MDB_NEXT)) == 0) { + resultHandler(data.mv_data, data.mv_size); + } + //We never find the last value + if (rc == MDB_NOTFOUND) { + rc = 0; + } + } else { + if ((rc = mdb_cursor_get(cursor, &key, &data, MDB_SET)) == 0) { + resultHandler(data.mv_data, data.mv_size); + } else { + std::cout << "couldn't find value " << sKey << std::endl; + } + } + if (rc) { + std::cerr << "mdb_cursor_get: " << rc << mdb_strerror(rc) << std::endl; + } + mdb_cursor_close(cursor); + //We keep the transaction open since we want to keep the returned values alive +} + diff --git a/store/database.h b/store/database.h index 999a89e..ab398a4 100644 --- a/store/database.h +++ b/store/database.h @@ -18,3 +18,21 @@ private: MDB_env *env; MDB_dbi dbi; }; + +/* + * This opens the db for a single read transaction. + * + * The lifetime of all read values is tied to this transaction. + */ +class ReadTransaction { +public: + ReadTransaction(const QString &path); + ~ReadTransaction(); + + void read(const std::string &sKey, const std::function &); + +private: + MDB_env *env; + MDB_dbi dbi; + MDB_txn *txn; +}; -- cgit v1.2.3