Skip to main content

sql_splitter/validate/
mod.rs

1//! Validate module for SQL dump integrity checking.
2//!
3//! This module provides:
4//! - SQL syntax validation (via parser error detection)
5//! - DDL/DML consistency checks (INSERTs reference existing tables)
6//! - Duplicate primary key detection (all dialects)
7//! - FK referential integrity checking (all dialects)
8//! - Encoding validation (UTF-8)
9
10use crate::parser::{
11    determine_buffer_size, mysql_insert, postgres_copy, Parser, SqlDialect, StatementType,
12};
13use crate::progress::ProgressReader;
14use crate::schema::{Schema, SchemaBuilder, TableId};
15use crate::splitter::Compression;
16use ahash::{AHashMap, AHashSet};
17use schemars::JsonSchema;
18use serde::Serialize;
19use std::fmt;
20use std::fs::File;
21use std::hash::{Hash, Hasher};
22use std::io::Read;
23use std::path::PathBuf;
24use std::sync::Arc;
25
26/// Maximum number of issues to collect before stopping
27const MAX_ISSUES: usize = 1000;
28
29/// Issue severity level
30#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, JsonSchema)]
31#[serde(rename_all = "lowercase")]
32pub enum Severity {
33    Error,
34    Warning,
35    Info,
36}
37
38impl fmt::Display for Severity {
39    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40        match self {
41            Severity::Error => write!(f, "ERROR"),
42            Severity::Warning => write!(f, "WARNING"),
43            Severity::Info => write!(f, "INFO"),
44        }
45    }
46}
47
48/// Location in the SQL dump where an issue was found
49#[derive(Debug, Clone, Serialize, JsonSchema)]
50pub struct Location {
51    #[serde(skip_serializing_if = "Option::is_none")]
52    pub table: Option<String>,
53    #[serde(skip_serializing_if = "Option::is_none")]
54    pub statement_index: Option<u64>,
55}
56
57impl Location {
58    pub fn new() -> Self {
59        Self {
60            table: None,
61            statement_index: None,
62        }
63    }
64
65    pub fn with_table(mut self, table: impl Into<String>) -> Self {
66        self.table = Some(table.into());
67        self
68    }
69
70    pub fn with_statement(mut self, index: u64) -> Self {
71        self.statement_index = Some(index);
72        self
73    }
74}
75
76impl Default for Location {
77    fn default() -> Self {
78        Self::new()
79    }
80}
81
82/// A validation issue found in the SQL dump
83#[derive(Debug, Clone, Serialize, JsonSchema)]
84pub struct ValidationIssue {
85    pub code: &'static str,
86    pub severity: Severity,
87    pub message: String,
88    #[serde(skip_serializing_if = "Option::is_none")]
89    pub location: Option<Location>,
90}
91
92impl ValidationIssue {
93    pub fn error(code: &'static str, message: impl Into<String>) -> Self {
94        Self {
95            code,
96            severity: Severity::Error,
97            message: message.into(),
98            location: None,
99        }
100    }
101
102    pub fn warning(code: &'static str, message: impl Into<String>) -> Self {
103        Self {
104            code,
105            severity: Severity::Warning,
106            message: message.into(),
107            location: None,
108        }
109    }
110
111    pub fn info(code: &'static str, message: impl Into<String>) -> Self {
112        Self {
113            code,
114            severity: Severity::Info,
115            message: message.into(),
116            location: None,
117        }
118    }
119
120    pub fn with_location(mut self, location: Location) -> Self {
121        self.location = Some(location);
122        self
123    }
124}
125
126impl fmt::Display for ValidationIssue {
127    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
128        write!(f, "{} [{}]", self.severity, self.code)?;
129        if let Some(ref loc) = self.location {
130            if let Some(ref table) = loc.table {
131                write!(f, " table={}", table)?;
132            }
133            if let Some(stmt) = loc.statement_index {
134                write!(f, " stmt={}", stmt)?;
135            }
136        }
137        write!(f, ": {}", self.message)
138    }
139}
140
141/// Validation options
142#[derive(Debug, Clone)]
143pub struct ValidateOptions {
144    pub path: PathBuf,
145    pub dialect: Option<SqlDialect>,
146    pub progress: bool,
147    pub strict: bool,
148    pub json: bool,
149    pub max_rows_per_table: usize,
150    pub fk_checks_enabled: bool,
151    /// Optional global cap on tracked PK/FK keys for memory safety.
152    /// When exceeded, PK/FK checks are skipped for the remainder of the run.
153    /// If None, no limit is enforced (default).
154    pub max_pk_fk_keys: Option<usize>,
155}
156
157/// Validation summary with collected issues
158#[derive(Debug, Serialize, JsonSchema)]
159pub struct ValidationSummary {
160    pub dialect: String,
161    pub issues: Vec<ValidationIssue>,
162    pub summary: SummaryStats,
163    pub checks: CheckResults,
164}
165
166#[derive(Debug, Serialize, JsonSchema)]
167pub struct SummaryStats {
168    pub errors: usize,
169    pub warnings: usize,
170    pub info: usize,
171    pub tables_scanned: usize,
172    pub statements_scanned: u64,
173}
174
175#[derive(Debug, Serialize, JsonSchema)]
176pub struct CheckResults {
177    pub syntax: CheckStatus,
178    pub encoding: CheckStatus,
179    pub ddl_dml_consistency: CheckStatus,
180    pub pk_duplicates: CheckStatus,
181    pub fk_integrity: CheckStatus,
182}
183
184#[derive(Debug, Serialize, JsonSchema)]
185#[serde(rename_all = "lowercase")]
186pub enum CheckStatus {
187    Ok,
188    Failed(usize),
189    Skipped(String),
190}
191
192impl fmt::Display for CheckStatus {
193    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
194        match self {
195            CheckStatus::Ok => write!(f, "OK"),
196            CheckStatus::Failed(n) => write!(f, "{} issues", n),
197            CheckStatus::Skipped(reason) => write!(f, "Skipped ({})", reason),
198        }
199    }
200}
201
202impl ValidationSummary {
203    pub fn has_errors(&self) -> bool {
204        self.summary.errors > 0
205    }
206
207    pub fn has_warnings(&self) -> bool {
208        self.summary.warnings > 0
209    }
210}
211
212/// Compact primary/foreign key representation for duplicate and FK checks.
213/// We use a 64-bit hash; collision risk is negligible for realistic dumps.
214type PkHash = u64;
215
216/// Hash a list of PK/FK values into a compact 64-bit hash.
217/// Uses AHash for fast, high-quality hashing.
218fn hash_pk_values(values: &smallvec::SmallVec<[mysql_insert::PkValue; 2]>) -> PkHash {
219    let mut hasher = ahash::AHasher::default();
220
221    // Include arity (number of columns) in the hash to distinguish (1) from (1, NULL)
222    (values.len() as u8).hash(&mut hasher);
223
224    for v in values {
225        match v {
226            mysql_insert::PkValue::Int(i) => {
227                0u8.hash(&mut hasher);
228                i.hash(&mut hasher);
229            }
230            mysql_insert::PkValue::BigInt(i) => {
231                1u8.hash(&mut hasher);
232                i.hash(&mut hasher);
233            }
234            mysql_insert::PkValue::Text(s) => {
235                2u8.hash(&mut hasher);
236                s.hash(&mut hasher);
237            }
238            mysql_insert::PkValue::Null => {
239                3u8.hash(&mut hasher);
240            }
241        }
242    }
243
244    hasher.finish()
245}
246
247/// Pending FK check to be validated after all PKs are loaded.
248/// Uses compact hash representation to minimize memory usage.
249struct PendingFkCheck {
250    child_table_id: TableId,
251    parent_table_id: TableId,
252    fk_hash: PkHash,
253    stmt_idx: u64,
254}
255
256/// Per-table tracking state for data checks.
257/// Uses hashed PK values to minimize memory usage.
258struct TableState {
259    row_count: u64,
260    /// Set of hashed PKs for duplicate and FK parent existence checks.
261    /// When None, PK/FK checks for this table are skipped (due to row or memory limits).
262    pk_values: Option<AHashSet<PkHash>>,
263    pk_column_indices: Vec<usize>,
264    pk_duplicates: u64,
265    fk_missing_parents: u64,
266}
267
268impl TableState {
269    fn new() -> Self {
270        Self {
271            row_count: 0,
272            pk_values: Some(AHashSet::new()),
273            pk_column_indices: Vec::new(),
274            pk_duplicates: 0,
275            fk_missing_parents: 0,
276        }
277    }
278
279    fn with_pk_columns(mut self, indices: Vec<usize>) -> Self {
280        self.pk_column_indices = indices;
281        self
282    }
283}
284
285/// SQL dump validator
286pub struct Validator {
287    options: ValidateOptions,
288    issues: Vec<ValidationIssue>,
289    dialect: SqlDialect,
290
291    // DDL/DML tracking
292    tables_from_ddl: AHashSet<String>,
293    tables_from_dml: Vec<(String, u64)>, // (table_name, statement_index)
294
295    // Schema for MySQL PK/FK checks
296    schema_builder: SchemaBuilder,
297    schema: Option<Schema>,
298
299    // Per-table state for data checks
300    table_states: AHashMap<TableId, TableState>,
301
302    // Pending FK checks (deferred until all PKs are loaded)
303    pending_fk_checks: Vec<PendingFkCheck>,
304
305    // Progress callback for byte-based progress tracking (Arc for reuse across passes)
306    progress_fn: Option<Arc<dyn Fn(u64) + Send + Sync>>,
307
308    // Counters
309    statement_count: u64,
310    syntax_errors: usize,
311    encoding_warnings: usize,
312    ddl_dml_errors: usize,
313    pk_errors: usize,
314    fk_errors: usize,
315
316    // Memory tracking for PK/FK checks
317    tracked_pk_count: usize,
318    tracked_fk_count: usize,
319    pk_fk_checks_disabled_due_to_memory: bool,
320
321    // PostgreSQL COPY context: (table_name, column_order, table_id)
322    current_copy_context: Option<(String, Vec<String>, TableId)>,
323}
324
325impl Validator {
326    pub fn new(options: ValidateOptions) -> Self {
327        Self {
328            dialect: options.dialect.unwrap_or(SqlDialect::MySql),
329            options,
330            issues: Vec::new(),
331            tables_from_ddl: AHashSet::new(),
332            tables_from_dml: Vec::new(),
333            schema_builder: SchemaBuilder::new(),
334            schema: None,
335            table_states: AHashMap::new(),
336            pending_fk_checks: Vec::new(),
337            progress_fn: None,
338            statement_count: 0,
339            syntax_errors: 0,
340            encoding_warnings: 0,
341            ddl_dml_errors: 0,
342            pk_errors: 0,
343            fk_errors: 0,
344            tracked_pk_count: 0,
345            tracked_fk_count: 0,
346            pk_fk_checks_disabled_due_to_memory: false,
347            current_copy_context: None,
348        }
349    }
350
351    /// Set a progress callback for byte-based progress tracking.
352    /// The callback receives cumulative bytes read across both validation passes.
353    pub fn with_progress<F>(mut self, f: F) -> Self
354    where
355        F: Fn(u64) + Send + Sync + 'static,
356    {
357        self.progress_fn = Some(Arc::new(f));
358        self
359    }
360
361    fn add_issue(&mut self, issue: ValidationIssue) {
362        if self.issues.len() >= MAX_ISSUES {
363            return;
364        }
365
366        match issue.severity {
367            Severity::Error => match issue.code {
368                "SYNTAX" => self.syntax_errors += 1,
369                "DDL_MISSING_TABLE" => self.ddl_dml_errors += 1,
370                "DUPLICATE_PK" => self.pk_errors += 1,
371                "FK_MISSING_PARENT" => self.fk_errors += 1,
372                _ => {}
373            },
374            Severity::Warning => {
375                if issue.code == "ENCODING" {
376                    self.encoding_warnings += 1;
377                }
378            }
379            Severity::Info => {}
380        }
381
382        self.issues.push(issue);
383    }
384
385    /// Check if we've exceeded the memory budget for PK/FK tracking.
386    /// If so, disable further checks and free existing state.
387    fn enforce_pk_fk_memory_budget(&mut self) {
388        if self.pk_fk_checks_disabled_due_to_memory {
389            return;
390        }
391
392        let Some(limit) = self.options.max_pk_fk_keys else {
393            return;
394        };
395
396        let total_tracked = self.tracked_pk_count + self.tracked_fk_count;
397        if total_tracked > limit {
398            self.pk_fk_checks_disabled_due_to_memory = true;
399
400            // Drop existing state to free memory
401            for state in self.table_states.values_mut() {
402                state.pk_values = None;
403            }
404            self.pending_fk_checks.clear();
405            self.pending_fk_checks.shrink_to_fit();
406
407            self.add_issue(ValidationIssue::warning(
408                "PK_FK_CHECKS_SKIPPED_MEMORY",
409                format!(
410                    "Skipping PK/FK checks after tracking {} keys (memory limit of {} exceeded)",
411                    total_tracked, limit
412                ),
413            ));
414        }
415    }
416
417    pub fn validate(mut self) -> anyhow::Result<ValidationSummary> {
418        let file = File::open(&self.options.path)?;
419        let file_size = file.metadata()?.len();
420        let buffer_size = determine_buffer_size(file_size);
421
422        // Pass 1 reports bytes as 0 to file_size/2 (first half of progress bar)
423        let compression = Compression::from_path(&self.options.path);
424        let reader: Box<dyn Read> = if let Some(ref cb) = self.progress_fn {
425            let cb = Arc::clone(cb);
426            let progress_reader = ProgressReader::new(file, move |bytes| {
427                // Scale to first half: 0% to 50%
428                cb(bytes / 2)
429            });
430            compression.wrap_reader(Box::new(progress_reader))?
431        } else {
432            compression.wrap_reader(Box::new(file))?
433        };
434
435        let mut parser = Parser::with_dialect(reader, buffer_size, self.dialect);
436
437        // Pass 1: Build schema and check DDL/DML consistency
438        loop {
439            match parser.read_statement() {
440                Ok(Some(stmt)) => {
441                    self.statement_count += 1;
442                    self.process_statement(&stmt);
443                }
444                Ok(None) => break,
445                Err(e) => {
446                    self.add_issue(
447                        ValidationIssue::error("SYNTAX", format!("Parser error: {}", e))
448                            .with_location(
449                                Location::new().with_statement(self.statement_count + 1),
450                            ),
451                    );
452                    break;
453                }
454            }
455        }
456
457        // Check for DML referencing missing tables - collect issues first, then add them
458        let missing_table_issues: Vec<_> = self
459            .tables_from_dml
460            .iter()
461            .filter(|(table, _)| {
462                let table_lower = table.to_lowercase();
463                !self
464                    .tables_from_ddl
465                    .iter()
466                    .any(|t| t.to_lowercase() == table_lower)
467            })
468            .map(|(table, stmt_idx)| {
469                ValidationIssue::error(
470                    "DDL_MISSING_TABLE",
471                    format!(
472                        "INSERT/COPY references table '{}' with no CREATE TABLE",
473                        table
474                    ),
475                )
476                .with_location(Location::new().with_table(table).with_statement(*stmt_idx))
477            })
478            .collect();
479
480        for issue in missing_table_issues {
481            self.add_issue(issue);
482        }
483
484        // Finalize schema and resolve FK references for data checks (all dialects)
485        if self.options.fk_checks_enabled {
486            self.schema = Some(self.schema_builder.build());
487            self.schema_builder = SchemaBuilder::new(); // Reset to avoid double use
488            self.initialize_table_states();
489        }
490
491        // Pass 2: Data checks (PK + collect FK refs) - requires re-reading the file
492        let schema_not_empty = self.schema.as_ref().is_some_and(|s| !s.is_empty());
493        if self.options.fk_checks_enabled && schema_not_empty {
494            self.run_data_checks()?;
495            // Now that all PKs are loaded, validate the collected FK references
496            self.validate_pending_fk_checks();
497        }
498
499        Ok(self.build_summary())
500    }
501
502    fn process_statement(&mut self, stmt: &[u8]) {
503        // Check encoding
504        if std::str::from_utf8(stmt).is_err() {
505            self.add_issue(
506                ValidationIssue::warning("ENCODING", "Statement contains invalid UTF-8 bytes")
507                    .with_location(Location::new().with_statement(self.statement_count)),
508            );
509        }
510
511        let (stmt_type, table_name) =
512            Parser::<&[u8]>::parse_statement_with_dialect(stmt, self.dialect);
513
514        match stmt_type {
515            StatementType::CreateTable => {
516                if !table_name.is_empty() {
517                    self.tables_from_ddl.insert(table_name.clone());
518
519                    // Parse CREATE TABLE for schema info (all dialects supported)
520                    if let Ok(stmt_str) = std::str::from_utf8(stmt) {
521                        self.schema_builder.parse_create_table(stmt_str);
522                    }
523                }
524            }
525            StatementType::AlterTable => {
526                // Parse ALTER TABLE for FK constraints (all dialects supported)
527                if let Ok(stmt_str) = std::str::from_utf8(stmt) {
528                    self.schema_builder.parse_alter_table(stmt_str);
529                }
530            }
531            StatementType::Insert | StatementType::Copy => {
532                if !table_name.is_empty() {
533                    self.tables_from_dml
534                        .push((table_name, self.statement_count));
535                }
536            }
537            StatementType::Unknown => {
538                // Could be a session command or comment - not an error
539            }
540            _ => {}
541        }
542    }
543
544    fn initialize_table_states(&mut self) {
545        let schema = match &self.schema {
546            Some(s) => s,
547            None => return,
548        };
549
550        for table_schema in schema.iter() {
551            let pk_indices: Vec<usize> = table_schema
552                .primary_key
553                .iter()
554                .map(|col_id| col_id.0 as usize)
555                .collect();
556
557            let state = TableState::new().with_pk_columns(pk_indices);
558            self.table_states.insert(table_schema.id, state);
559        }
560    }
561
562    fn run_data_checks(&mut self) -> anyhow::Result<()> {
563        let file = File::open(&self.options.path)?;
564        let file_size = file.metadata()?.len();
565        let buffer_size = determine_buffer_size(file_size);
566
567        // Pass 2 reports bytes as file_size/2 to file_size (second half of progress bar)
568        let compression = Compression::from_path(&self.options.path);
569        let reader: Box<dyn Read> = if let Some(ref cb) = self.progress_fn {
570            let cb = Arc::clone(cb);
571            let progress_reader = ProgressReader::new(file, move |bytes| {
572                // Scale to second half: 50% to 100%
573                cb(file_size / 2 + bytes / 2)
574            });
575            compression.wrap_reader(Box::new(progress_reader))?
576        } else {
577            compression.wrap_reader(Box::new(file))?
578        };
579
580        let mut parser = Parser::with_dialect(reader, buffer_size, self.dialect);
581        let mut stmt_count: u64 = 0;
582
583        // Reset COPY context for this pass
584        self.current_copy_context = None;
585
586        while let Some(stmt) = parser.read_statement()? {
587            stmt_count += 1;
588
589            let (stmt_type, table_name) =
590                Parser::<&[u8]>::parse_statement_with_dialect(&stmt, self.dialect);
591
592            // Handle PostgreSQL COPY data (separate statement from header)
593            if self.dialect == SqlDialect::Postgres && stmt_type == StatementType::Unknown {
594                // Check if this looks like COPY data (ends with \.)
595                if stmt.ends_with(b"\\.\n") || stmt.ends_with(b"\\.\r\n") {
596                    if let Some((ref copy_table, ref column_order, copy_table_id)) =
597                        self.current_copy_context.clone()
598                    {
599                        self.check_copy_data(
600                            &stmt,
601                            copy_table_id,
602                            copy_table,
603                            column_order.clone(),
604                            stmt_count,
605                        );
606                    }
607                }
608                self.current_copy_context = None;
609                continue;
610            }
611
612            // Get table_id without holding a borrow on self.schema
613            let table_id = match &self.schema {
614                Some(s) => match s.get_table_id(&table_name) {
615                    Some(id) => id,
616                    None => continue,
617                },
618                None => continue,
619            };
620
621            match stmt_type {
622                StatementType::Insert => {
623                    // MySQL and SQLite use INSERT VALUES syntax
624                    self.check_insert_statement(&stmt, table_id, &table_name, stmt_count);
625                }
626                StatementType::Copy => {
627                    // For PostgreSQL COPY, the data comes in the next statement
628                    // Save context for processing the data statement
629                    let header = String::from_utf8_lossy(&stmt);
630                    let column_order = postgres_copy::parse_copy_columns(&header);
631                    self.current_copy_context = Some((table_name.clone(), column_order, table_id));
632                }
633                _ => continue,
634            }
635        }
636
637        Ok(())
638    }
639
640    /// Check rows from a MySQL/SQLite INSERT statement
641    fn check_insert_statement(
642        &mut self,
643        stmt: &[u8],
644        table_id: TableId,
645        table_name: &str,
646        stmt_count: u64,
647    ) {
648        let table_schema = match &self.schema {
649            Some(s) => match s.table(table_id) {
650                Some(ts) => ts,
651                None => return,
652            },
653            None => return,
654        };
655
656        // Parse rows from INSERT using the schema (works for MySQL and SQLite)
657        let rows = match mysql_insert::parse_insert_rows_with(
658            stmt,
659            table_schema,
660            self.dialect,
661            mysql_insert::RowExtraction::PkFk,
662        ) {
663            Ok(r) => r,
664            Err(_) => return,
665        };
666
667        for row in rows {
668            self.check_mysql_row(table_id, table_name, &row, stmt_count);
669        }
670    }
671
672    /// Check rows from a PostgreSQL COPY statement
673    #[allow(dead_code)]
674    fn check_copy_statement(
675        &mut self,
676        stmt: &[u8],
677        table_id: TableId,
678        table_name: &str,
679        stmt_count: u64,
680    ) {
681        // Find the COPY header line and the data section
682        let stmt_str = match std::str::from_utf8(stmt) {
683            Ok(s) => s,
684            Err(_) => return,
685        };
686
687        // Find the data section (after the header line ending with "FROM stdin;")
688        let data_start = if let Some(pos) = stmt_str.find("FROM stdin;") {
689            pos + "FROM stdin;".len()
690        } else if let Some(pos) = stmt_str.find("from stdin;") {
691            pos + "from stdin;".len()
692        } else {
693            return;
694        };
695
696        // Skip any whitespace/newlines after the header
697        let data_section = stmt_str[data_start..].trim_start();
698        if data_section.is_empty() {
699            return;
700        }
701
702        // Parse column list from the header
703        let header = &stmt_str[..data_start];
704        let column_order = postgres_copy::parse_copy_columns(header);
705
706        // Get table schema
707        let table_schema = match &self.schema {
708            Some(s) => match s.table(table_id) {
709                Some(ts) => ts,
710                None => return,
711            },
712            None => return,
713        };
714
715        // Parse the COPY data rows
716        let rows = match postgres_copy::parse_postgres_copy_rows_with(
717            data_section.as_bytes(),
718            table_schema,
719            column_order,
720            mysql_insert::RowExtraction::PkFk,
721        ) {
722            Ok(r) => r,
723            Err(_) => return,
724        };
725
726        for row in rows {
727            self.check_copy_row(table_id, table_name, &row, stmt_count);
728        }
729    }
730
731    /// Check rows from PostgreSQL COPY data (separate statement from header)
732    fn check_copy_data(
733        &mut self,
734        data_stmt: &[u8],
735        table_id: TableId,
736        table_name: &str,
737        column_order: Vec<String>,
738        stmt_count: u64,
739    ) {
740        // The data_stmt contains the raw COPY data lines (may have leading newline)
741        // Strip leading whitespace/newlines
742        let data: Vec<u8> = data_stmt
743            .iter()
744            .skip_while(|&&b| b == b'\n' || b == b'\r' || b == b' ' || b == b'\t')
745            .cloned()
746            .collect();
747
748        if data.is_empty() {
749            return;
750        }
751
752        // Get table schema
753        let table_schema = match &self.schema {
754            Some(s) => match s.table(table_id) {
755                Some(ts) => ts,
756                None => return,
757            },
758            None => return,
759        };
760
761        // Parse the COPY data rows
762        let rows = match postgres_copy::parse_postgres_copy_rows_with(
763            &data,
764            table_schema,
765            column_order,
766            mysql_insert::RowExtraction::PkFk,
767        ) {
768            Ok(r) => r,
769            Err(_) => return,
770        };
771
772        for row in rows {
773            self.check_copy_row(table_id, table_name, &row, stmt_count);
774        }
775    }
776
777    /// Check a row from MySQL INSERT or SQLite INSERT
778    fn check_mysql_row(
779        &mut self,
780        table_id: TableId,
781        table_name: &str,
782        row: &mysql_insert::ParsedRow,
783        stmt_idx: u64,
784    ) {
785        self.check_row_common(
786            table_id,
787            table_name,
788            row.pk.as_ref(),
789            &row.fk_values,
790            stmt_idx,
791        );
792    }
793
794    /// Check a row from PostgreSQL COPY
795    fn check_copy_row(
796        &mut self,
797        table_id: TableId,
798        table_name: &str,
799        row: &postgres_copy::ParsedCopyRow,
800        stmt_idx: u64,
801    ) {
802        self.check_row_common(
803            table_id,
804            table_name,
805            row.pk.as_ref(),
806            &row.fk_values,
807            stmt_idx,
808        );
809    }
810
811    /// Common row checking logic for all dialects
812    fn check_row_common(
813        &mut self,
814        table_id: TableId,
815        table_name: &str,
816        pk: Option<&smallvec::SmallVec<[mysql_insert::PkValue; 2]>>,
817        fk_values: &[(
818            mysql_insert::FkRef,
819            smallvec::SmallVec<[mysql_insert::PkValue; 2]>,
820        )],
821        stmt_idx: u64,
822    ) {
823        // Skip if memory budget exceeded
824        if self.pk_fk_checks_disabled_due_to_memory {
825            return;
826        }
827
828        let max_rows = self.options.max_rows_per_table as u64;
829
830        let state = match self.table_states.get_mut(&table_id) {
831            Some(s) => s,
832            None => return,
833        };
834
835        state.row_count += 1;
836
837        // Check if we've exceeded max rows for this table
838        if state.row_count > max_rows {
839            if state.pk_values.is_some() {
840                state.pk_values = None;
841                self.add_issue(
842                    ValidationIssue::warning(
843                        "PK_CHECK_SKIPPED",
844                        format!(
845                            "Skipping PK/FK checks for table '{}' after {} rows (increase --max-rows-per-table)",
846                            table_name, max_rows
847                        ),
848                    )
849                    .with_location(Location::new().with_table(table_name)),
850                );
851            }
852            return;
853        }
854
855        // PK duplicate check using hash-based storage (8 bytes per key instead of full values)
856        if let Some(pk_values) = pk {
857            if let Some(ref mut pk_set) = state.pk_values {
858                let pk_hash = hash_pk_values(pk_values);
859
860                if pk_set.insert(pk_hash) {
861                    // Only count unique keys
862                    self.tracked_pk_count += 1;
863                    self.enforce_pk_fk_memory_budget();
864                } else {
865                    // Duplicate detected
866                    state.pk_duplicates += 1;
867
868                    // Build human-readable display on demand (duplicates are rare)
869                    let pk_display: String = pk_values
870                        .iter()
871                        .map(|v| match v {
872                            mysql_insert::PkValue::Int(i) => i.to_string(),
873                            mysql_insert::PkValue::BigInt(i) => i.to_string(),
874                            mysql_insert::PkValue::Text(s) => s.to_string(),
875                            mysql_insert::PkValue::Null => "NULL".to_string(),
876                        })
877                        .collect::<Vec<_>>()
878                        .join(", ");
879
880                    self.add_issue(
881                        ValidationIssue::error(
882                            "DUPLICATE_PK",
883                            format!(
884                                "Duplicate primary key in table '{}': ({})",
885                                table_name, pk_display
886                            ),
887                        )
888                        .with_location(
889                            Location::new()
890                                .with_table(table_name)
891                                .with_statement(stmt_idx),
892                        ),
893                    );
894                }
895            }
896        }
897
898        // Skip FK collection if checks are disabled
899        if self.pk_fk_checks_disabled_due_to_memory {
900            return;
901        }
902
903        // Collect FK references for deferred validation (after all PKs are loaded)
904        // First, gather the FK checks into a temp vec to avoid borrow issues
905        let new_fk_checks: Vec<PendingFkCheck> = {
906            let schema = match &self.schema {
907                Some(s) => s,
908                None => return,
909            };
910
911            let table_schema = match schema.table(table_id) {
912                Some(t) => t,
913                None => return,
914            };
915
916            fk_values
917                .iter()
918                .filter_map(|(fk_ref, fk_vals)| {
919                    // Skip if all FK values are NULL (nullable FK)
920                    if fk_vals.iter().all(|v| v.is_null()) {
921                        return None;
922                    }
923
924                    let fk_def = table_schema.foreign_keys.get(fk_ref.fk_index as usize)?;
925                    let parent_table_id = fk_def.referenced_table_id?;
926
927                    // Store only the hash, not full values - saves significant memory
928                    let fk_hash = hash_pk_values(fk_vals);
929
930                    Some(PendingFkCheck {
931                        child_table_id: table_id,
932                        parent_table_id,
933                        fk_hash,
934                        stmt_idx,
935                    })
936                })
937                .collect()
938        };
939
940        // Now add the FK checks and update memory tracking
941        let new_count = new_fk_checks.len();
942        self.pending_fk_checks.extend(new_fk_checks);
943        self.tracked_fk_count += new_count;
944
945        if new_count > 0 {
946            self.enforce_pk_fk_memory_budget();
947        }
948    }
949
950    /// Validate all collected FK references after all PKs are loaded
951    fn validate_pending_fk_checks(&mut self) {
952        for check in std::mem::take(&mut self.pending_fk_checks) {
953            let parent_has_pk = self
954                .table_states
955                .get(&check.parent_table_id)
956                .and_then(|s| s.pk_values.as_ref())
957                .is_some_and(|set| set.contains(&check.fk_hash));
958
959            if !parent_has_pk {
960                let state = match self.table_states.get_mut(&check.child_table_id) {
961                    Some(s) => s,
962                    None => continue,
963                };
964                state.fk_missing_parents += 1;
965
966                // Only add issue for first few violations per table
967                if state.fk_missing_parents <= 5 {
968                    // Derive table names from the schema (not stored per FK to save memory)
969                    let (child_name, parent_name) = if let Some(schema) = &self.schema {
970                        let child = schema
971                            .table(check.child_table_id)
972                            .map(|t| t.name.clone())
973                            .unwrap_or_else(|| "<unknown>".to_string());
974                        let parent = schema
975                            .table(check.parent_table_id)
976                            .map(|t| t.name.clone())
977                            .unwrap_or_else(|| "<unknown>".to_string());
978                        (child, parent)
979                    } else {
980                        ("<unknown>".to_string(), "<unknown>".to_string())
981                    };
982
983                    self.add_issue(
984                        ValidationIssue::error(
985                            "FK_MISSING_PARENT",
986                            format!(
987                                "FK violation in '{}': references missing row in '{}'",
988                                child_name, parent_name
989                            ),
990                        )
991                        .with_location(
992                            Location::new()
993                                .with_table(child_name)
994                                .with_statement(check.stmt_idx),
995                        ),
996                    );
997                }
998            }
999        }
1000    }
1001
1002    fn build_summary(&self) -> ValidationSummary {
1003        let errors = self
1004            .issues
1005            .iter()
1006            .filter(|i| matches!(i.severity, Severity::Error))
1007            .count();
1008        let warnings = self
1009            .issues
1010            .iter()
1011            .filter(|i| matches!(i.severity, Severity::Warning))
1012            .count();
1013        let info = self
1014            .issues
1015            .iter()
1016            .filter(|i| matches!(i.severity, Severity::Info))
1017            .count();
1018
1019        let syntax_status = if self.syntax_errors > 0 {
1020            CheckStatus::Failed(self.syntax_errors)
1021        } else {
1022            CheckStatus::Ok
1023        };
1024
1025        let encoding_status = if self.encoding_warnings > 0 {
1026            CheckStatus::Failed(self.encoding_warnings)
1027        } else {
1028            CheckStatus::Ok
1029        };
1030
1031        let ddl_dml_status = if self.ddl_dml_errors > 0 {
1032            CheckStatus::Failed(self.ddl_dml_errors)
1033        } else {
1034            CheckStatus::Ok
1035        };
1036
1037        let pk_status = if !self.options.fk_checks_enabled {
1038            CheckStatus::Skipped("--no-fk-checks".to_string())
1039        } else if self.pk_fk_checks_disabled_due_to_memory {
1040            CheckStatus::Skipped("memory limit exceeded".to_string())
1041        } else if self.pk_errors > 0 {
1042            CheckStatus::Failed(self.pk_errors)
1043        } else {
1044            CheckStatus::Ok
1045        };
1046
1047        let fk_status = if !self.options.fk_checks_enabled {
1048            CheckStatus::Skipped("--no-fk-checks".to_string())
1049        } else if self.pk_fk_checks_disabled_due_to_memory {
1050            CheckStatus::Skipped("memory limit exceeded".to_string())
1051        } else if self.fk_errors > 0 {
1052            CheckStatus::Failed(self.fk_errors)
1053        } else {
1054            CheckStatus::Ok
1055        };
1056
1057        ValidationSummary {
1058            dialect: self.dialect.to_string(),
1059            issues: self.issues.clone(),
1060            summary: SummaryStats {
1061                errors,
1062                warnings,
1063                info,
1064                tables_scanned: self.tables_from_ddl.len(),
1065                statements_scanned: self.statement_count,
1066            },
1067            checks: CheckResults {
1068                syntax: syntax_status,
1069                encoding: encoding_status,
1070                ddl_dml_consistency: ddl_dml_status,
1071                pk_duplicates: pk_status,
1072                fk_integrity: fk_status,
1073            },
1074        }
1075    }
1076}