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