simple_example.cc 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. #include <cstdio>
  6. #include <string>
  7. #include "rocksdb/db.h"
  8. #include "rocksdb/slice.h"
  9. #include "rocksdb/options.h"
  10. using namespace ROCKSDB_NAMESPACE;
  11. std::string kDBPath = "/tmp/rocksdb_simple_example";
  12. int main() {
  13. DB* db;
  14. Options options;
  15. // Optimize RocksDB. This is the easiest way to get RocksDB to perform well
  16. options.IncreaseParallelism();
  17. options.OptimizeLevelStyleCompaction();
  18. // create the DB if it's not already present
  19. options.create_if_missing = true;
  20. // open DB
  21. Status s = DB::Open(options, kDBPath, &db);
  22. assert(s.ok());
  23. // Put key-value
  24. s = db->Put(WriteOptions(), "key1", "value");
  25. assert(s.ok());
  26. std::string value;
  27. // get value
  28. s = db->Get(ReadOptions(), "key1", &value);
  29. assert(s.ok());
  30. assert(value == "value");
  31. // atomically apply a set of updates
  32. {
  33. WriteBatch batch;
  34. batch.Delete("key1");
  35. batch.Put("key2", value);
  36. s = db->Write(WriteOptions(), &batch);
  37. }
  38. s = db->Get(ReadOptions(), "key1", &value);
  39. assert(s.IsNotFound());
  40. db->Get(ReadOptions(), "key2", &value);
  41. assert(value == "value");
  42. {
  43. PinnableSlice pinnable_val;
  44. db->Get(ReadOptions(), db->DefaultColumnFamily(), "key2", &pinnable_val);
  45. assert(pinnable_val == "value");
  46. }
  47. {
  48. std::string string_val;
  49. // If it cannot pin the value, it copies the value to its internal buffer.
  50. // The intenral buffer could be set during construction.
  51. PinnableSlice pinnable_val(&string_val);
  52. db->Get(ReadOptions(), db->DefaultColumnFamily(), "key2", &pinnable_val);
  53. assert(pinnable_val == "value");
  54. // If the value is not pinned, the internal buffer must have the value.
  55. assert(pinnable_val.IsPinned() || string_val == "value");
  56. }
  57. PinnableSlice pinnable_val;
  58. db->Get(ReadOptions(), db->DefaultColumnFamily(), "key1", &pinnable_val);
  59. assert(s.IsNotFound());
  60. // Reset PinnableSlice after each use and before each reuse
  61. pinnable_val.Reset();
  62. db->Get(ReadOptions(), db->DefaultColumnFamily(), "key2", &pinnable_val);
  63. assert(pinnable_val == "value");
  64. pinnable_val.Reset();
  65. // The Slice pointed by pinnable_val is not valid after this point
  66. delete db;
  67. return 0;
  68. }