ckb_db/
write_batch.rs

1//! RocksDB write batch wrapper
2use crate::db::cf_handle;
3use crate::{Result, internal_error};
4use ckb_db_schema::Col;
5use rocksdb::{OptimisticTransactionDB, WriteBatch};
6use std::sync::Arc;
7
8/// An atomic batch of write operations.
9///
10/// Making an atomic commit of several write operations.
11pub struct RocksDBWriteBatch {
12    pub(crate) db: Arc<OptimisticTransactionDB>,
13    pub(crate) inner: WriteBatch,
14}
15
16impl RocksDBWriteBatch {
17    /// Return the count of write batch.
18    pub fn len(&self) -> usize {
19        self.inner.len()
20    }
21
22    /// Return WriteBatch serialized size (in bytes).
23    pub fn size_in_bytes(&self) -> usize {
24        self.inner.size_in_bytes()
25    }
26
27    /// Returns true if the write batch contains no operations.
28    pub fn is_empty(&self) -> bool {
29        self.inner.is_empty()
30    }
31
32    /// Write the bytes into the given column with associated key.
33    pub fn put(&mut self, col: Col, key: &[u8], value: &[u8]) -> Result<()> {
34        let cf = cf_handle(&self.db, col)?;
35        self.inner.put_cf(cf, key, value).map_err(internal_error)
36    }
37
38    /// Delete the data associated with the given key and given column.
39    pub fn delete(&mut self, col: Col, key: &[u8]) -> Result<()> {
40        let cf = cf_handle(&self.db, col)?;
41        self.inner.delete_cf(cf, key).map_err(internal_error)
42    }
43
44    /// Remove database entries from start key to end key.
45    ///
46    /// Removes the database entries in the range ["begin_key", "end_key"), i.e.,
47    /// including "begin_key" and excluding "end_key". It is not an error if no
48    /// keys exist in the range ["begin_key", "end_key").
49    pub fn delete_range<K: AsRef<[u8]>>(
50        &mut self,
51        col: Col,
52        range: impl Iterator<Item = K>,
53    ) -> Result<()> {
54        let cf = cf_handle(&self.db, col)?;
55
56        for key in range {
57            self.inner
58                .delete_cf(cf, key.as_ref())
59                .map_err(internal_error)?;
60        }
61        Ok(())
62
63        // since 6.18 delete_range_cf
64        // OptimisticTransactionDB now returns error Statuses from calls to DeleteRange() and calls to Write() where the WriteBatch contains a range deletion.
65        // Previously such operations may have succeeded while not providing the expected transactional guarantees.
66    }
67
68    /// Clear all updates buffered in this batch.
69    pub fn clear(&mut self) -> Result<()> {
70        self.inner.clear().map_err(internal_error)
71    }
72}