1mod 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#[derive(Debug, Clone)]
26pub struct DiffConfig {
27 pub old_path: PathBuf,
29 pub new_path: PathBuf,
31 pub dialect: Option<SqlDialect>,
33 pub schema_only: bool,
35 pub data_only: bool,
37 pub tables: Vec<String>,
39 pub exclude: Vec<String>,
41 pub format: DiffOutputFormat,
43 pub verbose: bool,
45 pub progress: bool,
47 pub max_pk_entries: usize,
49 pub allow_no_pk: bool,
51 pub ignore_column_order: bool,
53 pub pk_overrides: std::collections::HashMap<String, Vec<String>>,
55 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, 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#[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#[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#[derive(Debug, Serialize)]
113pub struct DiffResult {
114 #[serde(skip_serializing_if = "Option::is_none")]
116 pub schema: Option<SchemaDiff>,
117 #[serde(skip_serializing_if = "Option::is_none")]
119 pub data: Option<DataDiff>,
120 #[serde(skip_serializing_if = "Vec::is_empty")]
122 pub warnings: Vec<DiffWarning>,
123 pub summary: DiffSummary,
125}
126
127#[derive(Debug, Serialize)]
129pub struct DiffSummary {
130 pub tables_added: usize,
132 pub tables_removed: usize,
134 pub tables_modified: usize,
136 pub rows_added: u64,
138 pub rows_removed: u64,
140 pub rows_modified: u64,
142 pub truncated: bool,
144}
145
146pub struct Differ {
148 config: DiffConfig,
149 dialect: SqlDialect,
150 progress_fn: Option<Arc<dyn Fn(u64, u64) + Send + Sync>>,
151}
152
153impl Differ {
154 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 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 pub fn diff(self) -> anyhow::Result<DiffResult> {
174 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 };
182
183 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 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 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 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 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 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 data_differ.scan_file(
259 &self.config.old_path,
260 old_schema,
261 self.dialect,
262 true, &self.progress_fn,
264 byte_offset,
265 total_bytes,
266 )?;
267
268 data_differ.scan_file(
270 &self.config.new_path,
271 new_schema,
272 self.dialect,
273 false, &self.progress_fn,
275 byte_offset + old_size,
276 total_bytes,
277 )?;
278
279 Ok(data_differ.compute_diff())
280 }
281
282 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
339pub 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
347pub 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
353pub fn should_include_table(table_name: &str, tables: &[String], exclude: &[String]) -> bool {
355 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 !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}