summaryrefslogtreecommitdiff
path: root/include/caffe/lmdb_database.hpp
blob: a8ce60dada5813dab347427dbc57a6f200ef6aec (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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#ifndef CAFFE_LMDB_DATABASE_H_
#define CAFFE_LMDB_DATABASE_H_

#include <string>
#include <utility>
#include <vector>

#include "lmdb.h"

#include "caffe/common.hpp"
#include "caffe/database.hpp"

namespace caffe {

class LmdbDatabase : public Database {
 public:
  LmdbDatabase()
      : env_(NULL),
        dbi_(0),
        txn_(NULL) { }

  bool open(const string& filename, Mode mode);
  bool put(const key_type& key, const value_type& value);
  bool get(const key_type& key, value_type* value);
  bool commit();
  void close();

  void keys(vector<key_type>* keys);

  const_iterator begin() const;
  const_iterator cbegin() const;
  const_iterator end() const;
  const_iterator cend() const;

 protected:
  class LmdbState : public Database::DatabaseState {
   public:
    explicit LmdbState(MDB_cursor* cursor, MDB_txn* txn, const MDB_dbi* dbi)
        : Database::DatabaseState(),
          cursor_(cursor),
          txn_(txn),
          dbi_(dbi) { }

    shared_ptr<DatabaseState> clone() {
      MDB_cursor* new_cursor;

      if (cursor_) {
        int retval;
        retval = mdb_cursor_open(txn_, *dbi_, &new_cursor);
        CHECK_EQ(retval, MDB_SUCCESS) << mdb_strerror(retval);
        MDB_val key;
        MDB_val val;
        retval = mdb_cursor_get(cursor_, &key, &val, MDB_GET_CURRENT);
        CHECK_EQ(retval, MDB_SUCCESS) << mdb_strerror(retval);
        retval = mdb_cursor_get(new_cursor, &key, &val, MDB_SET);
        CHECK_EQ(MDB_SUCCESS, retval) << mdb_strerror(retval);
      } else {
        new_cursor = cursor_;
      }

      return shared_ptr<DatabaseState>(new LmdbState(new_cursor, txn_, dbi_));
    }

    MDB_cursor* cursor_;
    MDB_txn* txn_;
    const MDB_dbi* dbi_;
    KV kv_pair_;
  };

  bool equal(shared_ptr<DatabaseState> state1,
      shared_ptr<DatabaseState> state2) const;
  void increment(shared_ptr<DatabaseState>* state) const;
  Database::KV& dereference(shared_ptr<DatabaseState> state) const;

  MDB_env* env_;
  MDB_dbi dbi_;
  MDB_txn* txn_;
};

}  // namespace caffe

#endif  // CAFFE_LMDB_DATABASE_H_