c++protocol-buffersleveldb

Using C++ protobuf formatted structure in leveldb. set/get operations


I'd like to make a POC of using leveldb in order to store key-value table of different data types in protobuf format.

So far I was able to open the database file, and I also saw the get function with the following signature :

virtual Status Get(const ReadOptions& options, const Slice& key, std::string* value)=0

I understand that the value is actually refers to a binary string like vector and not regular alphanumeric string, so I guess it can fit for multi type primitives like string, uint, enum) but how can it support struct/class that represent protobuf layout in c++ ?

So this is my proto file that I'd like to store in the leveldb:

message agentStatus {
    string ip = 1;
    uint32 port = 2;
    string url = 3;
    google.protobuf.Timestamp last_seen = 4;
    google.protobuf.Timestamp last_keepalive = 5;
    bool status = 6;
}

and this is my current POC code. How can I use the get method to access any of the variables from the table above ?

#include <leveldb/db.h>


void main () { 

  std::string db_file_path = "/tmp/data.db";
  leveldb::DB* db;
  leveldb::Status status;

  leveldb::Options options;
  options.create_if_missing = false;
  status_ = leveldb::DB::Open(options, db_file_path, &db);
  if (!status_.ok()) {
    throw std::logic_error("unable to open db");
  }

Thanks !


Solution

    1. You need to serialize the protobuf message into a binary string, i.e. SerilaizeToString, and use the Put method to write the binary string to LevelDB with a key.

    2. Then you can use the Get method to retrieve the binary value with the given key, and parse the binary string to a protobuf message, i.e. ParseFromString.

    3. Finally, you can get fields of the message.