feat(db): initialize db with tables (#13130)

Co-authored-by: Matthias Seitz <matthias.seitz@outlook.de>
This commit is contained in:
Alessandro Mazza
2024-12-06 17:24:54 +01:00
committed by GitHub
parent 806a1b1e88
commit 627ceae86b
3 changed files with 34 additions and 20 deletions

View File

@ -3,9 +3,9 @@
use crate::{
lockfile::StorageLock,
metrics::DatabaseEnvMetrics,
tables::{self, TableType, Tables},
tables::{self, Tables},
utils::default_page_size,
DatabaseError,
DatabaseError, TableSet,
};
use eyre::Context;
use metrics::{gauge, Label};
@ -444,15 +444,18 @@ impl DatabaseEnv {
self
}
/// Creates all the defined tables, if necessary.
/// Creates all the tables defined in [`Tables`], if necessary.
pub fn create_tables(&self) -> Result<(), DatabaseError> {
self.create_tables_for::<Tables>()
}
/// Creates all the tables defined in the given [`TableSet`], if necessary.
pub fn create_tables_for<TS: TableSet>(&self) -> Result<(), DatabaseError> {
let tx = self.inner.begin_rw_txn().map_err(|e| DatabaseError::InitTx(e.into()))?;
for table in Tables::ALL {
let flags = match table.table_type() {
TableType::Table => DatabaseFlags::default(),
TableType::DupSort => DatabaseFlags::DUP_SORT,
};
for table in TS::tables() {
let flags =
if table.is_dupsort() { DatabaseFlags::DUP_SORT } else { DatabaseFlags::default() };
tx.create_db(Some(table.name()), flags)
.map_err(|e| DatabaseError::CreateTable(e.into()))?;

View File

@ -29,7 +29,7 @@ use reth_db_api::{
AccountBeforeTx, ClientVersion, CompactU256, IntegerList, ShardedKey,
StoredBlockBodyIndices, StoredBlockWithdrawals,
},
table::{Decode, DupSort, Encode, Table},
table::{Decode, DupSort, Encode, Table, TableInfo},
};
use reth_primitives::{Receipt, StorageEntry, TransactionSigned};
use reth_primitives_traits::{Account, Bytecode};
@ -101,10 +101,8 @@ pub trait TableViewer<R> {
/// General trait for defining the set of tables
/// Used to initialize database
pub trait TableSet {
/// Returns all the table names in the database.
fn table_names(&self) -> Vec<&'static str>;
/// Returns `true` if the table at the given index is a `DUPSORT` table.
fn is_dupsort(&self, idx: usize) -> bool;
/// Returns an iterator over the tables
fn tables() -> Box<dyn Iterator<Item = Box<dyn TableInfo>>>;
}
/// Defines all the tables in the database.
@ -252,15 +250,19 @@ macro_rules! tables {
}
}
impl TableSet for Tables {
fn table_names(&self) -> Vec<&'static str> {
//vec![$(table_names::$name,)*]
Self::ALL.iter().map(|t| t.name()).collect()
impl TableInfo for Tables {
fn name(&self) -> &'static str {
self.name()
}
fn is_dupsort(&self, idx: usize) -> bool {
let table: Self = self.table_names()[idx].parse().expect("should be valid table name");
table.is_dupsort()
fn is_dupsort(&self) -> bool {
self.is_dupsort()
}
}
impl TableSet for Tables {
fn tables() -> Box<dyn Iterator<Item = Box<dyn TableInfo>>> {
Box::new(Self::ALL.iter().map(|table| Box::new(*table) as Box<dyn TableInfo>))
}
}