tetcore_database/
tetsy_kvdb.rs

1// This file is part of Tetcore.
2
3// Copyright (C) 2017-2021 Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18/// A wrapper around `tetsy_kvdb::Database` that implements `tetcore_database::Database` trait
19
20use ::tetsy_kvdb::{DBTransaction, KeyValueDB};
21
22use crate::{Database, Change, ColumnId, Transaction, error};
23
24struct DbAdapter<D: KeyValueDB + 'static>(D);
25
26fn handle_err<T>(result: std::io::Result<T>) -> T {
27	match result {
28		Ok(r) => r,
29		Err(e) =>  {
30			panic!("Critical database error: {:?}", e);
31		}
32	}
33}
34
35/// Wrap RocksDb database into a trait object that implements `tetcore_database::Database`
36pub fn as_database<D: KeyValueDB + 'static, H: Clone>(db: D) -> std::sync::Arc<dyn Database<H>> {
37	std::sync::Arc::new(DbAdapter(db))
38}
39
40impl<D: KeyValueDB, H: Clone> Database<H> for DbAdapter<D> {
41	fn commit(&self, transaction: Transaction<H>) -> error::Result<()> {
42		let mut tx = DBTransaction::new();
43		for change in transaction.0.into_iter() {
44			match change {
45				Change::Set(col, key, value) => tx.put_vec(col, &key, value),
46				Change::Remove(col, key) => tx.delete(col, &key),
47				_ => unimplemented!(),
48			}
49		}
50		self.0.write(tx).map_err(|e| error::DatabaseError(Box::new(e)))
51	}
52
53	fn get(&self, col: ColumnId, key: &[u8]) -> Option<Vec<u8>> {
54		handle_err(self.0.get(col, key))
55	}
56
57	fn lookup(&self, _hash: &H) -> Option<Vec<u8>> {
58		unimplemented!();
59	}
60}