Skip to main content

sql_splitter/differ/
mod.rs

1//! Diff module for comparing two SQL dumps.
2//!
3//! This module provides:
4//! - Schema comparison (tables added/removed/modified, columns, PKs, FKs)
5//! - Data comparison (row counts: added/removed/modified)
6//! - Memory-bounded operation using PK hashing
7//! - Multiple output formats (text, json, sql)
8
9mod data;
10mod output;
11mod schema;
12
13pub use data::*;
14pub use output::*;
15pub use schema::*;
16
17use crate::parser::SqlDialect;
18use crate::schema::Schema;
19use glob::Pattern;
20use serde::Serialize;
21use std::path::{Path, PathBuf};
22use std::sync::Arc;
23
24/// Configuration for the diff operation
25#[derive(Debug, Clone)]
26pub struct DiffConfig {
27    /// Path to the "old" SQL file
28    pub old_path: PathBuf,
29    /// Path to the "new" SQL file
30    pub new_path: PathBuf,
31    /// SQL dialect (auto-detected if None)
32    pub dialect: Option<SqlDialect>,
33    /// Only compare schema, skip data
34    pub schema_only: bool,
35    /// Only compare data, skip schema
36    pub data_only: bool,
37    /// Tables to include (if empty, include all)
38    pub tables: Vec<String>,
39    /// Tables to exclude
40    pub exclude: Vec<String>,
41    /// Output format
42    pub format: DiffOutputFormat,
43    /// Show verbose row-level details
44    pub verbose: bool,
45    /// Show progress bar
46    pub progress: bool,
47    /// Maximum PK entries to track globally
48    pub max_pk_entries: usize,
49    /// Don't skip tables without PK, use all columns as key
50    pub allow_no_pk: bool,
51    /// Ignore column order when comparing schemas
52    pub ignore_column_order: bool,
53    /// Primary key overrides: table name -> column names
54    pub pk_overrides: std::collections::HashMap<String, Vec<String>>,
55    /// Column patterns to ignore (glob format: table.column)
56    pub ignore_columns: Vec<String>,
57}
58
59impl Default for DiffConfig {
60    fn default() -> Self {
61        Self {
62            old_path: PathBuf::new(),
63            new_path: PathBuf::new(),
64            dialect: None,
65            schema_only: false,
66            data_only: false,
67            tables: Vec::new(),
68            exclude: Vec::new(),
69            format: DiffOutputFormat::Text,
70            verbose: false,
71            progress: false,
72            max_pk_entries: 10_000_000, // 10M entries ~= 160MB
73            allow_no_pk: false,
74            ignore_column_order: false,
75            pk_overrides: std::collections::HashMap::new(),
76            ignore_columns: Vec::new(),
77        }
78    }
79}
80
81/// Output format for diff results
82#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
83pub enum DiffOutputFormat {
84    #[default]
85    Text,
86    Json,
87    Sql,
88}
89
90impl std::str::FromStr for DiffOutputFormat {
91    type Err = String;
92
93    fn from_str(s: &str) -> Result<Self, Self::Err> {
94        match s.to_lowercase().as_str() {
95            "text" => Ok(Self::Text),
96            "json" => Ok(Self::Json),
97            "sql" => Ok(Self::Sql),
98            _ => Err(format!("Unknown format: {}. Use: text, json, sql", s)),
99        }
100    }
101}
102
103/// A warning generated during diff operation
104#[derive(Debug, Serialize, Clone)]
105pub struct DiffWarning {
106    #[serde(skip_serializing_if = "Option::is_none")]
107    pub table: Option<String>,
108    pub message: String,
109}
110
111/// Complete diff result
112#[derive(Debug, Serialize)]
113pub struct DiffResult {
114    /// Schema differences
115    #[serde(skip_serializing_if = "Option::is_none")]
116    pub schema: Option<SchemaDiff>,
117    /// Data differences
118    #[serde(skip_serializing_if = "Option::is_none")]
119    pub data: Option<DataDiff>,
120    /// Warnings generated during diff
121    #[serde(skip_serializing_if = "Vec::is_empty")]
122    pub warnings: Vec<DiffWarning>,
123    /// Summary statistics
124    pub summary: DiffSummary,
125}
126
127/// Summary of differences
128#[derive(Debug, Serialize)]
129pub struct DiffSummary {
130    /// Number of tables added
131    pub tables_added: usize,
132    /// Number of tables removed
133    pub tables_removed: usize,
134    /// Number of tables modified (schema or data)
135    pub tables_modified: usize,
136    /// Total rows added across all tables
137    pub rows_added: u64,
138    /// Total rows removed across all tables
139    pub rows_removed: u64,
140    /// Total rows modified across all tables
141    pub rows_modified: u64,
142    /// Whether any data was truncated due to memory limits
143    pub truncated: bool,
144}
145
146/// Main differ engine
147pub struct Differ {
148    config: DiffConfig,
149    dialect: SqlDialect,
150    progress_fn: Option<Arc<dyn Fn(u64, u64) + Send + Sync>>,
151}
152
153impl Differ {
154    /// Create a new differ with the given configuration
155    pub fn new(config: DiffConfig) -> Self {
156        Self {
157            dialect: config.dialect.unwrap_or(SqlDialect::MySql),
158            config,
159            progress_fn: None,
160        }
161    }
162
163    /// Set a progress callback (receives current bytes, total bytes)
164    pub fn with_progress<F>(mut self, f: F) -> Self
165    where
166        F: Fn(u64, u64) + Send + Sync + 'static,
167    {
168        self.progress_fn = Some(Arc::new(f));
169        self
170    }
171
172    /// Run the diff operation
173    pub fn diff(self) -> anyhow::Result<DiffResult> {
174        // Calculate total bytes for progress (4 passes max: 2 schema + 2 data)
175        let old_size = std::fs::metadata(&self.config.old_path)?.len();
176        let new_size = std::fs::metadata(&self.config.new_path)?.len();
177        let total_bytes = if self.config.schema_only || self.config.data_only {
178            old_size + new_size
179        } else {
180            (old_size + new_size) * 2 // Schema pass + data pass for each file
181        };
182
183        // Pass 0: Extract schemas from both files (always needed, even data-only needs PK info)
184        let old_schema = self.extract_schema(&self.config.old_path.clone(), 0, total_bytes)?;
185        let new_schema =
186            self.extract_schema(&self.config.new_path.clone(), old_size, total_bytes)?;
187
188        // Schema comparison
189        let schema_diff = if !self.config.data_only {
190            Some(compare_schemas(&old_schema, &new_schema, &self.config))
191        } else {
192            None
193        };
194
195        // Data comparison
196        let (data_diff, warnings) = if !self.config.schema_only {
197            let base_offset = if self.config.data_only {
198                0
199            } else {
200                old_size + new_size
201            };
202
203            let (data, warns) =
204                self.compare_data(&old_schema, &new_schema, base_offset, total_bytes)?;
205            (Some(data), warns)
206        } else {
207            (None, Vec::new())
208        };
209
210        // Build summary
211        let summary = self.build_summary(&schema_diff, &data_diff);
212
213        Ok(DiffResult {
214            schema: schema_diff,
215            data: data_diff,
216            warnings,
217            summary,
218        })
219    }
220
221    /// Extract schema from a SQL file
222    fn extract_schema(
223        &self,
224        path: &Path,
225        byte_offset: u64,
226        total_bytes: u64,
227    ) -> anyhow::Result<Schema> {
228        let progress_fn: Option<Box<dyn Fn(u64)>> = self.progress_fn.as_ref().map(|cb| {
229            let cb = Arc::clone(cb);
230            Box::new(move |bytes| cb(byte_offset + bytes, total_bytes)) as Box<dyn Fn(u64)>
231        });
232
233        Schema::from_sql_file(path, self.dialect, progress_fn)
234    }
235
236    /// Compare data between two SQL files
237    fn compare_data(
238        &self,
239        old_schema: &Schema,
240        new_schema: &Schema,
241        byte_offset: u64,
242        total_bytes: u64,
243    ) -> anyhow::Result<(DataDiff, Vec<DiffWarning>)> {
244        let mut data_differ = DataDiffer::new(DataDiffOptions {
245            max_pk_entries_global: self.config.max_pk_entries,
246            max_pk_entries_per_table: self.config.max_pk_entries / 2,
247            sample_size: if self.config.verbose { 100 } else { 0 },
248            tables: self.config.tables.clone(),
249            exclude: self.config.exclude.clone(),
250            allow_no_pk: self.config.allow_no_pk,
251            pk_overrides: self.config.pk_overrides.clone(),
252            ignore_columns: self.config.ignore_columns.clone(),
253        });
254
255        let old_size = std::fs::metadata(&self.config.old_path)?.len();
256
257        // Pass 1: Scan old file
258        data_differ.scan_file(
259            &self.config.old_path,
260            old_schema,
261            self.dialect,
262            true, // is_old
263            &self.progress_fn,
264            byte_offset,
265            total_bytes,
266        )?;
267
268        // Pass 2: Scan new file
269        data_differ.scan_file(
270            &self.config.new_path,
271            new_schema,
272            self.dialect,
273            false, // is_old
274            &self.progress_fn,
275            byte_offset + old_size,
276            total_bytes,
277        )?;
278
279        Ok(data_differ.compute_diff())
280    }
281
282    /// Build summary from diff results
283    fn build_summary(
284        &self,
285        schema_diff: &Option<SchemaDiff>,
286        data_diff: &Option<DataDiff>,
287    ) -> DiffSummary {
288        let (tables_added, tables_removed, schema_modified) = schema_diff
289            .as_ref()
290            .map(|s| {
291                (
292                    s.tables_added.len(),
293                    s.tables_removed.len(),
294                    s.tables_modified.len(),
295                )
296            })
297            .unwrap_or((0, 0, 0));
298
299        let (rows_added, rows_removed, rows_modified, data_modified, truncated) = data_diff
300            .as_ref()
301            .map(|d| {
302                let mut added = 0u64;
303                let mut removed = 0u64;
304                let mut modified = 0u64;
305                let mut tables_with_changes = 0usize;
306                let mut any_truncated = false;
307
308                for table_diff in d.tables.values() {
309                    added += table_diff.added_count;
310                    removed += table_diff.removed_count;
311                    modified += table_diff.modified_count;
312                    if table_diff.added_count > 0
313                        || table_diff.removed_count > 0
314                        || table_diff.modified_count > 0
315                    {
316                        tables_with_changes += 1;
317                    }
318                    if table_diff.truncated {
319                        any_truncated = true;
320                    }
321                }
322
323                (added, removed, modified, tables_with_changes, any_truncated)
324            })
325            .unwrap_or((0, 0, 0, 0, false));
326
327        DiffSummary {
328            tables_added,
329            tables_removed,
330            tables_modified: schema_modified.max(data_modified),
331            rows_added,
332            rows_removed,
333            rows_modified,
334            truncated,
335        }
336    }
337}
338
339/// Parse ignore column patterns into compiled Pattern objects
340pub fn parse_ignore_patterns(patterns: &[String]) -> Vec<Pattern> {
341    patterns
342        .iter()
343        .filter_map(|p| Pattern::new(&p.to_lowercase()).ok())
344        .collect()
345}
346
347/// Check if a column should be ignored based on patterns
348pub fn should_ignore_column(table: &str, column: &str, patterns: &[Pattern]) -> bool {
349    let full_name = format!("{}.{}", table.to_lowercase(), column.to_lowercase());
350    patterns.iter().any(|p| p.matches(&full_name))
351}
352
353/// Check if a table should be included based on filter config
354pub fn should_include_table(table_name: &str, tables: &[String], exclude: &[String]) -> bool {
355    // If include list is specified, table must be in it
356    if !tables.is_empty() {
357        let name_lower = table_name.to_lowercase();
358        if !tables.iter().any(|t| t.to_lowercase() == name_lower) {
359            return false;
360        }
361    }
362
363    // If table is in exclude list, skip it
364    if !exclude.is_empty() {
365        let name_lower = table_name.to_lowercase();
366        if exclude.iter().any(|t| t.to_lowercase() == name_lower) {
367            return false;
368        }
369    }
370
371    true
372}