Skip to main content

nimiq_database/mdbx/transaction/
proxy.rs

1use std::ops::Deref;
2
3use super::MdbxReadTransaction;
4use crate::{
5    mdbx::CursorProxy,
6    traits::{DupTable, ReadTransaction, RegularTable, Table},
7};
8
9/// A proxy object that can be either a read or a write transaction.
10/// This can be used to hide the transaction kind generic.
11pub enum TransactionProxy<'db, 'txn>
12where
13    'db: 'txn,
14{
15    Read(&'txn MdbxReadTransaction<'db>),
16    OwnedRead(MdbxReadTransaction<'db>),
17}
18
19impl<'db, 'inner> ReadTransaction<'db> for TransactionProxy<'db, 'inner>
20where
21    'db: 'inner,
22{
23    type Cursor<'txn, T: Table>
24        = CursorProxy<'txn, T>
25    where
26        'inner: 'txn;
27
28    type DupCursor<'txn, T: DupTable>
29        = CursorProxy<'txn, T>
30    where
31        'inner: 'txn;
32
33    fn get<T: Table>(&self, table: &T, key: &T::Key) -> Option<T::Value> {
34        match self {
35            TransactionProxy::Read(txn) => txn.get(table, key),
36            TransactionProxy::OwnedRead(txn) => txn.get(table, key),
37        }
38    }
39
40    fn cursor<'txn, T: RegularTable>(&'txn self, table: &T) -> Self::Cursor<'txn, T> {
41        match self {
42            TransactionProxy::Read(txn) => txn.cursor(table),
43            TransactionProxy::OwnedRead(txn) => txn.cursor(table),
44        }
45    }
46
47    fn dup_cursor<'txn, T: DupTable>(&'txn self, table: &T) -> Self::DupCursor<'txn, T> {
48        match self {
49            TransactionProxy::Read(txn) => txn.dup_cursor(table),
50            TransactionProxy::OwnedRead(txn) => txn.dup_cursor(table),
51        }
52    }
53}
54
55impl<'db, 'inner> Deref for TransactionProxy<'db, 'inner>
56where
57    'db: 'inner,
58{
59    type Target = MdbxReadTransaction<'db>;
60
61    fn deref(&self) -> &Self::Target {
62        match self {
63            TransactionProxy::Read(txn) => txn,
64            TransactionProxy::OwnedRead(txn) => txn,
65        }
66    }
67}
68
69impl<'db, 'inner> AsRef<MdbxReadTransaction<'db>> for TransactionProxy<'db, 'inner>
70where
71    'db: 'inner,
72{
73    fn as_ref(&self) -> &MdbxReadTransaction<'db> {
74        match self {
75            TransactionProxy::Read(txn) => txn,
76            TransactionProxy::OwnedRead(txn) => txn,
77        }
78    }
79}