diff options
Diffstat (limited to 'datastore-leveldb/src/db.cpp')
-rw-r--r-- | datastore-leveldb/src/db.cpp | 55 |
1 files changed, 55 insertions, 0 deletions
diff --git a/datastore-leveldb/src/db.cpp b/datastore-leveldb/src/db.cpp new file mode 100644 index 0000000..aae378f --- /dev/null +++ b/datastore-leveldb/src/db.cpp @@ -0,0 +1,55 @@ +#include "db.h" + +#include <iostream> +#include <mutex> +#include <sstream> +#include <unordered_map> + +static std::unordered_map<std::string,leveldb::DB*> dbs; +static std::mutex getDBmutex; + +static bool sensor_name_is_sane(std::string& name) { + for (auto it = name.begin(); it != name.end(); ++it) { + if (not ((*it >= '0' and *it <= '9') or + (*it >= 'A' and *it <= 'Z') or + (*it >= 'a' and *it <= 'z'))) { + return false; + } + } + return true; +} + +leveldb::DB *getDB(std::string& name) { + getDBmutex.lock(); + if (dbs.find(name) == dbs.end()) { + if (not sensor_name_is_sane(name)) { + getDBmutex.unlock(); + return nullptr; + } + leveldb::DB *db; + leveldb::Options options; + options.create_if_missing = true; + leveldb::Status status = leveldb::DB::Open(options, "/tmp/testdb."+name, &db); + if (not status.ok()) { + std::cout << status.ToString() << std::endl; + getDBmutex.unlock(); + return nullptr; + } + dbs[name] = db; + getDBmutex.unlock(); + return db; + } else { + getDBmutex.unlock(); + return dbs.at(name); + } +} + + +void closeDB() { + for (auto it = dbs.begin(); it != dbs.end(); ++it) { + std::cout << "Close " << (*it).first << std::endl; + delete (*it).second; + dbs.erase(it); + } +} + |