reth_db_api/
database.rs

1use crate::{
2    table::TableImporter,
3    transaction::{DbTx, DbTxMut},
4    DatabaseError,
5};
6use std::{fmt::Debug, sync::Arc};
7
8/// Main Database trait that can open read-only and read-write transactions.
9///
10/// Sealed trait which cannot be implemented by 3rd parties, exposed only for consumption.
11pub trait Database: Send + Sync + Debug {
12    /// Read-Only database transaction
13    type TX: DbTx + Send + Sync + Debug + 'static;
14    /// Read-Write database transaction
15    type TXMut: DbTxMut + DbTx + TableImporter + Send + Sync + Debug + 'static;
16
17    /// Create read only transaction.
18    #[track_caller]
19    fn tx(&self) -> Result<Self::TX, DatabaseError>;
20
21    /// Create read write transaction only possible if database is open with write access.
22    #[track_caller]
23    fn tx_mut(&self) -> Result<Self::TXMut, DatabaseError>;
24
25    /// Takes a function and passes a read-only transaction into it, making sure it's closed in the
26    /// end of the execution.
27    fn view<T, F>(&self, f: F) -> Result<T, DatabaseError>
28    where
29        F: FnOnce(&Self::TX) -> T,
30    {
31        let tx = self.tx()?;
32
33        let res = f(&tx);
34        tx.commit()?;
35
36        Ok(res)
37    }
38
39    /// Takes a function and passes a write-read transaction into it, making sure it's committed in
40    /// the end of the execution.
41    fn update<T, F>(&self, f: F) -> Result<T, DatabaseError>
42    where
43        F: FnOnce(&Self::TXMut) -> T,
44    {
45        let tx = self.tx_mut()?;
46
47        let res = f(&tx);
48        tx.commit()?;
49
50        Ok(res)
51    }
52}
53
54impl<DB: Database> Database for Arc<DB> {
55    type TX = <DB as Database>::TX;
56    type TXMut = <DB as Database>::TXMut;
57
58    fn tx(&self) -> Result<Self::TX, DatabaseError> {
59        <DB as Database>::tx(self)
60    }
61
62    fn tx_mut(&self) -> Result<Self::TXMut, DatabaseError> {
63        <DB as Database>::tx_mut(self)
64    }
65}
66
67impl<DB: Database> Database for &DB {
68    type TX = <DB as Database>::TX;
69    type TXMut = <DB as Database>::TXMut;
70
71    fn tx(&self) -> Result<Self::TX, DatabaseError> {
72        <DB as Database>::tx(self)
73    }
74
75    fn tx_mut(&self) -> Result<Self::TXMut, DatabaseError> {
76        <DB as Database>::tx_mut(self)
77    }
78}