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 <stdio.h>
7 #include <string.h>
8 #include <stdlib.h>
9 #include <assert.h>
10 
11 #include "rocksdb/c.h"
12 
13 #include <unistd.h>  // sysconf() - get CPU count
14 
15 const char DBPath[] = "/tmp/rocksdb_simple_example";
16 const char DBBackupPath[] = "/tmp/rocksdb_simple_example_backup";
17 
main(int argc,char ** argv)18 int main(int argc, char **argv) {
19   rocksdb_t *db;
20   rocksdb_backup_engine_t *be;
21   rocksdb_options_t *options = rocksdb_options_create();
22   // Optimize RocksDB. This is the easiest way to
23   // get RocksDB to perform well
24   long cpus = sysconf(_SC_NPROCESSORS_ONLN);  // get # of online cores
25   rocksdb_options_increase_parallelism(options, (int)(cpus));
26   rocksdb_options_optimize_level_style_compaction(options, 0);
27   // create the DB if it's not already present
28   rocksdb_options_set_create_if_missing(options, 1);
29 
30   // open DB
31   char *err = NULL;
32   db = rocksdb_open(options, DBPath, &err);
33   assert(!err);
34 
35   // open Backup Engine that we will use for backing up our database
36   be = rocksdb_backup_engine_open(options, DBBackupPath, &err);
37   assert(!err);
38 
39   // Put key-value
40   rocksdb_writeoptions_t *writeoptions = rocksdb_writeoptions_create();
41   const char key[] = "key";
42   const char *value = "value";
43   rocksdb_put(db, writeoptions, key, strlen(key), value, strlen(value) + 1,
44               &err);
45   assert(!err);
46   // Get value
47   rocksdb_readoptions_t *readoptions = rocksdb_readoptions_create();
48   size_t len;
49   char *returned_value =
50       rocksdb_get(db, readoptions, key, strlen(key), &len, &err);
51   assert(!err);
52   assert(strcmp(returned_value, "value") == 0);
53   free(returned_value);
54 
55   // create new backup in a directory specified by DBBackupPath
56   rocksdb_backup_engine_create_new_backup(be, db, &err);
57   assert(!err);
58 
59   rocksdb_close(db);
60 
61   // If something is wrong, you might want to restore data from last backup
62   rocksdb_restore_options_t *restore_options = rocksdb_restore_options_create();
63   rocksdb_backup_engine_restore_db_from_latest_backup(be, DBPath, DBPath,
64                                                       restore_options, &err);
65   assert(!err);
66   rocksdb_restore_options_destroy(restore_options);
67 
68   db = rocksdb_open(options, DBPath, &err);
69   assert(!err);
70 
71   // cleanup
72   rocksdb_writeoptions_destroy(writeoptions);
73   rocksdb_readoptions_destroy(readoptions);
74   rocksdb_options_destroy(options);
75   rocksdb_backup_engine_close(be);
76   rocksdb_close(db);
77 
78   return 0;
79 }
80