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