#include "db.h" #include #include #include #include static std::unordered_map 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); } }