1 // Copyright (c) 2011-present, Facebook, Inc.  All rights reserved.
2 //  This source code is licensed under both the GPLv2 (found in the
3 //  COPYING file in the root directory) and Apache 2.0 License
4 //  (found in the LICENSE.Apache file in the root directory).
5 
6 #include <cstdio>
7 #include <string>
8 
9 #include "rocksdb/db.h"
10 #include "rocksdb/slice.h"
11 #include "rocksdb/options.h"
12 
13 using namespace ROCKSDB_NAMESPACE;
14 
15 std::string kDBPath = "/tmp/rocksdb_simple_example";
16 
main()17 int main() {
18   DB* db;
19   Options options;
20   // Optimize RocksDB. This is the easiest way to get RocksDB to perform well
21   options.IncreaseParallelism();
22   options.OptimizeLevelStyleCompaction();
23   // create the DB if it's not already present
24   options.create_if_missing = true;
25 
26   // open DB
27   Status s = DB::Open(options, kDBPath, &db);
28   assert(s.ok());
29 
30   // Put key-value
31   s = db->Put(WriteOptions(), "key1", "value");
32   assert(s.ok());
33   std::string value;
34   // get value
35   s = db->Get(ReadOptions(), "key1", &value);
36   assert(s.ok());
37   assert(value == "value");
38 
39   // atomically apply a set of updates
40   {
41     WriteBatch batch;
42     batch.Delete("key1");
43     batch.Put("key2", value);
44     s = db->Write(WriteOptions(), &batch);
45   }
46 
47   s = db->Get(ReadOptions(), "key1", &value);
48   assert(s.IsNotFound());
49 
50   db->Get(ReadOptions(), "key2", &value);
51   assert(value == "value");
52 
53   {
54     PinnableSlice pinnable_val;
55     db->Get(ReadOptions(), db->DefaultColumnFamily(), "key2", &pinnable_val);
56     assert(pinnable_val == "value");
57   }
58 
59   {
60     std::string string_val;
61     // If it cannot pin the value, it copies the value to its internal buffer.
62     // The intenral buffer could be set during construction.
63     PinnableSlice pinnable_val(&string_val);
64     db->Get(ReadOptions(), db->DefaultColumnFamily(), "key2", &pinnable_val);
65     assert(pinnable_val == "value");
66     // If the value is not pinned, the internal buffer must have the value.
67     assert(pinnable_val.IsPinned() || string_val == "value");
68   }
69 
70   PinnableSlice pinnable_val;
71   db->Get(ReadOptions(), db->DefaultColumnFamily(), "key1", &pinnable_val);
72   assert(s.IsNotFound());
73   // Reset PinnableSlice after each use and before each reuse
74   pinnable_val.Reset();
75   db->Get(ReadOptions(), db->DefaultColumnFamily(), "key2", &pinnable_val);
76   assert(pinnable_val == "value");
77   pinnable_val.Reset();
78   // The Slice pointed by pinnable_val is not valid after this point
79 
80   delete db;
81 
82   return 0;
83 }
84