Skip to main content

sql_splitter/analyzer/
mod.rs

1//! SQL dump analyzer for gathering per-table statistics.
2
3use crate::parser::{determine_buffer_size, Parser, SqlDialect, StatementType};
4use crate::splitter::open_input_opt_progress;
5use ahash::AHashMap;
6use serde::Serialize;
7use std::io::Read;
8use std::path::PathBuf;
9
10/// Per-table statistics gathered during analysis.
11#[derive(Debug, Clone, Serialize)]
12pub struct TableStats {
13    /// Name of the table.
14    pub table_name: String,
15    /// Number of INSERT (or COPY) statements for this table.
16    pub insert_count: u64,
17    /// Number of CREATE TABLE statements for this table.
18    pub create_count: u64,
19    /// Total bytes of all statements for this table.
20    pub total_bytes: u64,
21    /// Total number of statements for this table.
22    pub statement_count: u64,
23}
24
25impl TableStats {
26    fn new(table_name: String) -> Self {
27        Self {
28            table_name,
29            insert_count: 0,
30            create_count: 0,
31            total_bytes: 0,
32            statement_count: 0,
33        }
34    }
35}
36
37/// Streaming SQL dump analyzer that gathers per-table statistics.
38pub struct Analyzer {
39    input_file: PathBuf,
40    dialect: SqlDialect,
41    stats: AHashMap<String, TableStats>,
42}
43
44impl Analyzer {
45    /// Create a new analyzer for the given input file.
46    pub fn new(input_file: PathBuf) -> Self {
47        Self {
48            input_file,
49            dialect: SqlDialect::default(),
50            stats: AHashMap::new(),
51        }
52    }
53
54    /// Set the SQL dialect for parsing.
55    pub fn with_dialect(mut self, dialect: SqlDialect) -> Self {
56        self.dialect = dialect;
57        self
58    }
59
60    /// Run the analysis, returning sorted table statistics.
61    pub fn analyze(self) -> anyhow::Result<Vec<TableStats>> {
62        self.run(None)
63    }
64
65    /// Run the analysis with a progress callback, returning sorted table statistics.
66    pub fn analyze_with_progress<F: Fn(u64) + 'static>(
67        self,
68        progress_fn: F,
69    ) -> anyhow::Result<Vec<TableStats>> {
70        self.run(Some(Box::new(progress_fn)))
71    }
72
73    /// Shared scan loop behind [`Self::analyze`] / [`Self::analyze_with_progress`].
74    fn run(mut self, progress_fn: Option<Box<dyn Fn(u64)>>) -> anyhow::Result<Vec<TableStats>> {
75        let file_size = std::fs::metadata(&self.input_file)?.len();
76        let buffer_size = determine_buffer_size(file_size);
77        let dialect = self.dialect;
78
79        // Open the input, transparently handling any supported compression
80        // format (including zip archives).
81        let reader: Box<dyn Read> = open_input_opt_progress(&self.input_file, progress_fn)?;
82
83        let mut parser = Parser::with_dialect(reader, buffer_size, dialect);
84
85        while let Some(stmt) = parser.read_statement()? {
86            let (stmt_type, table_name) =
87                Parser::<&[u8]>::parse_statement_with_dialect(&stmt, dialect);
88
89            if stmt_type == StatementType::Unknown || table_name.is_empty() {
90                continue;
91            }
92
93            self.update_stats(&table_name, stmt_type, stmt.len() as u64);
94        }
95
96        Ok(self.get_sorted_stats())
97    }
98
99    fn update_stats(&mut self, table_name: &str, stmt_type: StatementType, bytes: u64) {
100        let stats = self
101            .stats
102            .entry(table_name.to_string())
103            .or_insert_with(|| TableStats::new(table_name.to_string()));
104
105        stats.statement_count += 1;
106        stats.total_bytes += bytes;
107
108        match stmt_type {
109            StatementType::CreateTable => stats.create_count += 1,
110            StatementType::Insert | StatementType::Copy => stats.insert_count += 1,
111            _ => {}
112        }
113    }
114
115    fn get_sorted_stats(&self) -> Vec<TableStats> {
116        let mut result: Vec<TableStats> = self.stats.values().cloned().collect();
117        result.sort_by_key(|s| std::cmp::Reverse(s.insert_count));
118        result
119    }
120}