1use super::{parse_ignore_patterns, should_ignore_column, should_include_table, DiffWarning};
7use crate::parser::{
8 determine_buffer_size, mysql_insert, postgres_copy, Parser, SqlDialect, StatementType,
9};
10use crate::pk::{format_pk_tuple, hash_pk_value_into, hash_pk_values, PkHash};
11use crate::schema::Schema;
12use crate::splitter::open_input_opt_progress;
13use ahash::AHashMap;
14use glob::Pattern;
15use serde::Serialize;
16use std::collections::HashMap;
17use std::hash::Hasher;
18use std::io::Read;
19use std::path::PathBuf;
20use std::sync::Arc;
21
22#[derive(Debug, Clone)]
24pub struct DataDiffOptions {
25 pub max_pk_entries_global: usize,
27 pub max_pk_entries_per_table: usize,
29 pub sample_size: usize,
31 pub tables: Vec<String>,
33 pub exclude: Vec<String>,
35 pub allow_no_pk: bool,
37 pub pk_overrides: std::collections::HashMap<String, Vec<String>>,
39 pub ignore_columns: Vec<String>,
41}
42
43impl Default for DataDiffOptions {
44 fn default() -> Self {
45 Self {
46 max_pk_entries_global: 10_000_000,
47 max_pk_entries_per_table: 5_000_000,
48 sample_size: 0,
49 tables: Vec::new(),
50 exclude: Vec::new(),
51 allow_no_pk: false,
52 pk_overrides: std::collections::HashMap::new(),
53 ignore_columns: Vec::new(),
54 }
55 }
56}
57
58#[derive(Debug, Serialize)]
60pub struct DataDiff {
61 pub tables: HashMap<String, TableDataDiff>,
63}
64
65#[derive(Debug, Serialize, Clone, Default)]
67pub struct TableDataDiff {
68 pub old_row_count: u64,
70 pub new_row_count: u64,
72 pub added_count: u64,
74 pub removed_count: u64,
76 pub modified_count: u64,
78 pub truncated: bool,
80 #[serde(skip_serializing_if = "Vec::is_empty")]
82 pub sample_added_pks: Vec<String>,
83 #[serde(skip_serializing_if = "Vec::is_empty")]
85 pub sample_removed_pks: Vec<String>,
86 #[serde(skip_serializing_if = "Vec::is_empty")]
88 pub sample_modified_pks: Vec<String>,
89}
90
91struct TableState {
93 row_count: u64,
95 pk_to_digest: Option<AHashMap<PkHash, u64>>,
98 pk_strings: Option<AHashMap<PkHash, String>>,
100 truncated: bool,
102}
103
104impl TableState {
105 fn new() -> Self {
106 Self {
107 row_count: 0,
108 pk_to_digest: Some(AHashMap::new()),
109 pk_strings: None,
110 truncated: false,
111 }
112 }
113
114 fn new_with_pk_strings() -> Self {
115 Self {
116 row_count: 0,
117 pk_to_digest: Some(AHashMap::new()),
118 pk_strings: Some(AHashMap::new()),
119 truncated: false,
120 }
121 }
122}
123
124fn hash_row_digest(values: &[mysql_insert::PkValue], ignore_indices: &[usize]) -> u64 {
127 let mut hasher = ahash::AHasher::default();
128 for (i, v) in values.iter().enumerate() {
129 if ignore_indices.contains(&i) {
130 continue;
131 }
132 hash_pk_value_into(v, &mut hasher);
133 }
134 hasher.finish()
135}
136
137pub struct DataDiffer {
139 options: DataDiffOptions,
140 old_state: AHashMap<String, TableState>,
142 new_state: AHashMap<String, TableState>,
144 total_pk_entries: usize,
146 global_truncated: bool,
148 current_copy_context: Option<(String, Vec<String>)>,
150 warnings: Vec<DiffWarning>,
152 warned_tables: AHashMap<String, ()>,
154 ignore_patterns: Vec<Pattern>,
156 ignore_indices_cache: AHashMap<String, Vec<usize>>,
158}
159
160impl DataDiffer {
161 pub fn new(options: DataDiffOptions) -> Self {
163 let ignore_patterns = parse_ignore_patterns(&options.ignore_columns);
164 Self {
165 options,
166 old_state: AHashMap::new(),
167 new_state: AHashMap::new(),
168 total_pk_entries: 0,
169 global_truncated: false,
170 current_copy_context: None,
171 warnings: Vec::new(),
172 warned_tables: AHashMap::new(),
173 ignore_patterns,
174 ignore_indices_cache: AHashMap::new(),
175 }
176 }
177
178 fn get_ignore_indices(
180 &mut self,
181 table_name: &str,
182 table_schema: &crate::schema::TableSchema,
183 ) -> Vec<usize> {
184 let table_lower = table_name.to_lowercase();
185 if let Some(indices) = self.ignore_indices_cache.get(&table_lower) {
186 return indices.clone();
187 }
188
189 let pk_indices: Vec<usize> = table_schema
191 .primary_key
192 .iter()
193 .map(|col_id| col_id.0 as usize)
194 .collect();
195
196 let mut indices: Vec<usize> = Vec::new();
197 for (i, col) in table_schema.columns.iter().enumerate() {
198 if should_ignore_column(table_name, &col.name, &self.ignore_patterns) {
199 if pk_indices.contains(&i) && !self.warned_tables.contains_key(&table_lower) {
201 self.warnings.push(DiffWarning {
202 table: Some(table_name.to_string()),
203 message: format!(
204 "Ignoring primary key column '{}' may affect diff accuracy",
205 col.name
206 ),
207 });
208 }
209 indices.push(i);
210 }
211 }
212
213 self.ignore_indices_cache
214 .insert(table_lower, indices.clone());
215 indices
216 }
217
218 fn get_effective_pk_indices(
221 &self,
222 table_name: &str,
223 table_schema: &crate::schema::TableSchema,
224 ) -> (Vec<usize>, bool, Vec<String>) {
225 if let Some(override_cols) = self.options.pk_overrides.get(&table_name.to_lowercase()) {
226 let mut indices: Vec<usize> = Vec::new();
227 let mut invalid_cols: Vec<String> = Vec::new();
228
229 for col_name in override_cols {
230 if let Some(idx) = table_schema
231 .columns
232 .iter()
233 .position(|c| c.name.eq_ignore_ascii_case(col_name))
234 {
235 indices.push(idx);
236 } else {
237 invalid_cols.push(col_name.clone());
238 }
239 }
240
241 (indices, true, invalid_cols)
242 } else {
243 let indices: Vec<usize> = table_schema
244 .primary_key
245 .iter()
246 .map(|col_id| col_id.0 as usize)
247 .collect();
248 (indices, false, Vec::new())
249 }
250 }
251
252 fn extract_pk_from_values(
254 &self,
255 all_values: &[mysql_insert::PkValue],
256 pk_indices: &[usize],
257 ) -> Option<smallvec::SmallVec<[mysql_insert::PkValue; 2]>> {
258 if pk_indices.is_empty() {
259 return None;
260 }
261 let mut pk_values: smallvec::SmallVec<[mysql_insert::PkValue; 2]> =
262 smallvec::SmallVec::new();
263 for &idx in pk_indices {
264 let val = all_values.get(idx)?;
265 if val.is_null() {
266 return None;
267 }
268 pk_values.push(val.clone());
269 }
270 if pk_values.is_empty() {
271 None
272 } else {
273 Some(pk_values)
274 }
275 }
276
277 #[allow(clippy::too_many_arguments)]
279 pub fn scan_file(
280 &mut self,
281 path: &PathBuf,
282 schema: &Schema,
283 dialect: SqlDialect,
284 is_old: bool,
285 progress_fn: &Option<Arc<dyn Fn(u64, u64) + Send + Sync>>,
286 byte_offset: u64,
287 total_bytes: u64,
288 ) -> anyhow::Result<()> {
289 let file_size = std::fs::metadata(path)?.len();
290 let buffer_size = determine_buffer_size(file_size);
291
292 let progress: Option<Box<dyn Fn(u64)>> = progress_fn.as_ref().map(|cb| {
295 let cb = Arc::clone(cb);
296 Box::new(move |bytes| cb(byte_offset + bytes, total_bytes)) as Box<dyn Fn(u64)>
297 });
298 let reader: Box<dyn Read> = open_input_opt_progress(path, progress)?;
299
300 let mut parser = Parser::with_dialect(reader, buffer_size, dialect);
301
302 self.current_copy_context = None;
304
305 while let Some(stmt) = parser.read_statement()? {
306 let (stmt_type, table_name) =
307 Parser::<&[u8]>::parse_statement_with_dialect(&stmt, dialect);
308
309 if dialect == SqlDialect::Postgres && stmt_type == StatementType::Unknown {
311 if crate::copy_data::is_copy_data_block(&stmt) {
313 if let Some((ref copy_table, ref column_order)) =
314 self.current_copy_context.clone()
315 {
316 if should_include_table(
318 copy_table,
319 &self.options.tables,
320 &self.options.exclude,
321 ) {
322 if let Some(table_schema) = schema.get_table(copy_table) {
323 let has_pk = !table_schema.primary_key.is_empty();
324 let has_pk_override = self
325 .options
326 .pk_overrides
327 .contains_key(©_table.to_lowercase());
328 if has_pk || self.options.allow_no_pk || has_pk_override {
329 self.process_copy_data(
330 &stmt,
331 copy_table,
332 table_schema,
333 column_order.clone(),
334 is_old,
335 )?;
336 } else if !self.warned_tables.contains_key(copy_table) {
337 self.warned_tables.insert(copy_table.clone(), ());
338 self.warnings.push(DiffWarning {
339 table: Some(copy_table.clone()),
340 message: "No primary key, data comparison skipped"
341 .to_string(),
342 });
343 }
344 }
345 }
346 }
347 }
348 self.current_copy_context = None;
349 continue;
350 }
351
352 if table_name.is_empty() {
353 continue;
354 }
355
356 if !should_include_table(&table_name, &self.options.tables, &self.options.exclude) {
358 continue;
359 }
360
361 let table_schema = match schema.get_table(&table_name) {
363 Some(t) => t,
364 None => continue,
365 };
366
367 let has_pk_override = self
369 .options
370 .pk_overrides
371 .contains_key(&table_name.to_lowercase());
372 if table_schema.primary_key.is_empty() && !self.options.allow_no_pk && !has_pk_override
373 {
374 if !self.warned_tables.contains_key(&table_name) {
376 self.warned_tables.insert(table_name.clone(), ());
377 self.warnings.push(DiffWarning {
378 table: Some(table_name.clone()),
379 message: "No primary key, data comparison skipped".to_string(),
380 });
381 }
382 continue;
383 }
385
386 match stmt_type {
387 StatementType::Insert => {
388 self.process_insert_statement(
389 &stmt,
390 &table_name,
391 table_schema,
392 is_old,
393 dialect,
394 )?;
395 }
396 StatementType::Copy => {
397 let header = String::from_utf8_lossy(&stmt);
400 let column_order = postgres_copy::parse_copy_columns(&header);
401 self.current_copy_context = Some((table_name.clone(), column_order));
402 }
403 _ => {}
404 }
405 }
406
407 Ok(())
408 }
409
410 fn process_insert_statement(
412 &mut self,
413 stmt: &[u8],
414 table_name: &str,
415 table_schema: &crate::schema::TableSchema,
416 is_old: bool,
417 dialect: SqlDialect,
418 ) -> anyhow::Result<()> {
419 let rows = mysql_insert::parse_insert_rows(stmt, table_schema, dialect)?;
420
421 let (pk_indices, has_override, invalid_cols) =
422 self.get_effective_pk_indices(table_name, table_schema);
423
424 let ignore_indices = self.get_ignore_indices(table_name, table_schema);
426
427 if !invalid_cols.is_empty() && !self.warned_tables.contains_key(table_name) {
429 self.warned_tables.insert(table_name.to_string(), ());
430 self.warnings.push(DiffWarning {
431 table: Some(table_name.to_string()),
432 message: format!(
433 "Primary key override column(s) not found: {}",
434 invalid_cols.join(", ")
435 ),
436 });
437 }
438
439 for row in rows {
440 let effective_pk = if has_override {
441 self.extract_pk_from_values(&row.all_values, &pk_indices)
442 } else {
443 row.pk
444 };
445 self.record_row(
446 table_name,
447 &effective_pk,
448 &row.all_values,
449 is_old,
450 &ignore_indices,
451 );
452 }
453
454 Ok(())
455 }
456
457 fn process_copy_data(
459 &mut self,
460 data_stmt: &[u8],
461 table_name: &str,
462 table_schema: &crate::schema::TableSchema,
463 column_order: Vec<String>,
464 is_old: bool,
465 ) -> anyhow::Result<()> {
466 let data = crate::copy_data::trim_copy_data(data_stmt);
469
470 if data.is_empty() {
471 return Ok(());
472 }
473
474 let rows = postgres_copy::parse_postgres_copy_rows(data, table_schema, column_order)?;
475
476 let (pk_indices, has_override, invalid_cols) =
477 self.get_effective_pk_indices(table_name, table_schema);
478
479 let ignore_indices = self.get_ignore_indices(table_name, table_schema);
481
482 if !invalid_cols.is_empty() && !self.warned_tables.contains_key(table_name) {
484 self.warned_tables.insert(table_name.to_string(), ());
485 self.warnings.push(DiffWarning {
486 table: Some(table_name.to_string()),
487 message: format!(
488 "Primary key override column(s) not found: {}",
489 invalid_cols.join(", ")
490 ),
491 });
492 }
493
494 for row in rows {
495 let effective_pk = if has_override {
496 self.extract_pk_from_values(&row.all_values, &pk_indices)
497 } else {
498 row.pk
499 };
500 self.record_row(
501 table_name,
502 &effective_pk,
503 &row.all_values,
504 is_old,
505 &ignore_indices,
506 );
507 }
508
509 Ok(())
510 }
511
512 fn record_row(
514 &mut self,
515 table_name: &str,
516 pk: &Option<smallvec::SmallVec<[mysql_insert::PkValue; 2]>>,
517 all_values: &[mysql_insert::PkValue],
518 is_old: bool,
519 ignore_indices: &[usize],
520 ) {
521 if self.global_truncated {
522 let state = if is_old {
524 self.old_state
525 .entry(table_name.to_string())
526 .or_insert_with(|| {
527 let mut s = TableState::new();
528 s.pk_to_digest = None;
529 s.truncated = true;
530 s
531 })
532 } else {
533 self.new_state
534 .entry(table_name.to_string())
535 .or_insert_with(|| {
536 let mut s = TableState::new();
537 s.pk_to_digest = None;
538 s.truncated = true;
539 s
540 })
541 };
542 state.row_count += 1;
543 return;
544 }
545
546 let sample_size = self.options.sample_size;
547 let state = if is_old {
548 self.old_state
549 .entry(table_name.to_string())
550 .or_insert_with(|| {
551 if sample_size > 0 {
552 TableState::new_with_pk_strings()
553 } else {
554 TableState::new()
555 }
556 })
557 } else {
558 self.new_state
559 .entry(table_name.to_string())
560 .or_insert_with(|| {
561 if sample_size > 0 {
562 TableState::new_with_pk_strings()
563 } else {
564 TableState::new()
565 }
566 })
567 };
568
569 state.row_count += 1;
570
571 if let Some(ref map) = state.pk_to_digest {
573 if map.len() >= self.options.max_pk_entries_per_table {
574 state.pk_to_digest = None;
575 state.pk_strings = None;
576 state.truncated = true;
577 return;
578 }
579 }
580
581 if self.total_pk_entries >= self.options.max_pk_entries_global {
583 self.global_truncated = true;
584 state.pk_to_digest = None;
585 state.pk_strings = None;
586 state.truncated = true;
587 return;
588 }
589
590 if let Some(ref pk_values) = pk {
592 if let Some(ref mut map) = state.pk_to_digest {
593 let pk_hash = hash_pk_values(pk_values);
594 let row_digest = hash_row_digest(all_values, ignore_indices);
595 let was_new = map.insert(pk_hash, row_digest).is_none();
596 if was_new {
597 self.total_pk_entries += 1;
598 }
599
600 if let Some(ref mut pk_str_map) = state.pk_strings {
602 pk_str_map.insert(pk_hash, format_pk_tuple(pk_values));
603 }
604 }
605 }
606 }
607
608 pub fn compute_diff(self) -> (DataDiff, Vec<DiffWarning>) {
610 let mut tables: HashMap<String, TableDataDiff> = HashMap::new();
611 let sample_size = self.options.sample_size;
612
613 let mut all_tables: Vec<String> = self.old_state.keys().cloned().collect();
615 for name in self.new_state.keys() {
616 if !all_tables.contains(name) {
617 all_tables.push(name.clone());
618 }
619 }
620
621 for table_name in all_tables {
622 let old_state = self.old_state.get(&table_name);
623 let new_state = self.new_state.get(&table_name);
624
625 let mut diff = TableDataDiff {
626 old_row_count: old_state.map(|s| s.row_count).unwrap_or(0),
627 new_row_count: new_state.map(|s| s.row_count).unwrap_or(0),
628 truncated: old_state.map(|s| s.truncated).unwrap_or(false)
629 || new_state.map(|s| s.truncated).unwrap_or(false)
630 || self.global_truncated,
631 ..Default::default()
632 };
633
634 let old_map = old_state.and_then(|s| s.pk_to_digest.as_ref());
636 let new_map = new_state.and_then(|s| s.pk_to_digest.as_ref());
637
638 let old_pk_strings = old_state.and_then(|s| s.pk_strings.as_ref());
640 let new_pk_strings = new_state.and_then(|s| s.pk_strings.as_ref());
641
642 match (old_map, new_map) {
643 (Some(old), Some(new)) => {
644 for pk_hash in new.keys() {
646 if !old.contains_key(pk_hash) {
647 diff.added_count += 1;
648
649 if sample_size > 0 && diff.sample_added_pks.len() < sample_size {
651 if let Some(pk_str) = new_pk_strings.and_then(|m| m.get(pk_hash)) {
652 diff.sample_added_pks.push(pk_str.clone());
653 }
654 }
655 }
656 }
657
658 for (pk_hash, old_digest) in old {
660 match new.get(pk_hash) {
661 None => {
662 diff.removed_count += 1;
663
664 if sample_size > 0 && diff.sample_removed_pks.len() < sample_size {
666 if let Some(pk_str) =
667 old_pk_strings.and_then(|m| m.get(pk_hash))
668 {
669 diff.sample_removed_pks.push(pk_str.clone());
670 }
671 }
672 }
673 Some(new_digest) => {
674 if old_digest != new_digest {
675 diff.modified_count += 1;
676
677 if sample_size > 0
679 && diff.sample_modified_pks.len() < sample_size
680 {
681 if let Some(pk_str) =
682 old_pk_strings.and_then(|m| m.get(pk_hash))
683 {
684 diff.sample_modified_pks.push(pk_str.clone());
685 }
686 }
687 }
688 }
689 }
690 }
691 }
692 _ => {
693 if diff.new_row_count > diff.old_row_count {
695 diff.added_count = diff.new_row_count - diff.old_row_count;
696 } else if diff.old_row_count > diff.new_row_count {
697 diff.removed_count = diff.old_row_count - diff.new_row_count;
698 }
699 }
700 }
701
702 if diff.old_row_count > 0
704 || diff.new_row_count > 0
705 || diff.added_count > 0
706 || diff.removed_count > 0
707 || diff.modified_count > 0
708 {
709 tables.insert(table_name, diff);
710 }
711 }
712
713 (DataDiff { tables }, self.warnings)
714 }
715}