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
use crate::{
columns, light,
utils::{DatabaseType, NUM_COLUMNS},
};
use sp_database::{error::DatabaseError, Change, ColumnId, Database, Transaction};
struct DbAdapter(parity_db::Db);
fn handle_err<T>(result: parity_db::Result<T>) -> T {
match result {
Ok(r) => r,
Err(e) => {
panic!("Critical database error: {:?}", e);
},
}
}
pub fn open<H: Clone + AsRef<[u8]>>(
path: &std::path::Path,
db_type: DatabaseType,
create: bool,
) -> parity_db::Result<std::sync::Arc<dyn Database<H>>> {
let mut config = parity_db::Options::with_columns(path, NUM_COLUMNS as u8);
match db_type {
DatabaseType::Full => {
let indexes = [
columns::STATE,
columns::HEADER,
columns::BODY,
columns::TRANSACTION,
columns::JUSTIFICATIONS,
];
for i in indexes {
let mut column = &mut config.columns[i as usize];
column.compression = parity_db::CompressionType::Lz4;
}
let mut state_col = &mut config.columns[columns::STATE as usize];
state_col.ref_counted = true;
state_col.preimage = true;
state_col.uniform = true;
},
DatabaseType::Light => {
config.columns[light::columns::HEADER as usize].compression =
parity_db::CompressionType::Lz4;
},
}
let db = if create {
parity_db::Db::open_or_create(&config)?
} else {
parity_db::Db::open(&config)?
};
Ok(std::sync::Arc::new(DbAdapter(db)))
}
impl<H: Clone + AsRef<[u8]>> Database<H> for DbAdapter {
fn commit(&self, transaction: Transaction<H>) -> Result<(), DatabaseError> {
handle_err(self.0.commit(transaction.0.into_iter().map(|change| match change {
Change::Set(col, key, value) => (col as u8, key, Some(value)),
Change::Remove(col, key) => (col as u8, key, None),
_ => unimplemented!(),
})));
Ok(())
}
fn get(&self, col: ColumnId, key: &[u8]) -> Option<Vec<u8>> {
handle_err(self.0.get(col as u8, key))
}
fn contains(&self, col: ColumnId, key: &[u8]) -> bool {
handle_err(self.0.get_size(col as u8, key)).is_some()
}
fn value_size(&self, col: ColumnId, key: &[u8]) -> Option<usize> {
handle_err(self.0.get_size(col as u8, key)).map(|s| s as usize)
}
fn supports_ref_counting(&self) -> bool {
true
}
}