From 95ff695381c9662ec100697bebc6132bc317c005 Mon Sep 17 00:00:00 2001 From: Martchus Date: Mon, 7 Mar 2022 23:31:47 +0100 Subject: [PATCH] Add helper to rebuild typed database --- lmdb-typed.hh | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/lmdb-typed.hh b/lmdb-typed.hh index ec1bd75..b096b6e 100644 --- a/lmdb-typed.hh +++ b/lmdb-typed.hh @@ -838,6 +838,30 @@ public: d_parent->forEachIndex([&](auto &&i) { i.clear(*d_txn); }); } + //! \brief Rebuilds the database, possibly throwing out invalid objects. + //! \param func Specifies a function which is supposed to return whether an object is still valid. + //! It might modify the passed object in order to "fix" it. + void rebuild(const std::function &func) + { + // clear all indexes to get rid of invalid entries + d_parent->forEachIndex([&](auto &&i) { i.clear(*d_txn); }); + // check all objects via func + for (auto i = this->begin(), end = this->end(); i != end; ++i) { + T *val = nullptr; + try { + val = &i.value(); + } catch (...) { // catch possible deserialization errors + } + if (func(i.getID(), val)) { + if (val) { + put(*val, i.getID()); + } + } else { + i.del(); + } + } + } + //! Commits this transaction. void commit() {