1
// This file is part of Substrate.
2

            
3
// Copyright (C) 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
//! The main database trait, allowing Substrate to store data persistently.
19

            
20
pub mod error;
21
mod kvdb;
22
mod mem;
23

            
24
pub use crate::kvdb::as_database;
25
pub use mem::MemDb;
26

            
27
/// An identifier for a column.
28
pub type ColumnId = u32;
29

            
30
/// An alteration to the database.
31
#[derive(Clone)]
32
pub enum Change<H> {
33
	Set(ColumnId, Vec<u8>, Vec<u8>),
34
	Remove(ColumnId, Vec<u8>),
35
	Store(ColumnId, H, Vec<u8>),
36
	Reference(ColumnId, H),
37
	Release(ColumnId, H),
38
}
39

            
40
/// A series of changes to the database that can be committed atomically. They do not take effect
41
/// until passed into `Database::commit`.
42
#[derive(Default, Clone)]
43
pub struct Transaction<H>(pub Vec<Change<H>>);
44

            
45
impl<H> Transaction<H> {
46
	/// Create a new transaction to be prepared and committed atomically.
47
	pub fn new() -> Self {
48
		Transaction(Vec::new())
49
	}
50
	/// Set the value of `key` in `col` to `value`, replacing anything that is there currently.
51
	pub fn set(&mut self, col: ColumnId, key: &[u8], value: &[u8]) {
52
		self.0.push(Change::Set(col, key.to_vec(), value.to_vec()))
53
	}
54
	/// Set the value of `key` in `col` to `value`, replacing anything that is there currently.
55
	pub fn set_from_vec(&mut self, col: ColumnId, key: &[u8], value: Vec<u8>) {
56
		self.0.push(Change::Set(col, key.to_vec(), value))
57
	}
58
	/// Remove the value of `key` in `col`.
59
	pub fn remove(&mut self, col: ColumnId, key: &[u8]) {
60
		self.0.push(Change::Remove(col, key.to_vec()))
61
	}
62
	/// Store the `preimage` of `hash` into the database, so that it may be looked up later with
63
	/// `Database::get`. This may be called multiple times, but subsequent
64
	/// calls will ignore `preimage` and simply increase the number of references on `hash`.
65
	pub fn store(&mut self, col: ColumnId, hash: H, preimage: Vec<u8>) {
66
		self.0.push(Change::Store(col, hash, preimage))
67
	}
68
	/// Increase the number of references for `hash` in the database.
69
	pub fn reference(&mut self, col: ColumnId, hash: H) {
70
		self.0.push(Change::Reference(col, hash))
71
	}
72
	/// Release the preimage of `hash` from the database. An equal number of these to the number of
73
	/// corresponding `store`s must have been given before it is legal for `Database::get` to
74
	/// be unable to provide the preimage.
75
	pub fn release(&mut self, col: ColumnId, hash: H) {
76
		self.0.push(Change::Release(col, hash))
77
	}
78
}
79

            
80
pub trait Database<H: Clone + AsRef<[u8]>>: Send + Sync {
81
	/// Commit the `transaction` to the database atomically. Any further calls to `get` or `lookup`
82
	/// will reflect the new state.
83
	fn commit(&self, transaction: Transaction<H>) -> error::Result<()>;
84

            
85
	/// Retrieve the value previously stored against `key` or `None` if
86
	/// `key` is not currently in the database.
87
	fn get(&self, col: ColumnId, key: &[u8]) -> Option<Vec<u8>>;
88

            
89
	/// Check if the value exists in the database without retrieving it.
90
	fn contains(&self, col: ColumnId, key: &[u8]) -> bool {
91
		self.get(col, key).is_some()
92
	}
93

            
94
	/// Check value size in the database possibly without retrieving it.
95
	fn value_size(&self, col: ColumnId, key: &[u8]) -> Option<usize> {
96
		self.get(col, key).map(|v| v.len())
97
	}
98

            
99
	/// Call `f` with the value previously stored against `key`.
100
	///
101
	/// This may be faster than `get` since it doesn't allocate.
102
	/// Use `with_get` helper function if you need `f` to return a value from `f`
103
	fn with_get(&self, col: ColumnId, key: &[u8], f: &mut dyn FnMut(&[u8])) {
104
		if let Some(v) = self.get(col, key) {
105
			f(&v)
106
		}
107
	}
108

            
109
	/// Check if database supports internal ref counting for state data.
110
	///
111
	/// For backwards compatibility returns `false` by default.
112
	fn supports_ref_counting(&self) -> bool {
113
		false
114
	}
115

            
116
	/// Remove a possible path-prefix from the key.
117
	///
118
	/// Not all database implementations use a prefix for keys, so this function may be a noop.
119
	fn sanitize_key(&self, _key: &mut Vec<u8>) {}
120
}
121

            
122
impl<H> std::fmt::Debug for dyn Database<H> {
123
	fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
124
		write!(f, "Database")
125
	}
126
}
127

            
128
/// Call `f` with the value previously stored against `key` and return the result, or `None` if
129
/// `key` is not currently in the database.
130
///
131
/// This may be faster than `get` since it doesn't allocate.
132
pub fn with_get<R, H: Clone + AsRef<[u8]>>(
133
	db: &dyn Database<H>,
134
	col: ColumnId,
135
	key: &[u8],
136
	mut f: impl FnMut(&[u8]) -> R,
137
) -> Option<R> {
138
	let mut result: Option<R> = None;
139
	let mut adapter = |k: &_| {
140
		result = Some(f(k));
141
	};
142
	db.with_get(col, key, &mut adapter);
143
	result
144
}