1use std::borrow::Borrow;
2
3use redb::{
4 AccessGuard, Key, MultimapRange, MultimapTable, MultimapTableDefinition, MultimapValue, ReadOnlyMultimapTable,
5 ReadOnlyTable, ReadTransaction, ReadableMultimapTable, ReadableTable, Range, Table, TableDefinition, Value,
6 WriteTransaction,
7};
8
9use crate::error::StorageError;
10
11#[derive(Clone, Copy)]
23pub enum Txn<'a> {
24 Write(&'a WriteTransaction),
25 Read(&'a ReadTransaction),
26}
27
28impl<'a> Txn<'a> {
29 pub fn open_table<K: Key + 'static, V: Value + 'static>(
30 &self,
31 def: TableDefinition<K, V>,
32 ) -> Result<TableHandle<'a, K, V>, StorageError> {
33 Ok(match self {
34 Txn::Write(w) => TableHandle::Write(w.open_table(def)?),
35 Txn::Read(r) => TableHandle::Read(r.open_table(def)?),
36 })
37 }
38
39 pub fn open_multimap_table<K: Key + 'static, V: Key + 'static>(
40 &self,
41 def: MultimapTableDefinition<K, V>,
42 ) -> Result<MultimapTableHandle<'a, K, V>, StorageError> {
43 Ok(match self {
44 Txn::Write(w) => MultimapTableHandle::Write(w.open_multimap_table(def)?),
45 Txn::Read(r) => MultimapTableHandle::Read(r.open_multimap_table(def)?),
46 })
47 }
48}
49
50pub enum TableHandle<'a, K: Key + 'static, V: Value + 'static> {
57 Write(Table<'a, K, V>),
58 Read(ReadOnlyTable<K, V>),
59}
60
61impl<'a, K: Key + 'static, V: Value + 'static> TableHandle<'a, K, V> {
62 pub fn get<'k>(&self, key: impl Borrow<K::SelfType<'k>>) -> Result<Option<AccessGuard<'_, V>>, StorageError> {
63 Ok(match self {
64 TableHandle::Write(t) => t.get(key)?,
65 TableHandle::Read(t) => t.get(key)?,
66 })
67 }
68
69 pub fn iter(&self) -> Result<Range<'_, K, V>, StorageError> {
70 Ok(match self {
71 TableHandle::Write(t) => t.iter()?,
72 TableHandle::Read(t) => t.iter()?,
73 })
74 }
75}
76
77pub enum MultimapTableHandle<'a, K: Key + 'static, V: Key + 'static> {
78 Write(MultimapTable<'a, K, V>),
79 Read(ReadOnlyMultimapTable<K, V>),
80}
81
82impl<'a, K: Key + 'static, V: Key + 'static> MultimapTableHandle<'a, K, V> {
83 pub fn get<'k>(&self, key: impl Borrow<K::SelfType<'k>>) -> Result<MultimapValue<'_, V>, StorageError> {
84 Ok(match self {
85 MultimapTableHandle::Write(t) => t.get(key)?,
86 MultimapTableHandle::Read(t) => t.get(key)?,
87 })
88 }
89
90 #[allow(dead_code)] pub fn iter(&self) -> Result<MultimapRange<'_, K, V>, StorageError> {
92 Ok(match self {
93 MultimapTableHandle::Write(t) => t.iter()?,
94 MultimapTableHandle::Read(t) => t.iter()?,
95 })
96 }
97}