Skip to main content

sql_splitter/differ/
data.rs

1//! Data comparison for diff command.
2//!
3//! Uses streaming with memory-bounded PK tracking to compare row-level
4//! differences between two SQL dumps.
5
6use 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::{Hash, Hasher};
18use std::io::Read;
19use std::path::PathBuf;
20use std::sync::Arc;
21
22/// Options for data comparison
23#[derive(Debug, Clone)]
24pub struct DataDiffOptions {
25    /// Maximum PK entries to track globally
26    pub max_pk_entries_global: usize,
27    /// Maximum PK entries per table
28    pub max_pk_entries_per_table: usize,
29    /// Number of sample rows to collect for verbose mode
30    pub sample_size: usize,
31    /// Tables to include (if empty, include all)
32    pub tables: Vec<String>,
33    /// Tables to exclude
34    pub exclude: Vec<String>,
35    /// Don't skip tables without PK, use all columns as key
36    pub allow_no_pk: bool,
37    /// Primary key overrides: table name -> column names
38    pub pk_overrides: std::collections::HashMap<String, Vec<String>>,
39    /// Column patterns to ignore (glob format: table.column)
40    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/// Complete data diff result
59#[derive(Debug, Serialize)]
60pub struct DataDiff {
61    /// Per-table data differences
62    pub tables: HashMap<String, TableDataDiff>,
63}
64
65/// Data differences for a single table
66#[derive(Debug, Serialize, Clone, Default)]
67pub struct TableDataDiff {
68    /// Row count in old file
69    pub old_row_count: u64,
70    /// Row count in new file
71    pub new_row_count: u64,
72    /// Number of rows added (in new but not old)
73    pub added_count: u64,
74    /// Number of rows removed (in old but not new)
75    pub removed_count: u64,
76    /// Number of rows modified (same PK, different content)
77    pub modified_count: u64,
78    /// Whether tracking was truncated due to memory limits
79    pub truncated: bool,
80    /// Sample PKs for added rows (only when verbose)
81    #[serde(skip_serializing_if = "Vec::is_empty")]
82    pub sample_added_pks: Vec<String>,
83    /// Sample PKs for removed rows (only when verbose)
84    #[serde(skip_serializing_if = "Vec::is_empty")]
85    pub sample_removed_pks: Vec<String>,
86    /// Sample PKs for modified rows (only when verbose)
87    #[serde(skip_serializing_if = "Vec::is_empty")]
88    pub sample_modified_pks: Vec<String>,
89}
90
91/// Per-table state during data scanning
92struct TableState {
93    /// Row count seen
94    row_count: u64,
95    /// Map from PK hash to row digest (for detecting modifications)
96    /// None if tracking was disabled due to memory limits
97    pk_to_digest: Option<AHashMap<PkHash, u64>>,
98    /// Map from PK hash to formatted PK string (only when sample_size > 0)
99    pk_strings: Option<AHashMap<PkHash, String>>,
100    /// Whether tracking was truncated
101    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
124/// Hash a row by schema column identity to detect modifications.
125///
126/// INSERT and COPY can provide reordered or partial column lists, so the
127/// position in `values` is not a stable table column identity. `column_map`
128/// maps each schema column to its position in this specific statement.
129fn hash_row_digest(
130    values: &[mysql_insert::PkValue],
131    column_map: &[Option<usize>],
132    ignore_indices: &[usize],
133) -> u64 {
134    let mut hasher = ahash::AHasher::default();
135    for (schema_index, value_index) in column_map.iter().enumerate() {
136        if ignore_indices.contains(&schema_index) {
137            continue;
138        }
139        schema_index.hash(&mut hasher);
140        match value_index.and_then(|index| values.get(index)) {
141            Some(value) => {
142                1u8.hash(&mut hasher);
143                hash_pk_value_into(value, &mut hasher);
144            }
145            None => 0u8.hash(&mut hasher),
146        }
147    }
148    hasher.finish()
149}
150
151/// Data differ engine that accumulates state across file scans
152pub struct DataDiffer {
153    options: DataDiffOptions,
154    /// State for old file: table -> (pk_hash -> row_digest)
155    old_state: AHashMap<String, TableState>,
156    /// State for new file: table -> (pk_hash -> row_digest)
157    new_state: AHashMap<String, TableState>,
158    /// Total PK entries tracked
159    total_pk_entries: usize,
160    /// Whether global memory limit was exceeded
161    global_truncated: bool,
162    /// Current COPY context for PostgreSQL: (table_name, column_order)
163    current_copy_context: Option<(String, Vec<String>)>,
164    /// Warnings generated during diff
165    warnings: Vec<DiffWarning>,
166    /// Tables already warned about (to avoid duplicate warnings)
167    warned_tables: AHashMap<String, ()>,
168    /// Compiled ignore column patterns
169    ignore_patterns: Vec<Pattern>,
170    /// Cache of ignored column indices per table
171    ignore_indices_cache: AHashMap<String, Vec<usize>>,
172}
173
174/// Parsed row inputs needed to record one side of a data diff.
175struct RowRecord<'a> {
176    key_values: &'a Option<smallvec::SmallVec<[mysql_insert::PkValue; 2]>>,
177    all_values: &'a [mysql_insert::PkValue],
178    column_map: &'a [Option<usize>],
179    ignore_indices: &'a [usize],
180    uses_all_values_as_key: bool,
181}
182
183impl DataDiffer {
184    /// Create a new data differ
185    pub fn new(options: DataDiffOptions) -> Self {
186        let ignore_patterns = parse_ignore_patterns(&options.ignore_columns);
187        Self {
188            options,
189            old_state: AHashMap::new(),
190            new_state: AHashMap::new(),
191            total_pk_entries: 0,
192            global_truncated: false,
193            current_copy_context: None,
194            warnings: Vec::new(),
195            warned_tables: AHashMap::new(),
196            ignore_patterns,
197            ignore_indices_cache: AHashMap::new(),
198        }
199    }
200
201    /// Get ignored column indices for a table
202    fn get_ignore_indices(
203        &mut self,
204        table_name: &str,
205        table_schema: &crate::schema::TableSchema,
206    ) -> Vec<usize> {
207        let table_lower = table_name.to_lowercase();
208        if let Some(indices) = self.ignore_indices_cache.get(&table_lower) {
209            return indices.clone();
210        }
211
212        // Get PK column indices
213        let pk_indices: Vec<usize> = table_schema
214            .primary_key
215            .iter()
216            .map(|col_id| col_id.0 as usize)
217            .collect();
218
219        let mut indices: Vec<usize> = Vec::new();
220        for (i, col) in table_schema.columns.iter().enumerate() {
221            if should_ignore_column(table_name, &col.name, &self.ignore_patterns) {
222                // Warn if trying to ignore a PK column (but still allow it for non-PK uses)
223                if pk_indices.contains(&i) && !self.warned_tables.contains_key(&table_lower) {
224                    self.warnings.push(DiffWarning {
225                        table: Some(table_name.to_string()),
226                        message: format!(
227                            "Ignoring primary key column '{}' may affect diff accuracy",
228                            col.name
229                        ),
230                    });
231                }
232                indices.push(i);
233            }
234        }
235
236        self.ignore_indices_cache
237            .insert(table_lower, indices.clone());
238        indices
239    }
240
241    /// Get effective PK column indices for a table, considering overrides
242    /// Returns (indices, has_override, invalid_columns) tuple
243    fn get_effective_pk_indices(
244        &self,
245        table_name: &str,
246        table_schema: &crate::schema::TableSchema,
247    ) -> (Vec<usize>, bool, Vec<String>) {
248        if let Some(override_cols) = self.options.pk_overrides.get(&table_name.to_lowercase()) {
249            let mut indices: Vec<usize> = Vec::new();
250            let mut invalid_cols: Vec<String> = Vec::new();
251
252            for col_name in override_cols {
253                if let Some(idx) = table_schema
254                    .columns
255                    .iter()
256                    .position(|c| c.name.eq_ignore_ascii_case(col_name))
257                {
258                    indices.push(idx);
259                } else {
260                    invalid_cols.push(col_name.clone());
261                }
262            }
263
264            (indices, true, invalid_cols)
265        } else {
266            let indices: Vec<usize> = table_schema
267                .primary_key
268                .iter()
269                .map(|col_id| col_id.0 as usize)
270                .collect();
271            (indices, false, Vec::new())
272        }
273    }
274
275    /// Extract PK from all_values using the given column indices
276    fn extract_pk_from_values(
277        &self,
278        all_values: &[mysql_insert::PkValue],
279        pk_indices: &[usize],
280    ) -> Option<smallvec::SmallVec<[mysql_insert::PkValue; 2]>> {
281        if pk_indices.is_empty() {
282            return None;
283        }
284        let mut pk_values: smallvec::SmallVec<[mysql_insert::PkValue; 2]> =
285            smallvec::SmallVec::new();
286        for &idx in pk_indices {
287            let val = all_values.get(idx)?;
288            if val.is_null() {
289                return None;
290            }
291            pk_values.push(val.clone());
292        }
293        if pk_values.is_empty() {
294            None
295        } else {
296            Some(pk_values)
297        }
298    }
299
300    /// Build a stable row key from every non-ignored schema column that is
301    /// present in the statement. Each value is prefixed with its schema
302    /// column index, so two partial INSERTs that put the same value in
303    /// different columns cannot collide. This is used for tables without a
304    /// primary key when `--allow-no-pk` is enabled.
305    fn extract_all_non_ignored_values(
306        &self,
307        all_values: &[mysql_insert::PkValue],
308        column_map: &[Option<usize>],
309        table_schema: &crate::schema::TableSchema,
310        ignore_indices: &[usize],
311    ) -> smallvec::SmallVec<[mysql_insert::PkValue; 2]> {
312        table_schema
313            .columns
314            .iter()
315            .enumerate()
316            .filter(|(index, _)| !ignore_indices.contains(index))
317            .flat_map(|(index, _)| {
318                column_map
319                    .get(index)
320                    .and_then(|value_index| *value_index)
321                    .and_then(|value_index| all_values.get(value_index))
322                    .cloned()
323                    .map(|value| [mysql_insert::PkValue::BigInt(index as i128), value])
324                    .into_iter()
325                    .flatten()
326            })
327            .collect()
328    }
329
330    /// Scan a SQL file and accumulate PK/digest state
331    #[allow(clippy::too_many_arguments)]
332    pub fn scan_file(
333        &mut self,
334        path: &PathBuf,
335        schema: &Schema,
336        dialect: SqlDialect,
337        is_old: bool,
338        progress_fn: &Option<Arc<dyn Fn(u64, u64) + Send + Sync>>,
339        byte_offset: u64,
340        total_bytes: u64,
341    ) -> anyhow::Result<()> {
342        let file_size = std::fs::metadata(path)?.len();
343        let buffer_size = determine_buffer_size(file_size);
344
345        // Open the input, transparently handling any supported compression
346        // format (including zip archives).
347        let progress: Option<Box<dyn Fn(u64)>> = progress_fn.as_ref().map(|cb| {
348            let cb = Arc::clone(cb);
349            Box::new(move |bytes| cb(byte_offset + bytes, total_bytes)) as Box<dyn Fn(u64)>
350        });
351        let reader: Box<dyn Read> = open_input_opt_progress(path, progress)?;
352
353        let mut parser = Parser::with_dialect(reader, buffer_size, dialect);
354
355        // Reset COPY context for this file scan
356        self.current_copy_context = None;
357
358        while let Some(stmt) = parser.read_statement()? {
359            let (stmt_type, table_name) =
360                Parser::<&[u8]>::parse_statement_with_dialect(&stmt, dialect);
361
362            // Handle PostgreSQL COPY data (separate statement from header)
363            if dialect == SqlDialect::Postgres && stmt_type == StatementType::Unknown {
364                // Check if this looks like COPY data (ends with \.)
365                if crate::copy_data::is_copy_data_block(&stmt) {
366                    if let Some((ref copy_table, ref column_order)) =
367                        self.current_copy_context.clone()
368                    {
369                        // Check table filter
370                        if should_include_table(
371                            copy_table,
372                            &self.options.tables,
373                            &self.options.exclude,
374                        ) {
375                            if let Some(table_schema) = schema.get_table(copy_table) {
376                                let has_pk = !table_schema.primary_key.is_empty();
377                                let has_pk_override = self
378                                    .options
379                                    .pk_overrides
380                                    .contains_key(&copy_table.to_lowercase());
381                                if has_pk || self.options.allow_no_pk || has_pk_override {
382                                    self.process_copy_data(
383                                        &stmt,
384                                        copy_table,
385                                        table_schema,
386                                        column_order.clone(),
387                                        is_old,
388                                    )?;
389                                } else if !self.warned_tables.contains_key(copy_table) {
390                                    self.warned_tables.insert(copy_table.clone(), ());
391                                    self.warnings.push(DiffWarning {
392                                        table: Some(copy_table.clone()),
393                                        message: "No primary key, data comparison skipped"
394                                            .to_string(),
395                                    });
396                                }
397                            }
398                        }
399                    }
400                }
401                self.current_copy_context = None;
402                continue;
403            }
404
405            if table_name.is_empty() {
406                continue;
407            }
408
409            // Check table filter
410            if !should_include_table(&table_name, &self.options.tables, &self.options.exclude) {
411                continue;
412            }
413
414            // Get table schema for PK info
415            let table_schema = match schema.get_table(&table_name) {
416                Some(t) => t,
417                None => continue,
418            };
419
420            // Handle tables without primary key (unless there's an override)
421            let has_pk_override = self
422                .options
423                .pk_overrides
424                .contains_key(&table_name.to_lowercase());
425            if table_schema.primary_key.is_empty() && !self.options.allow_no_pk && !has_pk_override
426            {
427                // Emit warning once per table
428                if !self.warned_tables.contains_key(&table_name) {
429                    self.warned_tables.insert(table_name.clone(), ());
430                    self.warnings.push(DiffWarning {
431                        table: Some(table_name.clone()),
432                        message: "No primary key, data comparison skipped".to_string(),
433                    });
434                }
435                continue;
436                // allow_no_pk is true - we'll use all columns as key (handled in process_*)
437            }
438
439            match stmt_type {
440                StatementType::Insert => {
441                    self.process_insert_statement(
442                        &stmt,
443                        &table_name,
444                        table_schema,
445                        is_old,
446                        dialect,
447                    )?;
448                }
449                StatementType::Copy => {
450                    // For PostgreSQL COPY, the data comes in the next statement
451                    // Save context for processing the data statement
452                    let header = String::from_utf8_lossy(&stmt);
453                    let column_order = postgres_copy::parse_copy_columns(&header);
454                    self.current_copy_context = Some((table_name.clone(), column_order));
455                }
456                _ => {}
457            }
458        }
459
460        Ok(())
461    }
462
463    /// Process an INSERT statement
464    fn process_insert_statement(
465        &mut self,
466        stmt: &[u8],
467        table_name: &str,
468        table_schema: &crate::schema::TableSchema,
469        is_old: bool,
470        dialect: SqlDialect,
471    ) -> anyhow::Result<()> {
472        let rows = mysql_insert::parse_insert_rows(stmt, table_schema, dialect)?;
473
474        let (pk_indices, has_override, invalid_cols) =
475            self.get_effective_pk_indices(table_name, table_schema);
476
477        // Get ignore indices for this table
478        let ignore_indices = self.get_ignore_indices(table_name, table_schema);
479
480        // Warn about invalid override columns (once per table)
481        if !invalid_cols.is_empty() && !self.warned_tables.contains_key(table_name) {
482            self.warned_tables.insert(table_name.to_string(), ());
483            self.warnings.push(DiffWarning {
484                table: Some(table_name.to_string()),
485                message: format!(
486                    "Primary key override column(s) not found: {}",
487                    invalid_cols.join(", ")
488                ),
489            });
490        }
491
492        for row in rows {
493            let uses_all_values_as_key = self.options.allow_no_pk && pk_indices.is_empty();
494            let effective_pk = if has_override {
495                self.extract_pk_from_values(&row.all_values, &pk_indices)
496            } else if uses_all_values_as_key {
497                Some(self.extract_all_non_ignored_values(
498                    &row.all_values,
499                    &row.column_map,
500                    table_schema,
501                    &ignore_indices,
502                ))
503            } else {
504                row.pk
505            };
506            self.record_row(
507                table_name,
508                RowRecord {
509                    key_values: &effective_pk,
510                    all_values: &row.all_values,
511                    column_map: &row.column_map,
512                    ignore_indices: &ignore_indices,
513                    uses_all_values_as_key,
514                },
515                is_old,
516            );
517        }
518
519        Ok(())
520    }
521
522    /// Process PostgreSQL COPY data (the data lines after the COPY header)
523    fn process_copy_data(
524        &mut self,
525        data_stmt: &[u8],
526        table_name: &str,
527        table_schema: &crate::schema::TableSchema,
528        column_order: Vec<String>,
529        is_old: bool,
530    ) -> anyhow::Result<()> {
531        // The data_stmt contains the raw COPY data lines (may have leading
532        // newline); trim in place as a slice — no copy needed.
533        let data = crate::copy_data::trim_copy_data(data_stmt);
534
535        if data.is_empty() {
536            return Ok(());
537        }
538
539        let rows = postgres_copy::parse_postgres_copy_rows(data, table_schema, column_order)?;
540
541        let (pk_indices, has_override, invalid_cols) =
542            self.get_effective_pk_indices(table_name, table_schema);
543
544        // Get ignore indices for this table
545        let ignore_indices = self.get_ignore_indices(table_name, table_schema);
546
547        // Warn about invalid override columns (once per table)
548        if !invalid_cols.is_empty() && !self.warned_tables.contains_key(table_name) {
549            self.warned_tables.insert(table_name.to_string(), ());
550            self.warnings.push(DiffWarning {
551                table: Some(table_name.to_string()),
552                message: format!(
553                    "Primary key override column(s) not found: {}",
554                    invalid_cols.join(", ")
555                ),
556            });
557        }
558
559        for row in rows {
560            let uses_all_values_as_key = self.options.allow_no_pk && pk_indices.is_empty();
561            let effective_pk = if has_override {
562                self.extract_pk_from_values(&row.all_values, &pk_indices)
563            } else if uses_all_values_as_key {
564                Some(self.extract_all_non_ignored_values(
565                    &row.all_values,
566                    &row.column_map,
567                    table_schema,
568                    &ignore_indices,
569                ))
570            } else {
571                row.pk
572            };
573            self.record_row(
574                table_name,
575                RowRecord {
576                    key_values: &effective_pk,
577                    all_values: &row.all_values,
578                    column_map: &row.column_map,
579                    ignore_indices: &ignore_indices,
580                    uses_all_values_as_key,
581                },
582                is_old,
583            );
584        }
585
586        Ok(())
587    }
588
589    /// Record a row in the appropriate state map
590    fn record_row(&mut self, table_name: &str, row: RowRecord<'_>, is_old: bool) {
591        if self.global_truncated {
592            // Still count rows but don't track PKs
593            let state = if is_old {
594                self.old_state
595                    .entry(table_name.to_string())
596                    .or_insert_with(|| {
597                        let mut s = TableState::new();
598                        s.pk_to_digest = None;
599                        s.truncated = true;
600                        s
601                    })
602            } else {
603                self.new_state
604                    .entry(table_name.to_string())
605                    .or_insert_with(|| {
606                        let mut s = TableState::new();
607                        s.pk_to_digest = None;
608                        s.truncated = true;
609                        s
610                    })
611            };
612            state.row_count += 1;
613            return;
614        }
615
616        let sample_size = self.options.sample_size;
617        let state = if is_old {
618            self.old_state
619                .entry(table_name.to_string())
620                .or_insert_with(|| {
621                    if sample_size > 0 {
622                        TableState::new_with_pk_strings()
623                    } else {
624                        TableState::new()
625                    }
626                })
627        } else {
628            self.new_state
629                .entry(table_name.to_string())
630                .or_insert_with(|| {
631                    if sample_size > 0 {
632                        TableState::new_with_pk_strings()
633                    } else {
634                        TableState::new()
635                    }
636                })
637        };
638
639        state.row_count += 1;
640
641        // Check per-table limit
642        if let Some(ref map) = state.pk_to_digest {
643            if map.len() >= self.options.max_pk_entries_per_table {
644                state.pk_to_digest = None;
645                state.pk_strings = None;
646                state.truncated = true;
647                return;
648            }
649        }
650
651        // Check global limit
652        if self.total_pk_entries >= self.options.max_pk_entries_global {
653            self.global_truncated = true;
654            state.pk_to_digest = None;
655            state.pk_strings = None;
656            state.truncated = true;
657            return;
658        }
659
660        // Record PK and digest
661        if let Some(pk_values) = row.key_values {
662            if let Some(ref mut map) = state.pk_to_digest {
663                let pk_hash = hash_pk_values(pk_values);
664                let row_digest = if row.uses_all_values_as_key {
665                    // The key already contains every non-ignored logical
666                    // column, including reordered INSERT/COPY column lists.
667                    pk_hash
668                } else {
669                    hash_row_digest(row.all_values, row.column_map, row.ignore_indices)
670                };
671                let was_new = map.insert(pk_hash, row_digest).is_none();
672                if was_new {
673                    self.total_pk_entries += 1;
674                }
675
676                // Also store PK string for sampling if enabled
677                if let Some(ref mut pk_str_map) = state.pk_strings {
678                    pk_str_map.insert(pk_hash, format_pk_tuple(pk_values));
679                }
680            }
681        }
682    }
683
684    /// Compute the final diff from accumulated state
685    pub fn compute_diff(self) -> (DataDiff, Vec<DiffWarning>) {
686        let mut tables: HashMap<String, TableDataDiff> = HashMap::new();
687        let sample_size = self.options.sample_size;
688
689        // Get all table names from both states
690        let mut all_tables: Vec<String> = self.old_state.keys().cloned().collect();
691        for name in self.new_state.keys() {
692            if !all_tables.contains(name) {
693                all_tables.push(name.clone());
694            }
695        }
696
697        for table_name in all_tables {
698            let old_state = self.old_state.get(&table_name);
699            let new_state = self.new_state.get(&table_name);
700
701            let mut diff = TableDataDiff {
702                old_row_count: old_state.map(|s| s.row_count).unwrap_or(0),
703                new_row_count: new_state.map(|s| s.row_count).unwrap_or(0),
704                truncated: old_state.map(|s| s.truncated).unwrap_or(false)
705                    || new_state.map(|s| s.truncated).unwrap_or(false)
706                    || self.global_truncated,
707                ..Default::default()
708            };
709
710            // If we have full PK maps, compute detailed diff
711            let old_map = old_state.and_then(|s| s.pk_to_digest.as_ref());
712            let new_map = new_state.and_then(|s| s.pk_to_digest.as_ref());
713
714            // Get PK string maps for sampling
715            let old_pk_strings = old_state.and_then(|s| s.pk_strings.as_ref());
716            let new_pk_strings = new_state.and_then(|s| s.pk_strings.as_ref());
717
718            match (old_map, new_map) {
719                (Some(old), Some(new)) => {
720                    // Count added (in new but not old) and collect samples
721                    for pk_hash in new.keys() {
722                        if !old.contains_key(pk_hash) {
723                            diff.added_count += 1;
724
725                            // Collect sample PK strings
726                            if sample_size > 0 && diff.sample_added_pks.len() < sample_size {
727                                if let Some(pk_str) = new_pk_strings.and_then(|m| m.get(pk_hash)) {
728                                    diff.sample_added_pks.push(pk_str.clone());
729                                }
730                            }
731                        }
732                    }
733
734                    // Count removed (in old but not new) and modified (same PK, different digest)
735                    for (pk_hash, old_digest) in old {
736                        match new.get(pk_hash) {
737                            None => {
738                                diff.removed_count += 1;
739
740                                // Collect sample PK strings
741                                if sample_size > 0 && diff.sample_removed_pks.len() < sample_size {
742                                    if let Some(pk_str) =
743                                        old_pk_strings.and_then(|m| m.get(pk_hash))
744                                    {
745                                        diff.sample_removed_pks.push(pk_str.clone());
746                                    }
747                                }
748                            }
749                            Some(new_digest) => {
750                                if old_digest != new_digest {
751                                    diff.modified_count += 1;
752
753                                    // Collect sample PK strings
754                                    if sample_size > 0
755                                        && diff.sample_modified_pks.len() < sample_size
756                                    {
757                                        if let Some(pk_str) =
758                                            old_pk_strings.and_then(|m| m.get(pk_hash))
759                                        {
760                                            diff.sample_modified_pks.push(pk_str.clone());
761                                        }
762                                    }
763                                }
764                            }
765                        }
766                    }
767                }
768                _ => {
769                    // Truncated - can only report row count differences
770                    if diff.new_row_count > diff.old_row_count {
771                        diff.added_count = diff.new_row_count - diff.old_row_count;
772                    } else if diff.old_row_count > diff.new_row_count {
773                        diff.removed_count = diff.old_row_count - diff.new_row_count;
774                    }
775                }
776            }
777
778            // Only include tables with changes or both files had data
779            if diff.old_row_count > 0
780                || diff.new_row_count > 0
781                || diff.added_count > 0
782                || diff.removed_count > 0
783                || diff.modified_count > 0
784            {
785                tables.insert(table_name, diff);
786            }
787        }
788
789        (DataDiff { tables }, self.warnings)
790    }
791}
792
793#[cfg(test)]
794mod tests {
795    use super::{DataDiffOptions, DataDiffer};
796    use crate::parser::SqlDialect;
797    use crate::schema::{Column, ColumnId, ColumnType, TableId, TableSchema};
798
799    fn logs_schema() -> TableSchema {
800        TableSchema {
801            name: "logs".to_string(),
802            id: TableId(0),
803            columns: vec![
804                Column {
805                    name: "message".to_string(),
806                    col_type: ColumnType::Text,
807                    source_type: "VARCHAR(255)".to_string(),
808                    ordinal: ColumnId(0),
809                    is_primary_key: false,
810                    is_nullable: true,
811                    is_unique: false,
812                    default_sql: None,
813                    is_generated: false,
814                    is_identity: false,
815                    collation: None,
816                },
817                Column {
818                    name: "level".to_string(),
819                    col_type: ColumnType::Text,
820                    source_type: "VARCHAR(20)".to_string(),
821                    ordinal: ColumnId(1),
822                    is_primary_key: false,
823                    is_nullable: true,
824                    is_unique: false,
825                    default_sql: None,
826                    is_generated: false,
827                    is_identity: false,
828                    collation: None,
829                },
830            ],
831            primary_key: Vec::new(),
832            foreign_keys: Vec::new(),
833            unique_constraints: Vec::new(),
834            check_constraints: Vec::new(),
835            indexes: Vec::new(),
836            create_statement: None,
837        }
838    }
839
840    #[test]
841    fn allow_no_pk_uses_all_values_as_the_row_key() {
842        let mut differ = DataDiffer::new(DataDiffOptions {
843            allow_no_pk: true,
844            ..Default::default()
845        });
846        let schema = logs_schema();
847
848        differ
849            .process_insert_statement(
850                b"INSERT INTO logs VALUES ('Test', 'INFO'), ('Debug', 'DEBUG');",
851                "logs",
852                &schema,
853                true,
854                SqlDialect::MySql,
855            )
856            .unwrap();
857        differ
858            .process_insert_statement(
859                b"INSERT INTO logs VALUES ('Test Updated', 'INFO'), ('New', 'WARN');",
860                "logs",
861                &schema,
862                false,
863                SqlDialect::MySql,
864            )
865            .unwrap();
866
867        let (diff, warnings) = differ.compute_diff();
868        let logs = &diff.tables["logs"];
869        assert!(warnings.is_empty());
870        assert_eq!(logs.added_count, 2);
871        assert_eq!(logs.removed_count, 2);
872        assert_eq!(logs.modified_count, 0);
873    }
874
875    #[test]
876    fn allow_no_pk_respects_ignored_columns_with_reordered_insert_columns() {
877        let mut differ = DataDiffer::new(DataDiffOptions {
878            allow_no_pk: true,
879            ignore_columns: vec!["logs.level".to_string()],
880            ..Default::default()
881        });
882        let schema = logs_schema();
883
884        differ
885            .process_insert_statement(
886                b"INSERT INTO logs (level, message) VALUES ('INFO', 'unchanged');",
887                "logs",
888                &schema,
889                true,
890                SqlDialect::MySql,
891            )
892            .unwrap();
893        differ
894            .process_insert_statement(
895                b"INSERT INTO logs (level, message) VALUES ('WARN', 'unchanged');",
896                "logs",
897                &schema,
898                false,
899                SqlDialect::MySql,
900            )
901            .unwrap();
902
903        let (diff, _) = differ.compute_diff();
904        let logs = &diff.tables["logs"];
905        assert_eq!(logs.added_count, 0);
906        assert_eq!(logs.removed_count, 0);
907        assert_eq!(logs.modified_count, 0);
908    }
909}