diff --git a/cache.h b/cache.h index 4f9ccbf..00e3042 100644 --- a/cache.h +++ b/cache.h @@ -42,6 +42,7 @@ public: virtual bool forceRecord(const K& key, const V& value) override; virtual void changeRecord(const K& key, const V& value) override; virtual void removeRecord(const K& key) override; + virtual bool checkRecord(const K& key) const override; virtual V getRecord(const K& key) const override; virtual uint32_t count() const override; virtual int drop(MDB_txn * transaction) override; diff --git a/cache.hpp b/cache.hpp index 98485c5..89011ae 100644 --- a/cache.hpp +++ b/cache.hpp @@ -137,11 +137,41 @@ V DataBase::Cache::getRecord(const K& key) const { handleMode(); return value; } catch (const NotFound& error) { - abscent->insert(key); + if (*mode != Mode::full) { + abscent->insert(key); + } throw error; } } +template +bool DataBase::Cache::checkRecord(const K& key) const { + if (!DataBase::Table::db->opened) { + throw Closed("checkRecord", DataBase::Table::db->name, DataBase::Table::name); + } + + typename std::map::const_iterator itr = cache->find(key); + if (itr != cache->end()) { + return true; + } + + if (*mode == Mode::full || abscent->count(key) != 0) { + return false; + } + + try { + V value = Table::getRecord(key); + cache->insert(std::make_pair(key, value)); + handleMode(); + return true; + } catch (const NotFound& error) { + if (*mode != Mode::full) { + abscent->insert(key); + } + return false; + } +} + template std::map DataBase::Cache::readAll() const { if (!DataBase::Table::db->opened) { diff --git a/table.h b/table.h index fa647f7..8803e2e 100644 --- a/table.h +++ b/table.h @@ -58,6 +58,7 @@ public: virtual bool forceRecord(const K& key, const V& value); //returns true if there was addition, false if change virtual void changeRecord(const K& key, const V& value); virtual void removeRecord(const K& key); + virtual bool checkRecord(const K& key) const; //checks if there is a record with given key virtual V getRecord(const K& key) const; virtual std::map readAll() const; diff --git a/table.hpp b/table.hpp index c4d0bf8..573c828 100644 --- a/table.hpp +++ b/table.hpp @@ -141,6 +141,32 @@ V DataBase::Table::getRecord(const K& key) const { } } +template +bool DataBase::Table::checkRecord(const K& key) const { + if (!db->opened) { + throw Closed("checkRecord", db->name, name); + } + + MDB_val lmdbKey = keySerializer->setData(key); + MDB_val lmdbData; + + MDB_txn *txn; + int rc; + mdb_txn_begin(db->environment, NULL, MDB_RDONLY, &txn); + rc = mdb_get(txn, dbi, &lmdbKey, &lmdbData); + mdb_txn_abort(txn); + + if (rc) { + if (rc == MDB_NOTFOUND) { + return false; + } else { + throw Unknown(db->name, mdb_strerror(rc), name); + } + } else { + return true; + } +} + template std::map DataBase::Table::readAll() const { if (!db->opened) {