reth_cli_commands/db/
mod.rs

1use crate::common::{AccessRights, CliNodeTypes, Environment, EnvironmentArgs};
2use clap::{Parser, Subcommand};
3use reth_chainspec::{EthChainSpec, EthereumHardforks};
4use reth_cli::chainspec::ChainSpecParser;
5use reth_db::version::{get_db_version, DatabaseVersionError, DB_VERSION};
6use reth_db_common::DbTool;
7use std::{
8    io::{self, Write},
9    sync::Arc,
10};
11mod checksum;
12mod clear;
13mod diff;
14mod get;
15mod list;
16mod stats;
17/// DB List TUI
18mod tui;
19
20/// `reth db` command
21#[derive(Debug, Parser)]
22pub struct Command<C: ChainSpecParser> {
23    #[command(flatten)]
24    env: EnvironmentArgs<C>,
25
26    #[command(subcommand)]
27    command: Subcommands,
28}
29
30#[derive(Subcommand, Debug)]
31/// `reth db` subcommands
32pub enum Subcommands {
33    /// Lists all the tables, their entry count and their size
34    Stats(stats::Command),
35    /// Lists the contents of a table
36    List(list::Command),
37    /// Calculates the content checksum of a table
38    Checksum(checksum::Command),
39    /// Create a diff between two database tables or two entire databases.
40    Diff(diff::Command),
41    /// Gets the content of a table for the given key
42    Get(get::Command),
43    /// Deletes all database entries
44    Drop {
45        /// Bypasses the interactive confirmation and drops the database directly
46        #[arg(short, long)]
47        force: bool,
48    },
49    /// Deletes all table entries
50    Clear(clear::Command),
51    /// Lists current and local database versions
52    Version,
53    /// Returns the full database path
54    Path,
55}
56
57/// `db_ro_exec` opens a database in read-only mode, and then execute with the provided command
58macro_rules! db_ro_exec {
59    ($env:expr, $tool:ident, $N:ident, $command:block) => {
60        let Environment { provider_factory, .. } = $env.init::<$N>(AccessRights::RO)?;
61
62        let $tool = DbTool::new(provider_factory.clone())?;
63        $command;
64    };
65}
66
67impl<C: ChainSpecParser<ChainSpec: EthChainSpec + EthereumHardforks>> Command<C> {
68    /// Execute `db` command
69    pub async fn execute<N: CliNodeTypes<ChainSpec = C::ChainSpec>>(self) -> eyre::Result<()> {
70        let data_dir = self.env.datadir.clone().resolve_datadir(self.env.chain.chain());
71        let db_path = data_dir.db();
72        let static_files_path = data_dir.static_files();
73        let exex_wal_path = data_dir.exex_wal();
74
75        // ensure the provided datadir exist
76        eyre::ensure!(
77            data_dir.data_dir().is_dir(),
78            "Datadir does not exist: {:?}",
79            data_dir.data_dir()
80        );
81
82        // ensure the provided database exist
83        eyre::ensure!(db_path.is_dir(), "Database does not exist: {:?}", db_path);
84
85        match self.command {
86            // TODO: We'll need to add this on the DB trait.
87            Subcommands::Stats(command) => {
88                db_ro_exec!(self.env, tool, N, {
89                    command.execute(data_dir, &tool)?;
90                });
91            }
92            Subcommands::List(command) => {
93                db_ro_exec!(self.env, tool, N, {
94                    command.execute(&tool)?;
95                });
96            }
97            Subcommands::Checksum(command) => {
98                db_ro_exec!(self.env, tool, N, {
99                    command.execute(&tool)?;
100                });
101            }
102            Subcommands::Diff(command) => {
103                db_ro_exec!(self.env, tool, N, {
104                    command.execute(&tool)?;
105                });
106            }
107            Subcommands::Get(command) => {
108                db_ro_exec!(self.env, tool, N, {
109                    command.execute(&tool)?;
110                });
111            }
112            Subcommands::Drop { force } => {
113                if !force {
114                    // Ask for confirmation
115                    print!("Are you sure you want to drop the database at {data_dir}? This cannot be undone. (y/N): ");
116                    // Flush the buffer to ensure the message is printed immediately
117                    io::stdout().flush().unwrap();
118
119                    let mut input = String::new();
120                    io::stdin().read_line(&mut input).expect("Failed to read line");
121
122                    if !input.trim().eq_ignore_ascii_case("y") {
123                        println!("Database drop aborted!");
124                        return Ok(())
125                    }
126                }
127
128                let Environment { provider_factory, .. } = self.env.init::<N>(AccessRights::RW)?;
129                let tool = DbTool::new(provider_factory)?;
130                tool.drop(db_path, static_files_path, exex_wal_path)?;
131            }
132            Subcommands::Clear(command) => {
133                let Environment { provider_factory, .. } = self.env.init::<N>(AccessRights::RW)?;
134                command.execute(provider_factory)?;
135            }
136            Subcommands::Version => {
137                let local_db_version = match get_db_version(&db_path) {
138                    Ok(version) => Some(version),
139                    Err(DatabaseVersionError::MissingFile) => None,
140                    Err(err) => return Err(err.into()),
141                };
142
143                println!("Current database version: {DB_VERSION}");
144
145                if let Some(version) = local_db_version {
146                    println!("Local database version: {version}");
147                } else {
148                    println!("Local database is uninitialized");
149                }
150            }
151            Subcommands::Path => {
152                println!("{}", db_path.display());
153            }
154        }
155
156        Ok(())
157    }
158
159    /// Returns the underlying chain being used to run this command
160    pub fn chain_spec(&self) -> Option<&Arc<C::ChainSpec>> {
161        Some(&self.env.chain)
162    }
163}
164
165#[cfg(test)]
166mod tests {
167    use super::*;
168    use reth_ethereum_cli::chainspec::{EthereumChainSpecParser, SUPPORTED_CHAINS};
169    use std::path::Path;
170
171    #[test]
172    fn parse_stats_globals() {
173        let path = format!("../{}", SUPPORTED_CHAINS[0]);
174        let cmd = Command::<EthereumChainSpecParser>::try_parse_from([
175            "reth",
176            "--datadir",
177            &path,
178            "stats",
179        ])
180        .unwrap();
181        assert_eq!(cmd.env.datadir.resolve_datadir(cmd.env.chain.chain).as_ref(), Path::new(&path));
182    }
183}