leveldb_datastore.h 2.63 KB
Newer Older
1 2 3 4 5 6 7
// Copyright (c) 2017, Los Alamos National Security, LLC.
// All rights reserved.
#ifndef ldb_datastore_h
#define ldb_datastore_h

#include "kv-config.h"
#include <leveldb/db.h>
8
#include <leveldb/comparator.h>
9
#include <leveldb/env.h>
10
#include "datastore/datastore.h"
11 12 13

// may want to implement some caching for persistent stores like LevelDB
class LevelDBDataStore : public AbstractDataStore {
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
    private:

        class LevelDBDataStoreComparator : public leveldb::Comparator {
            private:
                LevelDBDataStore* _store;

            public:
                LevelDBDataStoreComparator(LevelDBDataStore* store)
                    : _store(store) {}

                int Compare(const leveldb::Slice& a, const leveldb::Slice& b) const {
                    if(_store->_less) {
                        return _store->_less((const void*)a.data(), a.size(), (const void*)b.data(), b.size());
                    } else {
                        return a.compare(b);
                    }
                }

                // Ignore the following methods for now:
                const char* Name() const { return "LevelDBDataStoreComparator"; }
                void FindShortestSeparator(std::string*, const leveldb::Slice&) const {}
                void FindShortSuccessor(std::string*) const {}
        };

    public:
        LevelDBDataStore();
        LevelDBDataStore(Duplicates duplicates, bool eraseOnGet, bool debug);
        virtual ~LevelDBDataStore();
42
        virtual bool openDatabase(const std::string& db_name, const std::string& path);
43 44 45
        virtual bool put(const ds_bulk_t &key, const ds_bulk_t &data);
        virtual bool get(const ds_bulk_t &key, ds_bulk_t &data);
        virtual bool get(const ds_bulk_t &key, std::vector<ds_bulk_t> &data);
46
        virtual bool exists(const ds_bulk_t &key);
47 48 49
        virtual bool erase(const ds_bulk_t &key);
        virtual void set_in_memory(bool enable); // not supported, a no-op
        virtual void set_comparison_function(comparator_fn less);
50 51 52
        virtual void set_no_overwrite() {
            _no_overwrite = true;
        }
53 54 55 56 57 58 59 60 61
    protected:
        virtual std::vector<ds_bulk_t> vlist_keys(const ds_bulk_t &start, size_t count, const ds_bulk_t &prefix);
        virtual std::vector<std::pair<ds_bulk_t,ds_bulk_t>> vlist_keyvals(const ds_bulk_t &start_key, size_t count, const ds_bulk_t &prefix);
        leveldb::DB *_dbm = NULL;
    private:
        std::string toString(const ds_bulk_t &key);
        ds_bulk_t fromString(const std::string &keystr);
        AbstractDataStore::comparator_fn _less;
        LevelDBDataStoreComparator _keycmp;
62
        bool _no_overwrite = false;
63 64 65
};

#endif // ldb_datastore_h