Skip to main content

reth_db_api/
database.rs

1use crate::{
2    table::TableImporter,
3    transaction::{DbTx, DbTxMut},
4    DatabaseError,
5};
6use std::{fmt::Debug, path::PathBuf, 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    /// Returns the path to the database directory.
26    fn path(&self) -> PathBuf;
27
28    /// Takes a function and passes a read-only transaction into it, making sure it's closed in the
29    /// end of the execution.
30    fn view<T, F>(&self, f: F) -> Result<T, DatabaseError>
31    where
32        F: FnOnce(&mut Self::TX) -> T,
33    {
34        let mut tx = self.tx()?;
35
36        let res = f(&mut tx);
37        tx.commit()?;
38
39        Ok(res)
40    }
41
42    /// Takes a function and passes a write-read transaction into it, making sure it's committed in
43    /// the end of the execution.
44    fn update<T, F>(&self, f: F) -> Result<T, DatabaseError>
45    where
46        F: FnOnce(&Self::TXMut) -> T,
47    {
48        let tx = self.tx_mut()?;
49
50        let res = f(&tx);
51        tx.commit()?;
52
53        Ok(res)
54    }
55}
56
57impl<DB: Database> Database for Arc<DB> {
58    type TX = <DB as Database>::TX;
59    type TXMut = <DB as Database>::TXMut;
60
61    fn tx(&self) -> Result<Self::TX, DatabaseError> {
62        <DB as Database>::tx(self)
63    }
64
65    fn tx_mut(&self) -> Result<Self::TXMut, DatabaseError> {
66        <DB as Database>::tx_mut(self)
67    }
68
69    fn path(&self) -> PathBuf {
70        <DB as Database>::path(self)
71    }
72}
73
74impl<DB: Database> Database for &DB {
75    type TX = <DB as Database>::TX;
76    type TXMut = <DB as Database>::TXMut;
77
78    fn tx(&self) -> Result<Self::TX, DatabaseError> {
79        <DB as Database>::tx(self)
80    }
81
82    fn tx_mut(&self) -> Result<Self::TXMut, DatabaseError> {
83        <DB as Database>::tx_mut(self)
84    }
85
86    fn path(&self) -> PathBuf {
87        <DB as Database>::path(self)
88    }
89}