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 <vector>
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_column_families_example";
16 
main()17 int main() {
18   // open DB
19   Options options;
20   options.create_if_missing = true;
21   DB* db;
22   Status s = DB::Open(options, kDBPath, &db);
23   assert(s.ok());
24 
25   // create column family
26   ColumnFamilyHandle* cf;
27   s = db->CreateColumnFamily(ColumnFamilyOptions(), "new_cf", &cf);
28   assert(s.ok());
29 
30   // close DB
31   s = db->DestroyColumnFamilyHandle(cf);
32   assert(s.ok());
33   delete db;
34 
35   // open DB with two column families
36   std::vector<ColumnFamilyDescriptor> column_families;
37   // have to open default column family
38   column_families.push_back(ColumnFamilyDescriptor(
39       kDefaultColumnFamilyName, ColumnFamilyOptions()));
40   // open the new one, too
41   column_families.push_back(ColumnFamilyDescriptor(
42       "new_cf", ColumnFamilyOptions()));
43   std::vector<ColumnFamilyHandle*> handles;
44   s = DB::Open(DBOptions(), kDBPath, column_families, &handles, &db);
45   assert(s.ok());
46 
47   // put and get from non-default column family
48   s = db->Put(WriteOptions(), handles[1], Slice("key"), Slice("value"));
49   assert(s.ok());
50   std::string value;
51   s = db->Get(ReadOptions(), handles[1], Slice("key"), &value);
52   assert(s.ok());
53 
54   // atomic write
55   WriteBatch batch;
56   batch.Put(handles[0], Slice("key2"), Slice("value2"));
57   batch.Put(handles[1], Slice("key3"), Slice("value3"));
58   batch.Delete(handles[0], Slice("key"));
59   s = db->Write(WriteOptions(), &batch);
60   assert(s.ok());
61 
62   // drop column family
63   s = db->DropColumnFamily(handles[1]);
64   assert(s.ok());
65 
66   // close db
67   for (auto handle : handles) {
68     s = db->DestroyColumnFamilyHandle(handle);
69     assert(s.ok());
70   }
71   delete db;
72 
73   return 0;
74 }
75