summaryrefslogtreecommitdiff
path: root/datastore-leveldb/src/db.cpp
blob: 84e30f347d63749e69c2041e7c8743bd02f3164e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#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') or
                 (*it == '.'))) {
            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() {
    std::cout << "Close Databases: ";
    auto it = dbs.begin();
    while (it != dbs.end()) {
        std::cout << (*it).first << ". ";
        delete (*it).second;
        dbs.erase(it++); //post increment!
    }
    std::cout << std::endl;
}