use std::marker::PhantomData;
use bincode::{Decode, Encode};
use crate::{DbResult, ReadTransaction, ReservedExtensionTableSnafu, WriteTransactionCtx};
pub const EXTENSION_RESERVED_TABLE_PREFIXES: &[&str] = &[
"_total_migration_",
"content_",
"db_",
"events_",
"ids_",
"reception_order_",
"shoutbox_",
"social_",
];
pub struct ExtensionTableDefinition<'a, K, V> {
name: &'a str,
marker: PhantomData<(K, V)>,
}
impl<'a, K, V> ExtensionTableDefinition<'a, K, V> {
pub const fn new(name: &'a str) -> Self {
Self {
name,
marker: PhantomData,
}
}
pub const fn name(&self) -> &'a str {
self.name
}
}
pub struct ExtensionReadTransaction<'a> {
tx: &'a ReadTransaction,
}
impl<'a> ExtensionReadTransaction<'a> {
pub(crate) fn new(tx: &'a ReadTransaction) -> Self {
Self { tx }
}
pub fn open_table<K, V>(
&self,
definition: &ExtensionTableDefinition<'_, K, V>,
) -> DbResult<redb_bincode::ReadOnlyTable<K, V>>
where
K: Encode + Decode<()>,
V: Encode + Decode<()>,
{
ensure_extension_table(definition.name)?;
Ok(self
.tx
.open_table(&redb_bincode::TableDefinition::new(definition.name))?)
}
}
pub struct ExtensionWriteTransaction<'a> {
tx: &'a WriteTransactionCtx,
}
impl<'a> ExtensionWriteTransaction<'a> {
pub(crate) fn new(tx: &'a WriteTransactionCtx) -> Self {
Self { tx }
}
pub fn open_table<K, V>(
&self,
definition: &ExtensionTableDefinition<'_, K, V>,
) -> DbResult<redb_bincode::Table<'_, K, V>>
where
K: Encode + Decode<()>,
V: Encode + Decode<()>,
{
ensure_extension_table(definition.name)?;
Ok(self
.tx
.open_table(&redb_bincode::TableDefinition::new(definition.name))?)
}
}
fn ensure_extension_table(name: &str) -> DbResult<()> {
if is_reserved_extension_table(name) {
return ReservedExtensionTableSnafu {
name: name.to_owned(),
}
.fail();
}
Ok(())
}
pub(crate) fn is_reserved_extension_table(name: &str) -> bool {
name == "events"
|| EXTENSION_RESERVED_TABLE_PREFIXES
.iter()
.any(|prefix| name.starts_with(prefix))
}
#[macro_export]
macro_rules! define_extension_table {
($(#[$outer:meta])*
$name:ident, $persistent_name:literal : $k:ty => $v:ty) => {
#[allow(unused)]
$(#[$outer])*
pub mod $name {
use super::*;
pub type Key = $k;
pub type Value = $v;
pub type Definition<'a> =
$crate::ExtensionTableDefinition<'a, Key, Value>;
pub const TABLE: Definition<'static> =
$crate::ExtensionTableDefinition::new($persistent_name);
}
};
}