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