Skip to main content

nimiq_database/traits/
table.rs

1pub use nimiq_database_value::{AsDatabaseBytes, FromDatabaseBytes};
2
3/// A key in a database table.
4pub trait Key: AsDatabaseBytes + FromDatabaseBytes + Ord + 'static {}
5impl<T: AsDatabaseBytes + FromDatabaseBytes + Ord + 'static> Key for T {}
6/// A value in a database table.
7pub trait Value: AsDatabaseBytes + FromDatabaseBytes + 'static {}
8impl<T: AsDatabaseBytes + FromDatabaseBytes + 'static> Value for T {}
9
10/// Dup(licate key) table values consist of a sub key and an actual value.
11pub trait DupTableValue: Value {
12    /// The subkey type.
13    type SubKey: Key;
14
15    /// The value type.
16    type Value: Value;
17
18    /// Return the subkey value.
19    fn subkey(&self) -> &Self::SubKey;
20
21    /// Return the value.
22    fn value(&self) -> &Self::Value;
23}
24
25/// A database table.
26pub trait Table {
27    /// The name of the table.
28    const NAME: &'static str;
29
30    /// The table's key type.
31    type Key: Key;
32    /// The table's value type.
33    type Value: Value;
34}
35
36/// Regular Key-Value tables.
37pub trait RegularTable: Table {}
38
39/// Dup(licate key) tables allow us to have a subkey.
40pub trait DupTable: Table {}
41
42/// Examples:
43/// - `declare_table!(Test, "test", u32 => u32)` will create a regular table mapping u32 to u32.
44/// - `declare_table!(Test, "test", u32 => u32 => u32)` will create a dup table mapping u32 to a subkey of u32 to a value of u32.
45/// - `declare_table!(Test, "test", u32 => dup(Foo))` will create a dup table mapping u32 to Foo.
46#[macro_export]
47macro_rules! declare_table {
48    // Basic struct, this is not to be used directly.
49    ($typ:ident, $name:expr, $key:ty, $value:ty) => {
50        #[derive(Clone, Debug, Default)]
51        pub struct $typ;
52        impl $crate::traits::Table for $typ {
53            const NAME: &'static str = $name;
54            type Key = $key;
55            type Value = $value;
56        }
57    };
58    // Dup table.
59    ($typ:ident, $name:expr, $key:ty => dup($value:ty)) => {
60        $crate::declare_table!($typ, $name, $key, $value);
61        impl $crate::traits::DupTable for $typ {}
62    };
63    // Regular table.
64    ($typ:ident, $name:expr, $key:ty => $value:ty) => {
65        $crate::declare_table!($typ, $name, $key, $value);
66        impl $crate::traits::RegularTable for $typ {}
67    };
68    // Indexed table.
69    ($typ:ident, $name:expr, $key:ty => $subkey:ty => $value:ty) => {
70        $crate::declare_table!($typ, $name, $key, $crate::utils::IndexedValue<$subkey, $value>);
71        impl $crate::traits::DupTable for $typ {}
72    };
73}