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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
pub use kvdb::{DBTransaction, DBValue, KeyValueDB};
pub trait Database: KeyValueDB {
fn is_indexed_column(&self, col: u32) -> bool;
}
pub mod kvdb_impl {
use super::{DBTransaction, DBValue, Database, KeyValueDB};
use kvdb::{DBOp, IoStats, IoStatsKind};
use parity_util_mem::{MallocSizeOf, MallocSizeOfOps};
use std::{collections::BTreeSet, io::Result};
#[derive(Clone)]
pub struct DbAdapter<D> {
db: D,
indexed_columns: BTreeSet<u32>,
}
impl<D: KeyValueDB> DbAdapter<D> {
pub fn new(db: D, indexed_columns: &[u32]) -> Self {
DbAdapter { db, indexed_columns: indexed_columns.iter().cloned().collect() }
}
fn ensure_is_indexed(&self, col: u32) {
debug_assert!(
self.is_indexed_column(col),
"Invalid configuration of database, column {} is not ordered.",
col
);
}
fn ensure_ops_indexing(&self, transaction: &DBTransaction) {
debug_assert!({
let mut pass = true;
for op in &transaction.ops {
if let DBOp::DeletePrefix { col, .. } = op {
if !self.is_indexed_column(*col) {
pass = false;
break
}
}
}
pass
})
}
}
impl<D: KeyValueDB> Database for DbAdapter<D> {
fn is_indexed_column(&self, col: u32) -> bool {
self.indexed_columns.contains(&col)
}
}
impl<D: KeyValueDB> KeyValueDB for DbAdapter<D> {
fn transaction(&self) -> DBTransaction {
self.db.transaction()
}
fn get(&self, col: u32, key: &[u8]) -> Result<Option<DBValue>> {
self.db.get(col, key)
}
fn get_by_prefix(&self, col: u32, prefix: &[u8]) -> Option<Box<[u8]>> {
self.ensure_is_indexed(col);
self.db.get_by_prefix(col, prefix)
}
fn write(&self, transaction: DBTransaction) -> Result<()> {
self.ensure_ops_indexing(&transaction);
self.db.write(transaction)
}
fn iter<'a>(&'a self, col: u32) -> Box<dyn Iterator<Item = (Box<[u8]>, Box<[u8]>)> + 'a> {
self.ensure_is_indexed(col);
self.db.iter(col)
}
fn iter_with_prefix<'a>(
&'a self,
col: u32,
prefix: &'a [u8],
) -> Box<dyn Iterator<Item = (Box<[u8]>, Box<[u8]>)> + 'a> {
self.ensure_is_indexed(col);
self.db.iter_with_prefix(col, prefix)
}
fn restore(&self, _new_db: &str) -> Result<()> {
unimplemented!("restore is unsupported")
}
fn io_stats(&self, kind: IoStatsKind) -> IoStats {
self.db.io_stats(kind)
}
fn has_key(&self, col: u32, key: &[u8]) -> Result<bool> {
self.db.has_key(col, key)
}
fn has_prefix(&self, col: u32, prefix: &[u8]) -> bool {
self.ensure_is_indexed(col);
self.db.has_prefix(col, prefix)
}
}
impl<D: KeyValueDB> MallocSizeOf for DbAdapter<D> {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
self.db.size_of(ops)
}
}
}
pub mod paritydb_impl {
use super::{DBTransaction, DBValue, Database, KeyValueDB};
use kvdb::{DBOp, IoStats, IoStatsKind};
use parity_db::Db;
use parking_lot::Mutex;
use std::{collections::BTreeSet, io::Result, sync::Arc};
fn handle_err<T>(result: parity_db::Result<T>) -> T {
match result {
Ok(r) => r,
Err(e) => {
panic!("Critical database error: {:?}", e);
},
}
}
fn map_err<T>(result: parity_db::Result<T>) -> Result<T> {
result.map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, format!("{:?}", e)))
}
pub struct DbAdapter {
db: Db,
indexed_columns: BTreeSet<u32>,
write_lock: Arc<Mutex<()>>,
}
impl parity_util_mem::MallocSizeOf for DbAdapter {
fn size_of(&self, _ops: &mut parity_util_mem::MallocSizeOfOps) -> usize {
unimplemented!("size_of is not supported for parity_db")
}
}
impl KeyValueDB for DbAdapter {
fn transaction(&self) -> DBTransaction {
DBTransaction::new()
}
fn get(&self, col: u32, key: &[u8]) -> Result<Option<DBValue>> {
map_err(self.db.get(col as u8, key))
}
fn get_by_prefix(&self, col: u32, prefix: &[u8]) -> Option<Box<[u8]>> {
self.iter_with_prefix(col, prefix).next().map(|(_, v)| v)
}
fn iter<'a>(&'a self, col: u32) -> Box<dyn Iterator<Item = (Box<[u8]>, Box<[u8]>)> + 'a> {
let mut iter = handle_err(self.db.iter(col as u8));
Box::new(std::iter::from_fn(move || {
if let Some((key, value)) = handle_err(iter.next()) {
Some((key.into_boxed_slice(), value.into_boxed_slice()))
} else {
None
}
}))
}
fn iter_with_prefix<'a>(
&'a self,
col: u32,
prefix: &'a [u8],
) -> Box<dyn Iterator<Item = (Box<[u8]>, Box<[u8]>)> + 'a> {
if prefix.len() == 0 {
return self.iter(col)
}
let mut iter = handle_err(self.db.iter(col as u8));
handle_err(iter.seek(prefix));
Box::new(std::iter::from_fn(move || {
if let Some((key, value)) = handle_err(iter.next()) {
key.starts_with(prefix)
.then(|| (key.into_boxed_slice(), value.into_boxed_slice()))
} else {
None
}
}))
}
fn restore(&self, _new_db: &str) -> Result<()> {
unimplemented!("restore is unsupported")
}
fn io_stats(&self, _kind: IoStatsKind) -> IoStats {
unimplemented!("io_stats not supported by parity_db");
}
fn has_key(&self, col: u32, key: &[u8]) -> Result<bool> {
map_err(self.db.get_size(col as u8, key).map(|r| r.is_some()))
}
fn has_prefix(&self, col: u32, prefix: &[u8]) -> bool {
self.get_by_prefix(col, prefix).is_some()
}
fn write(&self, transaction: DBTransaction) -> std::io::Result<()> {
let mut ops = transaction.ops.into_iter();
let mut current_prefix_iter: Option<(parity_db::BTreeIterator, u8, Vec<u8>)> = None;
let current_prefix_iter = &mut current_prefix_iter;
let transaction = std::iter::from_fn(move || loop {
if let Some((prefix_iter, col, prefix)) = current_prefix_iter {
if let Some((key, _value)) = handle_err(prefix_iter.next()) {
if key.starts_with(prefix) {
return Some((*col, key.to_vec(), None))
}
}
*current_prefix_iter = None;
}
return match ops.next() {
None => None,
Some(DBOp::Insert { col, key, value }) =>
Some((col as u8, key.to_vec(), Some(value))),
Some(DBOp::Delete { col, key }) => Some((col as u8, key.to_vec(), None)),
Some(DBOp::DeletePrefix { col, prefix }) => {
let col = col as u8;
let mut iter = handle_err(self.db.iter(col));
handle_err(iter.seek(&prefix[..]));
*current_prefix_iter = Some((iter, col, prefix.to_vec()));
continue
},
}
});
let _lock = self.write_lock.lock();
map_err(self.db.commit(transaction))
}
}
impl Database for DbAdapter {
fn is_indexed_column(&self, col: u32) -> bool {
self.indexed_columns.contains(&col)
}
}
impl DbAdapter {
pub fn new(db: Db, indexed_columns: &[u32]) -> Self {
let write_lock = Arc::new(Mutex::new(()));
DbAdapter { db, indexed_columns: indexed_columns.iter().cloned().collect(), write_lock }
}
}
#[cfg(test)]
mod tests {
use super::*;
use kvdb_shared_tests as st;
use std::io;
use tempfile::Builder as TempfileBuilder;
fn create(num_col: u32) -> io::Result<(DbAdapter, tempfile::TempDir)> {
let tempdir = TempfileBuilder::new().prefix("").tempdir()?;
let mut options = parity_db::Options::with_columns(tempdir.path(), num_col as u8);
for i in 0..num_col {
options.columns[i as usize].btree_index = true;
}
let db = parity_db::Db::open_or_create(&options)
.map_err(|err| io::Error::new(io::ErrorKind::Other, format!("{:?}", err)))?;
let db = DbAdapter::new(db, &[0]);
Ok((db, tempdir))
}
#[test]
fn put_and_get() -> io::Result<()> {
let (db, _temp_file) = create(1)?;
st::test_put_and_get(&db)
}
#[test]
fn delete_and_get() -> io::Result<()> {
let (db, _temp_file) = create(1)?;
st::test_delete_and_get(&db)
}
#[test]
fn delete_prefix() -> io::Result<()> {
let (db, _temp_file) = create(st::DELETE_PREFIX_NUM_COLUMNS)?;
st::test_delete_prefix(&db)
}
#[test]
fn iter() -> io::Result<()> {
let (db, _temp_file) = create(1)?;
st::test_iter(&db)
}
#[test]
fn iter_with_prefix() -> io::Result<()> {
let (db, _temp_file) = create(1)?;
st::test_iter_with_prefix(&db)
}
#[test]
fn complex() -> io::Result<()> {
let (db, _temp_file) = create(1)?;
st::test_complex(&db)
}
}
}