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_mysql_insert_rows(stmt, table_schema) {
658            Ok(r) => r,
659            Err(_) => return,
660        };
661
662        for row in rows {
663            self.check_mysql_row(table_id, table_name, &row, stmt_count);
664        }
665    }
666
667    /// Check rows from a PostgreSQL COPY statement
668    #[allow(dead_code)]
669    fn check_copy_statement(
670        &mut self,
671        stmt: &[u8],
672        table_id: TableId,
673        table_name: &str,
674        stmt_count: u64,
675    ) {
676        // Find the COPY header line and the data section
677        let stmt_str = match std::str::from_utf8(stmt) {
678            Ok(s) => s,
679            Err(_) => return,
680        };
681
682        // Find the data section (after the header line ending with "FROM stdin;")
683        let data_start = if let Some(pos) = stmt_str.find("FROM stdin;") {
684            pos + "FROM stdin;".len()
685        } else if let Some(pos) = stmt_str.find("from stdin;") {
686            pos + "from stdin;".len()
687        } else {
688            return;
689        };
690
691        // Skip any whitespace/newlines after the header
692        let data_section = stmt_str[data_start..].trim_start();
693        if data_section.is_empty() {
694            return;
695        }
696
697        // Parse column list from the header
698        let header = &stmt_str[..data_start];
699        let column_order = postgres_copy::parse_copy_columns(header);
700
701        // Get table schema
702        let table_schema = match &self.schema {
703            Some(s) => match s.table(table_id) {
704                Some(ts) => ts,
705                None => return,
706            },
707            None => return,
708        };
709
710        // Parse the COPY data rows
711        let rows = match postgres_copy::parse_postgres_copy_rows(
712            data_section.as_bytes(),
713            table_schema,
714            column_order,
715        ) {
716            Ok(r) => r,
717            Err(_) => return,
718        };
719
720        for row in rows {
721            self.check_copy_row(table_id, table_name, &row, stmt_count);
722        }
723    }
724
725    /// Check rows from PostgreSQL COPY data (separate statement from header)
726    fn check_copy_data(
727        &mut self,
728        data_stmt: &[u8],
729        table_id: TableId,
730        table_name: &str,
731        column_order: Vec<String>,
732        stmt_count: u64,
733    ) {
734        // The data_stmt contains the raw COPY data lines (may have leading newline)
735        // Strip leading whitespace/newlines
736        let data: Vec<u8> = data_stmt
737            .iter()
738            .skip_while(|&&b| b == b'\n' || b == b'\r' || b == b' ' || b == b'\t')
739            .cloned()
740            .collect();
741
742        if data.is_empty() {
743            return;
744        }
745
746        // Get table schema
747        let table_schema = match &self.schema {
748            Some(s) => match s.table(table_id) {
749                Some(ts) => ts,
750                None => return,
751            },
752            None => return,
753        };
754
755        // Parse the COPY data rows
756        let rows = match postgres_copy::parse_postgres_copy_rows(&data, table_schema, column_order)
757        {
758            Ok(r) => r,
759            Err(_) => return,
760        };
761
762        for row in rows {
763            self.check_copy_row(table_id, table_name, &row, stmt_count);
764        }
765    }
766
767    /// Check a row from MySQL INSERT or SQLite INSERT
768    fn check_mysql_row(
769        &mut self,
770        table_id: TableId,
771        table_name: &str,
772        row: &mysql_insert::ParsedRow,
773        stmt_idx: u64,
774    ) {
775        self.check_row_common(
776            table_id,
777            table_name,
778            row.pk.as_ref(),
779            &row.fk_values,
780            stmt_idx,
781        );
782    }
783
784    /// Check a row from PostgreSQL COPY
785    fn check_copy_row(
786        &mut self,
787        table_id: TableId,
788        table_name: &str,
789        row: &postgres_copy::ParsedCopyRow,
790        stmt_idx: u64,
791    ) {
792        self.check_row_common(
793            table_id,
794            table_name,
795            row.pk.as_ref(),
796            &row.fk_values,
797            stmt_idx,
798        );
799    }
800
801    /// Common row checking logic for all dialects
802    fn check_row_common(
803        &mut self,
804        table_id: TableId,
805        table_name: &str,
806        pk: Option<&smallvec::SmallVec<[mysql_insert::PkValue; 2]>>,
807        fk_values: &[(
808            mysql_insert::FkRef,
809            smallvec::SmallVec<[mysql_insert::PkValue; 2]>,
810        )],
811        stmt_idx: u64,
812    ) {
813        // Skip if memory budget exceeded
814        if self.pk_fk_checks_disabled_due_to_memory {
815            return;
816        }
817
818        let max_rows = self.options.max_rows_per_table as u64;
819
820        let state = match self.table_states.get_mut(&table_id) {
821            Some(s) => s,
822            None => return,
823        };
824
825        state.row_count += 1;
826
827        // Check if we've exceeded max rows for this table
828        if state.row_count > max_rows {
829            if state.pk_values.is_some() {
830                state.pk_values = None;
831                self.add_issue(
832                    ValidationIssue::warning(
833                        "PK_CHECK_SKIPPED",
834                        format!(
835                            "Skipping PK/FK checks for table '{}' after {} rows (increase --max-rows-per-table)",
836                            table_name, max_rows
837                        ),
838                    )
839                    .with_location(Location::new().with_table(table_name)),
840                );
841            }
842            return;
843        }
844
845        // PK duplicate check using hash-based storage (8 bytes per key instead of full values)
846        if let Some(pk_values) = pk {
847            if let Some(ref mut pk_set) = state.pk_values {
848                let pk_hash = hash_pk_values(pk_values);
849
850                if pk_set.insert(pk_hash) {
851                    // Only count unique keys
852                    self.tracked_pk_count += 1;
853                    self.enforce_pk_fk_memory_budget();
854                } else {
855                    // Duplicate detected
856                    state.pk_duplicates += 1;
857
858                    // Build human-readable display on demand (duplicates are rare)
859                    let pk_display: String = pk_values
860                        .iter()
861                        .map(|v| match v {
862                            mysql_insert::PkValue::Int(i) => i.to_string(),
863                            mysql_insert::PkValue::BigInt(i) => i.to_string(),
864                            mysql_insert::PkValue::Text(s) => s.to_string(),
865                            mysql_insert::PkValue::Null => "NULL".to_string(),
866                        })
867                        .collect::<Vec<_>>()
868                        .join(", ");
869
870                    self.add_issue(
871                        ValidationIssue::error(
872                            "DUPLICATE_PK",
873                            format!(
874                                "Duplicate primary key in table '{}': ({})",
875                                table_name, pk_display
876                            ),
877                        )
878                        .with_location(
879                            Location::new()
880                                .with_table(table_name)
881                                .with_statement(stmt_idx),
882                        ),
883                    );
884                }
885            }
886        }
887
888        // Skip FK collection if checks are disabled
889        if self.pk_fk_checks_disabled_due_to_memory {
890            return;
891        }
892
893        // Collect FK references for deferred validation (after all PKs are loaded)
894        // First, gather the FK checks into a temp vec to avoid borrow issues
895        let new_fk_checks: Vec<PendingFkCheck> = {
896            let schema = match &self.schema {
897                Some(s) => s,
898                None => return,
899            };
900
901            let table_schema = match schema.table(table_id) {
902                Some(t) => t,
903                None => return,
904            };
905
906            fk_values
907                .iter()
908                .filter_map(|(fk_ref, fk_vals)| {
909                    // Skip if all FK values are NULL (nullable FK)
910                    if fk_vals.iter().all(|v| v.is_null()) {
911                        return None;
912                    }
913
914                    let fk_def = table_schema.foreign_keys.get(fk_ref.fk_index as usize)?;
915                    let parent_table_id = fk_def.referenced_table_id?;
916
917                    // Store only the hash, not full values - saves significant memory
918                    let fk_hash = hash_pk_values(fk_vals);
919
920                    Some(PendingFkCheck {
921                        child_table_id: table_id,
922                        parent_table_id,
923                        fk_hash,
924                        stmt_idx,
925                    })
926                })
927                .collect()
928        };
929
930        // Now add the FK checks and update memory tracking
931        let new_count = new_fk_checks.len();
932        self.pending_fk_checks.extend(new_fk_checks);
933        self.tracked_fk_count += new_count;
934
935        if new_count > 0 {
936            self.enforce_pk_fk_memory_budget();
937        }
938    }
939
940    /// Validate all collected FK references after all PKs are loaded
941    fn validate_pending_fk_checks(&mut self) {
942        for check in std::mem::take(&mut self.pending_fk_checks) {
943            let parent_has_pk = self
944                .table_states
945                .get(&check.parent_table_id)
946                .and_then(|s| s.pk_values.as_ref())
947                .is_some_and(|set| set.contains(&check.fk_hash));
948
949            if !parent_has_pk {
950                let state = match self.table_states.get_mut(&check.child_table_id) {
951                    Some(s) => s,
952                    None => continue,
953                };
954                state.fk_missing_parents += 1;
955
956                // Only add issue for first few violations per table
957                if state.fk_missing_parents <= 5 {
958                    // Derive table names from the schema (not stored per FK to save memory)
959                    let (child_name, parent_name) = if let Some(schema) = &self.schema {
960                        let child = schema
961                            .table(check.child_table_id)
962                            .map(|t| t.name.clone())
963                            .unwrap_or_else(|| "<unknown>".to_string());
964                        let parent = schema
965                            .table(check.parent_table_id)
966                            .map(|t| t.name.clone())
967                            .unwrap_or_else(|| "<unknown>".to_string());
968                        (child, parent)
969                    } else {
970                        ("<unknown>".to_string(), "<unknown>".to_string())
971                    };
972
973                    self.add_issue(
974                        ValidationIssue::error(
975                            "FK_MISSING_PARENT",
976                            format!(
977                                "FK violation in '{}': references missing row in '{}'",
978                                child_name, parent_name
979                            ),
980                        )
981                        .with_location(
982                            Location::new()
983                                .with_table(child_name)
984                                .with_statement(check.stmt_idx),
985                        ),
986                    );
987                }
988            }
989        }
990    }
991
992    fn build_summary(&self) -> ValidationSummary {
993        let errors = self
994            .issues
995            .iter()
996            .filter(|i| matches!(i.severity, Severity::Error))
997            .count();
998        let warnings = self
999            .issues
1000            .iter()
1001            .filter(|i| matches!(i.severity, Severity::Warning))
1002            .count();
1003        let info = self
1004            .issues
1005            .iter()
1006            .filter(|i| matches!(i.severity, Severity::Info))
1007            .count();
1008
1009        let syntax_status = if self.syntax_errors > 0 {
1010            CheckStatus::Failed(self.syntax_errors)
1011        } else {
1012            CheckStatus::Ok
1013        };
1014
1015        let encoding_status = if self.encoding_warnings > 0 {
1016            CheckStatus::Failed(self.encoding_warnings)
1017        } else {
1018            CheckStatus::Ok
1019        };
1020
1021        let ddl_dml_status = if self.ddl_dml_errors > 0 {
1022            CheckStatus::Failed(self.ddl_dml_errors)
1023        } else {
1024            CheckStatus::Ok
1025        };
1026
1027        let pk_status = if !self.options.fk_checks_enabled {
1028            CheckStatus::Skipped("--no-fk-checks".to_string())
1029        } else if self.pk_fk_checks_disabled_due_to_memory {
1030            CheckStatus::Skipped("memory limit exceeded".to_string())
1031        } else if self.pk_errors > 0 {
1032            CheckStatus::Failed(self.pk_errors)
1033        } else {
1034            CheckStatus::Ok
1035        };
1036
1037        let fk_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.fk_errors > 0 {
1042            CheckStatus::Failed(self.fk_errors)
1043        } else {
1044            CheckStatus::Ok
1045        };
1046
1047        ValidationSummary {
1048            dialect: self.dialect.to_string(),
1049            issues: self.issues.clone(),
1050            summary: SummaryStats {
1051                errors,
1052                warnings,
1053                info,
1054                tables_scanned: self.tables_from_ddl.len(),
1055                statements_scanned: self.statement_count,
1056            },
1057            checks: CheckResults {
1058                syntax: syntax_status,
1059                encoding: encoding_status,
1060                ddl_dml_consistency: ddl_dml_status,
1061                pk_duplicates: pk_status,
1062                fk_integrity: fk_status,
1063            },
1064        }
1065    }
1066}