1 module rocksdb.batch;
2 
3 import std.string : toStringz;
4 
5 import rocksdb.options,
6        rocksdb.queryable,
7        rocksdb.columnfamily;
8 
9 extern (C) {
10   struct rocksdb_writebatch_t {};
11 
12   rocksdb_writebatch_t* rocksdb_writebatch_create();
13   rocksdb_writebatch_t* rocksdb_writebatch_create_from(const char*, size_t);
14   void rocksdb_writebatch_destroy(rocksdb_writebatch_t*);
15   void rocksdb_writebatch_clear(rocksdb_writebatch_t*);
16   int rocksdb_writebatch_count(rocksdb_writebatch_t*);
17 
18   void rocksdb_writebatch_put(rocksdb_writebatch_t*, const char*, size_t, const char*, size_t);
19   void rocksdb_writebatch_put_cf(rocksdb_writebatch_t*, rocksdb_column_family_handle_t*, const char*, size_t, const char*, size_t);
20 
21   void rocksdb_writebatch_delete(rocksdb_writebatch_t*, const char*, size_t);
22   void rocksdb_writebatch_delete_cf(rocksdb_writebatch_t*, rocksdb_column_family_handle_t*, const char*, size_t);
23 }
24 
25 
26 class WriteBatch {
27   mixin Putable;
28   mixin Removeable;
29 
30   rocksdb_writebatch_t* batch;
31 
32   this() {
33     this.batch = rocksdb_writebatch_create();
34   }
35 
36   this(string frm) {
37     this.batch = rocksdb_writebatch_create_from(toStringz(frm), frm.length);
38   }
39 
40   ~this() {
41     rocksdb_writebatch_destroy(this.batch);
42   }
43 
44   void clear() {
45     rocksdb_writebatch_clear(this.batch);
46   }
47 
48   int count() {
49     return rocksdb_writebatch_count(this.batch);
50   }
51 
52   void putImpl(ubyte[] key, ubyte[] value, ColumnFamily family, WriteOptions opts = null) {
53     assert(opts is null, "WriteBatch cannot use WriteOptions");
54 
55     if (family) {
56       rocksdb_writebatch_put_cf(
57         this.batch,
58         family.cf,
59         cast(char*)key.ptr,
60         key.length,
61         cast(char*)value.ptr,
62         value.length);
63     } else {
64       rocksdb_writebatch_put(
65         this.batch,
66         cast(char*)key.ptr,
67         key.length,
68         cast(char*)value.ptr,
69         value.length);
70     }
71   }
72 
73   void removeImpl(ubyte[] key, ColumnFamily family, WriteOptions opts = null) {
74     assert(opts is null, "WriteBatch cannot use WriteOptions");
75 
76     if (family) {
77       rocksdb_writebatch_delete_cf(
78         this.batch,
79         family.cf,
80         cast(char*)key.ptr,
81         key.length);
82     } else {
83       rocksdb_writebatch_delete(
84         this.batch,
85         cast(char*)key.ptr,
86         key.length);
87     }
88   }
89 }