Kaviranga
Kaviranga

Reputation: 666

How to insert integer values to rocksdb like uint64_t?

I've tested following code for inserting integer values like uint64_t to the rocksdb database using casting . Is that a correct approach ?

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<assert.h>

#include<unistd.h>
#include<stdint.h>

const char DBPath[] = "/tmp/test_sample";

#include "rocksdb/c.h"

int main(int argc, char **argv){

   // Intialize basic parameters
   rocksdb_t *db;
   rocksdb_options_t *options = rocksdb_options_create();

   // Create the database if it's not already present
   rocksdb_options_set_create_if_missing(options,1);

   // Open database
   char *err = NULL;
   db = rocksdb_open(options,DBPath,&err);
   assert(!err);

   //Put key value
   //Insert insert value to the database
   rocksdb_writeoptions_t *writeoptions = rocksdb_writeoptions_create();
   int intKey = 256;
   int intValue = 256*256;

   const char* key;
   const char* value; 

   //Convert integer value to char array
   key = (char*)&intKey; 
   value = (char*)&intValue ; 

   rocksdb_put(db,writeoptions,key,strlen(key),value,strlen(value) + 1,&err);

   assert(!err);

   //Cleanup 
   rocksdb_writeoptions_destroy(writeoptions);
   rocksdb_options_destroy(options);
   rocksdb_close(db);

   return 0;
}

I have referred the following reference Can integer keys / values be stored in LevelDB?

Upvotes: 0

Views: 1447

Answers (2)

midor
midor

Reputation: 5557

Your approach is not portable. What you do is to just dump the integer representation into the binary field. If the code de-serializing your int has a different understanding of int, this won't work. You should use a serialization library to get a stable binary representation of the int, e.g. protobuf/flatbuffers.

How likely is this to blow up in your face? I don't know, depends on your system. Note that rocksdb internally uses serialized representations for all integer types: util/coding.h

Upvotes: 3

Serge Ballesta
Serge Ballesta

Reputation: 148965

There is one major difference between the linked post and your own code: they use sizeof while you use strlen. strlen searches the memory for a null byte. It only makes sense when you really have a null terminated character string.

Here you want to store an integer data, no matter whether it contains null bytes of not. So you must declare the size of that data to be sizeof(int):

rocksdb_put(db,writeoptions,key,sizeof(int),value,sizeof(int),&err);

Upvotes: 1

Related Questions