reth_cli_commands/db/
mod.rs1use 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::io::{self, Write};
8
9mod checksum;
10mod clear;
11mod diff;
12mod get;
13mod list;
14mod stats;
15mod tui;
17
18#[derive(Debug, Parser)]
20pub struct Command<C: ChainSpecParser> {
21 #[command(flatten)]
22 env: EnvironmentArgs<C>,
23
24 #[command(subcommand)]
25 command: Subcommands,
26}
27
28#[derive(Subcommand, Debug)]
29pub enum Subcommands {
31 Stats(stats::Command),
33 List(list::Command),
35 Checksum(checksum::Command),
37 Diff(diff::Command),
39 Get(get::Command),
41 Drop {
43 #[arg(short, long)]
45 force: bool,
46 },
47 Clear(clear::Command),
49 Version,
51 Path,
53}
54
55macro_rules! db_ro_exec {
57 ($env:expr, $tool:ident, $N:ident, $command:block) => {
58 let Environment { provider_factory, .. } = $env.init::<$N>(AccessRights::RO)?;
59
60 let $tool = DbTool::new(provider_factory.clone())?;
61 $command;
62 };
63}
64
65impl<C: ChainSpecParser<ChainSpec: EthChainSpec + EthereumHardforks>> Command<C> {
66 pub async fn execute<N: CliNodeTypes<ChainSpec = C::ChainSpec>>(self) -> eyre::Result<()> {
68 let data_dir = self.env.datadir.clone().resolve_datadir(self.env.chain.chain());
69 let db_path = data_dir.db();
70 let static_files_path = data_dir.static_files();
71
72 eyre::ensure!(
74 data_dir.data_dir().is_dir(),
75 "Datadir does not exist: {:?}",
76 data_dir.data_dir()
77 );
78
79 eyre::ensure!(db_path.is_dir(), "Database does not exist: {:?}", db_path);
81
82 match self.command {
83 Subcommands::Stats(command) => {
85 db_ro_exec!(self.env, tool, N, {
86 command.execute(data_dir, &tool)?;
87 });
88 }
89 Subcommands::List(command) => {
90 db_ro_exec!(self.env, tool, N, {
91 command.execute(&tool)?;
92 });
93 }
94 Subcommands::Checksum(command) => {
95 db_ro_exec!(self.env, tool, N, {
96 command.execute(&tool)?;
97 });
98 }
99 Subcommands::Diff(command) => {
100 db_ro_exec!(self.env, tool, N, {
101 command.execute(&tool)?;
102 });
103 }
104 Subcommands::Get(command) => {
105 db_ro_exec!(self.env, tool, N, {
106 command.execute(&tool)?;
107 });
108 }
109 Subcommands::Drop { force } => {
110 if !force {
111 print!("Are you sure you want to drop the database at {data_dir}? This cannot be undone. (y/N): ");
113 io::stdout().flush().unwrap();
115
116 let mut input = String::new();
117 io::stdin().read_line(&mut input).expect("Failed to read line");
118
119 if !input.trim().eq_ignore_ascii_case("y") {
120 println!("Database drop aborted!");
121 return Ok(())
122 }
123 }
124
125 let Environment { provider_factory, .. } = self.env.init::<N>(AccessRights::RW)?;
126 let tool = DbTool::new(provider_factory)?;
127 tool.drop(db_path, static_files_path)?;
128 }
129 Subcommands::Clear(command) => {
130 let Environment { provider_factory, .. } = self.env.init::<N>(AccessRights::RW)?;
131 command.execute(provider_factory)?;
132 }
133 Subcommands::Version => {
134 let local_db_version = match get_db_version(&db_path) {
135 Ok(version) => Some(version),
136 Err(DatabaseVersionError::MissingFile) => None,
137 Err(err) => return Err(err.into()),
138 };
139
140 println!("Current database version: {DB_VERSION}");
141
142 if let Some(version) = local_db_version {
143 println!("Local database version: {version}");
144 } else {
145 println!("Local database is uninitialized");
146 }
147 }
148 Subcommands::Path => {
149 println!("{}", db_path.display());
150 }
151 }
152
153 Ok(())
154 }
155}
156
157#[cfg(test)]
158mod tests {
159 use super::*;
160 use reth_ethereum_cli::chainspec::{EthereumChainSpecParser, SUPPORTED_CHAINS};
161 use std::path::Path;
162
163 #[test]
164 fn parse_stats_globals() {
165 let path = format!("../{}", SUPPORTED_CHAINS[0]);
166 let cmd = Command::<EthereumChainSpecParser>::try_parse_from([
167 "reth",
168 "--datadir",
169 &path,
170 "stats",
171 ])
172 .unwrap();
173 assert_eq!(cmd.env.datadir.resolve_datadir(cmd.env.chain.chain).as_ref(), Path::new(&path));
174 }
175}