diff options
author | Ebus-at-dockstar <ebus@dockstar> | 2014-07-26 19:55:43 +0200 |
---|---|---|
committer | Ebus-at-dockstar <ebus@dockstar> | 2014-07-26 19:55:43 +0200 |
commit | a8cd2ecf7387d7bbe16808ca0c7acdb04a4909cb (patch) | |
tree | 524672c3237be2552379f9d752184bd3cbf1d554 /datastore-leveldb/src/db.cpp | |
parent | 3f5b5ff5e71cf078c2c04906bffa06f3a1050085 (diff) | |
download | ebus-alt-a8cd2ecf7387d7bbe16808ca0c7acdb04a4909cb.tar.gz ebus-alt-a8cd2ecf7387d7bbe16808ca0c7acdb04a4909cb.zip |
Revert "embed xexpr-path" restore datastore-leveldb and other stuff
This reverts commit f6675ccdd7a5997def3c4656f0e2c5dbbbed1fc8.
Diffstat (limited to 'datastore-leveldb/src/db.cpp')
-rw-r--r-- | datastore-leveldb/src/db.cpp | 74 |
1 files changed, 74 insertions, 0 deletions
diff --git a/datastore-leveldb/src/db.cpp b/datastore-leveldb/src/db.cpp new file mode 100644 index 0000000..991a82e --- /dev/null +++ b/datastore-leveldb/src/db.cpp @@ -0,0 +1,74 @@ +#include "db.h" + +#include <iomanip> +#include <iostream> +#include <mutex> +#include <unordered_map> +#include <sstream> + +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') or + (*it == '.'))) { + return false; + } + } + return true; +} + +std::string db_make_key(const uint64_t timestamp) { + std::stringstream key; + key << "ts-"; + key << std::setfill('0') << std::setw(20) << timestamp; + return key.str(); +} + +leveldb::DB *db_get(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, "data/"+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); + } +} + + +bool db_insert(std::string& name, const uint64_t timestamp, std::string& value) { + leveldb::DB *db = db_get(name); + if (db == nullptr) return false; + + auto status = db->Put(leveldb::WriteOptions(), db_make_key(timestamp), value); + return status.ok(); +} + +void db_close() { + auto it = dbs.begin(); + while (it != dbs.end()) { + std::cout << "Close Database: " << (*it).first << std::endl; + delete (*it).second; + dbs.erase(it++); //post increment! + } + std::cout << std::endl; +} + |