Skip to main content

sql_splitter/sample/
mod.rs

1//! Sample command for creating reduced datasets from SQL dumps.
2//!
3//! The sample command creates reduced datasets while optionally preserving
4//! foreign key integrity through dependency-aware FK chain resolution.
5//!
6//! Supports MySQL, PostgreSQL, and SQLite dialects.
7
8mod config;
9mod reservoir;
10
11pub use config::{DefaultClassifier, GlobalTableMode, SampleYamlConfig, TableClassification};
12pub use reservoir::Reservoir;
13
14use crate::parser::mysql_insert::{
15    hash_pk_tuple, parse_insert_rows_with, ParsedRow, PkHashSet, RowExtraction,
16};
17use crate::parser::postgres_copy::{
18    parse_copy_columns, parse_postgres_copy_rows_with, ParsedCopyRow,
19};
20use crate::parser::{ContentFilter, Parser, SqlDialect, StatementType};
21use crate::schema::{SchemaBuilder, SchemaGraph, TableId};
22use crate::splitter::Splitter;
23use ahash::AHashMap;
24use indicatif::{ProgressBar, ProgressStyle};
25use rand::rngs::StdRng;
26use rand::{RngExt, SeedableRng};
27use std::fs::{self, File};
28use std::io::{BufWriter, Write};
29use std::path::{Path, PathBuf};
30use tempfile::TempDir;
31
32/// Sampling mode
33#[derive(Debug, Clone, Copy)]
34pub enum SampleMode {
35    /// Sample N% of rows from each table
36    Percent(u32),
37    /// Sample up to N rows from each table
38    Rows(usize),
39}
40
41/// Configuration for the sample command
42#[derive(Debug)]
43pub struct SampleConfig {
44    /// Input SQL file
45    pub input: PathBuf,
46    /// Output SQL file (None for stdout)
47    pub output: Option<PathBuf>,
48    /// SQL dialect
49    pub dialect: SqlDialect,
50    /// Sampling mode
51    pub mode: SampleMode,
52    /// Preserve foreign key relationships
53    pub preserve_relations: bool,
54    /// Only sample these tables (None = all)
55    pub tables_filter: Option<Vec<String>>,
56    /// Exclude these tables
57    pub exclude: Vec<String>,
58    /// Root tables for sampling (start from these)
59    pub root_tables: Vec<String>,
60    /// How to handle global/lookup tables
61    pub include_global: GlobalTableMode,
62    /// Random seed for reproducibility
63    pub seed: u64,
64    /// Dry run mode (show stats only)
65    pub dry_run: bool,
66    /// Show progress
67    pub progress: bool,
68    /// YAML config file path
69    pub config_file: Option<PathBuf>,
70    /// Maximum total rows to sample (explosion guard)
71    pub max_total_rows: Option<usize>,
72    /// Fail if any FK integrity issues detected
73    pub strict_fk: bool,
74    /// Include schema statements in output
75    pub include_schema: bool,
76}
77
78impl Default for SampleConfig {
79    fn default() -> Self {
80        Self {
81            input: PathBuf::new(),
82            output: None,
83            dialect: SqlDialect::MySql,
84            mode: SampleMode::Percent(10),
85            preserve_relations: false,
86            tables_filter: None,
87            exclude: Vec::new(),
88            root_tables: Vec::new(),
89            include_global: GlobalTableMode::Lookups,
90            seed: rand::random(),
91            dry_run: false,
92            progress: false,
93            config_file: None,
94            max_total_rows: None,
95            strict_fk: false,
96            include_schema: true,
97        }
98    }
99}
100
101/// Statistics from sample operation
102#[derive(Debug, Default, serde::Serialize)]
103pub struct SampleStats {
104    /// Number of tables sampled
105    pub tables_sampled: usize,
106    /// Number of tables skipped
107    pub tables_skipped: usize,
108    /// Total rows selected
109    pub total_rows_selected: u64,
110    /// Total rows seen
111    pub total_rows_seen: u64,
112    /// Per-table statistics
113    pub table_stats: Vec<TableSampleStats>,
114    /// Warning messages
115    pub warnings: Vec<String>,
116    /// FK orphan count (rows rejected due to missing parents)
117    pub fk_orphans_rejected: u64,
118}
119
120/// Per-table sampling statistics
121#[derive(Debug, Clone, serde::Serialize)]
122pub struct TableSampleStats {
123    pub name: String,
124    pub rows_seen: u64,
125    pub rows_selected: u64,
126    pub classification: TableClassification,
127}
128
129/// Runtime state for a table during sampling
130struct TableRuntime {
131    /// Table name
132    name: String,
133    /// Primary key hashes for FK membership checks (compact: 8 bytes per key)
134    pk_set: PkHashSet,
135    /// Rows seen count
136    rows_seen: u64,
137    /// Rows selected count
138    rows_selected: u64,
139    /// Whether to skip this table
140    skip: bool,
141    /// Table classification
142    classification: TableClassification,
143    /// FK orphans rejected for this table
144    fk_orphans: u64,
145    /// Path to temp file containing selected row bytes (None if no rows selected yet)
146    selected_temp_path: Option<PathBuf>,
147}
148
149/// Combined row representation for both MySQL INSERT and PostgreSQL COPY
150enum UnifiedRow {
151    Insert(ParsedRow),
152    Copy(ParsedCopyRow),
153}
154
155/// Row format indicator for output
156#[derive(Debug, Clone, Copy, PartialEq)]
157enum RowFormat {
158    Insert,
159    Copy,
160}
161
162impl UnifiedRow {
163    fn fk_values(
164        &self,
165    ) -> &[(
166        crate::parser::mysql_insert::FkRef,
167        smallvec::SmallVec<[crate::parser::mysql_insert::PkValue; 2]>,
168    )] {
169        match self {
170            UnifiedRow::Insert(r) => &r.fk_values,
171            UnifiedRow::Copy(r) => &r.fk_values,
172        }
173    }
174}
175
176/// Run the sample command
177pub fn run(config: SampleConfig) -> anyhow::Result<SampleStats> {
178    // Load YAML config if provided
179    let yaml_config = if let Some(ref path) = config.config_file {
180        Some(SampleYamlConfig::load(path)?)
181    } else {
182        None
183    };
184
185    let mut rng = StdRng::seed_from_u64(config.seed);
186    let mut stats = SampleStats::default();
187
188    // Get file size for progress tracking
189    let file_size = std::fs::metadata(&config.input)?.len();
190
191    // Progress bar setup - byte-based for the split phase
192    let progress_bar = if config.progress {
193        let pb = ProgressBar::new(file_size);
194        pb.set_style(
195            ProgressStyle::with_template(
196                "{spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] {bytes}/{total_bytes} ({percent}%) {msg}",
197            )
198            .unwrap()
199            .progress_chars("█▓▒░  ")
200            .tick_chars("⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"),
201        );
202        pb.enable_steady_tick(std::time::Duration::from_millis(100));
203        pb.set_message("Splitting dump...");
204        Some(pb)
205    } else {
206        None
207    };
208
209    // Phase 0: Split into temp per-table files
210    let temp_dir = TempDir::new()?;
211    let tables_dir = temp_dir.path().join("tables");
212
213    let mut splitter = Splitter::new(config.input.clone(), tables_dir.clone())
214        .with_dialect(config.dialect)
215        .with_content_filter(ContentFilter::All);
216
217    if let Some(ref pb) = progress_bar {
218        let pb_clone = pb.clone();
219        splitter = splitter.with_progress(move |bytes| {
220            pb_clone.set_position(bytes);
221        });
222    }
223
224    let split_stats = splitter.split()?;
225
226    // Finish byte-based progress, switch to milestone messages
227    if let Some(ref pb) = progress_bar {
228        pb.finish_and_clear();
229    }
230
231    if config.progress {
232        eprintln!(
233            "Split complete: {} tables, {} statements",
234            split_stats.tables_found, split_stats.statements_processed
235        );
236    }
237
238    // Phase 1: Build schema graph
239    if config.progress {
240        eprintln!("Building schema graph...");
241    }
242
243    let graph = build_schema_graph(&tables_dir, &config)?;
244
245    let (topo_order, cyclic_tables) = graph.processing_order();
246
247    if !cyclic_tables.is_empty() {
248        let names: Vec<_> = cyclic_tables
249            .iter()
250            .filter_map(|&id| graph.table_name(id))
251            .collect();
252        let msg = format!(
253            "Warning: {} tables have FK cycles (intra-cycle FK enforcement disabled): {:?}",
254            cyclic_tables.len(),
255            names
256        );
257        if config.progress {
258            eprintln!("{}", msg);
259        }
260        stats.warnings.push(msg);
261    }
262
263    // Build set of cyclic table IDs for quick lookup
264    let cyclic_set: ahash::AHashSet<TableId> = cyclic_tables.iter().copied().collect();
265
266    // Determine root tables
267    let explicit_roots: ahash::AHashSet<String> = config
268        .root_tables
269        .iter()
270        .map(|s| s.to_lowercase())
271        .collect();
272
273    // Initialize table runtimes with classification
274    let mut runtimes: AHashMap<TableId, TableRuntime> = AHashMap::new();
275    for table in graph.schema.iter() {
276        let classification =
277            determine_classification(&table.name, &graph, table.id, &yaml_config, &explicit_roots);
278        let skip = should_skip_table(&table.name, &config, &yaml_config, classification);
279
280        runtimes.insert(
281            table.id,
282            TableRuntime {
283                name: table.name.clone(),
284                pk_set: PkHashSet::default(),
285                rows_seen: 0,
286                rows_selected: 0,
287                skip,
288                classification,
289                fk_orphans: 0,
290                selected_temp_path: None,
291            },
292        );
293    }
294
295    // Create directory for selected row temp files
296    let selected_dir = temp_dir.path().join("selected");
297    fs::create_dir_all(&selected_dir)?;
298
299    // Phase 2: Process tables in dependency order
300    if config.progress {
301        eprintln!(
302            "Sampling {} tables in dependency order...",
303            topo_order.len()
304        );
305    }
306
307    // Process acyclic tables first, then cyclic tables
308    let all_tables: Vec<TableId> = topo_order.into_iter().chain(cyclic_tables).collect();
309
310    let mut total_selected: u64 = 0;
311
312    for table_id in &all_tables {
313        let table_schema = match graph.schema.table(*table_id) {
314            Some(s) => s,
315            None => continue,
316        };
317
318        // Check if we should skip this table
319        let (should_skip, table_name, classification) = {
320            let runtime = match runtimes.get(table_id) {
321                Some(r) => r,
322                None => continue,
323            };
324            (runtime.skip, runtime.name.clone(), runtime.classification)
325        };
326
327        if should_skip {
328            stats.tables_skipped += 1;
329            continue;
330        }
331
332        // Handle lookup/global tables specially
333        let sample_mode = match classification {
334            TableClassification::Lookup => {
335                match config.include_global {
336                    GlobalTableMode::None => {
337                        stats.tables_skipped += 1;
338                        continue;
339                    }
340                    GlobalTableMode::Lookups | GlobalTableMode::All => {
341                        // Include all rows
342                        SampleMode::Percent(100)
343                    }
344                }
345            }
346            TableClassification::System => {
347                stats.tables_skipped += 1;
348                continue;
349            }
350            _ => get_table_sample_mode(&table_name, &config, &yaml_config),
351        };
352
353        let table_file = tables_dir.join(format!("{}.sql", table_name));
354        if !table_file.exists() {
355            continue;
356        }
357
358        // Process table with streaming sampling - rows go directly to temp file
359        let result = sample_table_streaming(
360            &table_file,
361            table_schema,
362            *table_id,
363            &table_name,
364            sample_mode,
365            &config,
366            &runtimes,
367            &cyclic_set,
368            &selected_dir,
369            &mut rng,
370        )?;
371
372        // Check max_total_rows guard
373        if let Some(max) = config.max_total_rows {
374            if total_selected + result.rows_selected > max as u64 {
375                let msg = format!(
376                    "Warning: Reached max_total_rows limit ({}) at table '{}'",
377                    max, table_name
378                );
379                stats.warnings.push(msg);
380                break;
381            }
382        }
383
384        // Update total count
385        total_selected += result.rows_selected;
386
387        // Update runtime state and add PK hashes for FK checks by children
388        // Safe: runtime existence was checked at loop start (line 323-326)
389        let runtime = runtimes
390            .get_mut(table_id)
391            .expect("runtime must exist - checked at loop start");
392        runtime.rows_seen = result.rows_seen;
393        runtime.rows_selected = result.rows_selected;
394        runtime.fk_orphans = result.fk_orphans;
395
396        // Add PK hashes for FK membership checks by child tables
397        for pk_hash in result.pk_hashes {
398            runtime.pk_set.insert(pk_hash);
399        }
400
401        // Set the temp file path if we selected any rows
402        if result.rows_selected > 0 {
403            let temp_path = selected_dir.join(format!("{}.rows", table_name));
404            if temp_path.exists() {
405                runtime.selected_temp_path = Some(temp_path);
406            }
407        }
408
409        stats.fk_orphans_rejected += result.fk_orphans;
410
411        stats.table_stats.push(TableSampleStats {
412            name: runtime.name.clone(),
413            rows_seen: result.rows_seen,
414            rows_selected: result.rows_selected,
415            classification: runtime.classification,
416        });
417    }
418
419    // Calculate totals
420    for table_stats in &stats.table_stats {
421        stats.total_rows_seen += table_stats.rows_seen;
422        stats.total_rows_selected += table_stats.rows_selected;
423    }
424    stats.tables_sampled = stats.table_stats.len();
425
426    if config.progress {
427        eprintln!("Sampling complete");
428    }
429
430    // Phase 3: Output synthesis
431    if config.dry_run {
432        return Ok(stats);
433    }
434
435    if config.progress {
436        eprintln!("Writing output...");
437    }
438
439    write_output(&config, &graph, &all_tables, &runtimes, &tables_dir, &stats)?;
440
441    Ok(stats)
442}
443
444/// Build schema graph from split table files
445fn build_schema_graph(tables_dir: &Path, config: &SampleConfig) -> anyhow::Result<SchemaGraph> {
446    let mut builder = SchemaBuilder::new();
447
448    for entry in fs::read_dir(tables_dir)? {
449        let entry = entry?;
450        let path = entry.path();
451
452        if path.extension().map(|e| e == "sql").unwrap_or(false) {
453            let file = File::open(&path)?;
454            let mut parser = Parser::with_dialect(file, 64 * 1024, config.dialect);
455
456            while let Some(stmt) = parser.read_statement()? {
457                let stmt_str = String::from_utf8_lossy(&stmt);
458                let (stmt_type, _) =
459                    Parser::<&[u8]>::parse_statement_with_dialect(&stmt, config.dialect);
460
461                match stmt_type {
462                    StatementType::CreateTable => {
463                        builder.parse_create_table(&stmt_str);
464                    }
465                    StatementType::AlterTable => {
466                        builder.parse_alter_table(&stmt_str);
467                    }
468                    _ => {}
469                }
470            }
471        }
472    }
473
474    Ok(SchemaGraph::from_schema(builder.build()))
475}
476
477/// Determine table classification
478fn determine_classification(
479    name: &str,
480    graph: &SchemaGraph,
481    table_id: TableId,
482    yaml_config: &Option<SampleYamlConfig>,
483    explicit_roots: &ahash::AHashSet<String>,
484) -> TableClassification {
485    // Check explicit roots first
486    if explicit_roots.contains(&name.to_lowercase()) {
487        return TableClassification::Root;
488    }
489
490    // Check YAML config
491    if let Some(ref config) = yaml_config {
492        let class = config.get_classification(name);
493        if class != TableClassification::Normal {
494            return class;
495        }
496    }
497
498    // Check if it's a graph root (no parents)
499    if graph.parents[table_id.0 as usize].is_empty() {
500        return TableClassification::Root;
501    }
502
503    // Use default classifier
504    DefaultClassifier::classify(name)
505}
506
507/// Check if a table should be skipped
508fn should_skip_table(
509    name: &str,
510    config: &SampleConfig,
511    yaml_config: &Option<SampleYamlConfig>,
512    classification: TableClassification,
513) -> bool {
514    let name_lower = name.to_lowercase();
515
516    // Check exclude list
517    if config
518        .exclude
519        .iter()
520        .any(|e| e.to_lowercase() == name_lower)
521    {
522        return true;
523    }
524
525    // Check YAML skip
526    if let Some(ref yc) = yaml_config {
527        if yc.should_skip(name) {
528            return true;
529        }
530    }
531
532    // Check include filter
533    if let Some(ref filter) = config.tables_filter {
534        if !filter.iter().any(|f| f.to_lowercase() == name_lower) {
535            return true;
536        }
537    }
538
539    // Skip system tables by default
540    if classification == TableClassification::System {
541        return true;
542    }
543
544    false
545}
546
547/// Get sample mode for a specific table
548fn get_table_sample_mode(
549    name: &str,
550    config: &SampleConfig,
551    yaml_config: &Option<SampleYamlConfig>,
552) -> SampleMode {
553    // Check YAML config first
554    if let Some(ref yc) = yaml_config {
555        if let Some(rows) = yc.get_rows(name) {
556            return SampleMode::Rows(rows);
557        }
558        if let Some(percent) = yc.get_percent(name) {
559            return SampleMode::Percent(percent);
560        }
561    }
562
563    // Fall back to global config
564    config.mode
565}
566
567/// Result from streaming sampling
568struct StreamingSampleResult {
569    rows_seen: u64,
570    rows_selected: u64,
571    fk_orphans: u64,
572    /// PK hashes of selected rows (for FK checks by children)
573    pk_hashes: Vec<u64>,
574}
575
576/// Stream-sample a table: parse rows, apply FK checks, sample inline, write to temp file.
577/// Returns StreamingSampleResult with stats and PK hashes.
578/// Uses Bernoulli sampling for --percent mode (single pass).
579/// For --rows mode, we use reservoir sampling on row indices with a second pass.
580#[allow(clippy::too_many_arguments)]
581fn sample_table_streaming(
582    table_file: &Path,
583    table_schema: &crate::schema::TableSchema,
584    table_id: TableId,
585    table_name: &str,
586    sample_mode: SampleMode,
587    config: &SampleConfig,
588    runtimes: &AHashMap<TableId, TableRuntime>,
589    cyclic_set: &ahash::AHashSet<TableId>,
590    selected_dir: &Path,
591    rng: &mut StdRng,
592) -> anyhow::Result<StreamingSampleResult> {
593    let mut rows_seen = 0u64;
594    let mut rows_selected = 0u64;
595    let mut fk_orphans = 0u64;
596
597    // Temp file for selected rows
598    let temp_path = selected_dir.join(format!("{}.rows", table_name));
599    let mut temp_writer: Option<BufWriter<File>> = None;
600
601    // Track PKs of selected rows (for children's FK checks)
602    let mut selected_pk_hashes: Vec<u64> = Vec::new();
603
604    // For PostgreSQL COPY, track the current column order
605    let mut copy_columns: Vec<String> = Vec::new();
606
607    match sample_mode {
608        SampleMode::Percent(p) => {
609            // Bernoulli sampling: decide immediately for each row
610            let prob = p as f64 / 100.0;
611
612            let file = File::open(table_file)?;
613            let mut parser = Parser::with_dialect(file, 64 * 1024, config.dialect);
614
615            while let Some(stmt) = parser.read_statement()? {
616                let (stmt_type, _) =
617                    Parser::<&[u8]>::parse_statement_with_dialect(&stmt, config.dialect);
618
619                match stmt_type {
620                    StatementType::Insert => {
621                        let rows = parse_insert_rows_with(
622                            &stmt,
623                            table_schema,
624                            config.dialect,
625                            RowExtraction::PkFk,
626                        )?;
627                        for row in rows {
628                            rows_seen += 1;
629
630                            // FK check
631                            if config.preserve_relations {
632                                let unified = UnifiedRow::Insert(row.clone());
633                                let (passes, orphan) = check_unified_fk_membership(
634                                    &unified,
635                                    table_schema,
636                                    runtimes,
637                                    cyclic_set,
638                                    &table_id,
639                                );
640                                if !passes {
641                                    fk_orphans += 1;
642                                    if orphan && config.strict_fk {
643                                        anyhow::bail!(
644                                            "FK integrity violation in table '{}': row references missing parent",
645                                            table_name
646                                        );
647                                    }
648                                    continue;
649                                }
650                            }
651
652                            // Bernoulli sample
653                            if rng.random::<f64>() < prob {
654                                // Write to temp file
655                                if temp_writer.is_none() {
656                                    temp_writer = Some(BufWriter::new(File::create(&temp_path)?));
657                                }
658                                let writer = temp_writer.as_mut().unwrap();
659                                // Format: 1-byte type (0=insert, 1=copy), then row bytes, then newline
660                                writer.write_all(&[0u8])?;
661                                writer.write_all(&row.raw)?;
662                                writer.write_all(b"\n")?;
663
664                                // Track PK hash
665                                if let Some(pk) = &row.pk {
666                                    selected_pk_hashes.push(hash_pk_tuple(pk));
667                                }
668                                rows_selected += 1;
669                            }
670                        }
671                    }
672                    StatementType::Copy => {
673                        let header = String::from_utf8_lossy(&stmt);
674                        copy_columns = parse_copy_columns(&header);
675                    }
676                    StatementType::Unknown if config.dialect == SqlDialect::Postgres => {
677                        if stmt.ends_with(b"\\.\n") || stmt.ends_with(b"\\.\r\n") {
678                            let rows = parse_postgres_copy_rows_with(
679                                &stmt,
680                                table_schema,
681                                copy_columns.clone(),
682                                RowExtraction::PkFk,
683                            )?;
684                            for row in rows {
685                                rows_seen += 1;
686
687                                if config.preserve_relations {
688                                    let unified = UnifiedRow::Copy(row.clone());
689                                    let (passes, orphan) = check_unified_fk_membership(
690                                        &unified,
691                                        table_schema,
692                                        runtimes,
693                                        cyclic_set,
694                                        &table_id,
695                                    );
696                                    if !passes {
697                                        fk_orphans += 1;
698                                        if orphan && config.strict_fk {
699                                            anyhow::bail!(
700                                                "FK integrity violation in table '{}': row references missing parent",
701                                                table_name
702                                            );
703                                        }
704                                        continue;
705                                    }
706                                }
707
708                                if rng.random::<f64>() < prob {
709                                    if temp_writer.is_none() {
710                                        temp_writer =
711                                            Some(BufWriter::new(File::create(&temp_path)?));
712                                    }
713                                    let writer = temp_writer.as_mut().unwrap();
714                                    writer.write_all(&[1u8])?;
715                                    writer.write_all(&row.raw)?;
716                                    writer.write_all(b"\n")?;
717
718                                    if let Some(pk) = &row.pk {
719                                        selected_pk_hashes.push(hash_pk_tuple(pk));
720                                    }
721                                    rows_selected += 1;
722                                }
723                            }
724                        }
725                    }
726                    _ => {}
727                }
728            }
729        }
730        SampleMode::Rows(n) => {
731            // Reservoir sampling: collect eligible row indices in first pass,
732            // then write selected rows in second pass
733            let mut reservoir: Reservoir<(u64, RowFormat, Option<u64>)> =
734                Reservoir::new(n, StdRng::from_rng(&mut *rng));
735
736            // First pass: build reservoir of (row_index, format, pk_hash)
737            let file = File::open(table_file)?;
738            let mut parser = Parser::with_dialect(file, 64 * 1024, config.dialect);
739
740            while let Some(stmt) = parser.read_statement()? {
741                let (stmt_type, _) =
742                    Parser::<&[u8]>::parse_statement_with_dialect(&stmt, config.dialect);
743
744                match stmt_type {
745                    StatementType::Insert => {
746                        let rows = parse_insert_rows_with(
747                            &stmt,
748                            table_schema,
749                            config.dialect,
750                            RowExtraction::PkFk,
751                        )?;
752                        for row in rows {
753                            let current_idx = rows_seen;
754                            rows_seen += 1;
755
756                            if config.preserve_relations {
757                                let unified = UnifiedRow::Insert(row.clone());
758                                let (passes, orphan) = check_unified_fk_membership(
759                                    &unified,
760                                    table_schema,
761                                    runtimes,
762                                    cyclic_set,
763                                    &table_id,
764                                );
765                                if !passes {
766                                    fk_orphans += 1;
767                                    if orphan && config.strict_fk {
768                                        anyhow::bail!(
769                                            "FK integrity violation in table '{}': row references missing parent",
770                                            table_name
771                                        );
772                                    }
773                                    continue;
774                                }
775                            }
776
777                            let pk_hash = row.pk.as_ref().map(hash_pk_tuple);
778                            reservoir.consider((current_idx, RowFormat::Insert, pk_hash));
779                        }
780                    }
781                    StatementType::Copy => {
782                        let header = String::from_utf8_lossy(&stmt);
783                        copy_columns = parse_copy_columns(&header);
784                    }
785                    StatementType::Unknown if config.dialect == SqlDialect::Postgres => {
786                        if stmt.ends_with(b"\\.\n") || stmt.ends_with(b"\\.\r\n") {
787                            let rows = parse_postgres_copy_rows_with(
788                                &stmt,
789                                table_schema,
790                                copy_columns.clone(),
791                                RowExtraction::PkFk,
792                            )?;
793                            for row in rows {
794                                let current_idx = rows_seen;
795                                rows_seen += 1;
796
797                                if config.preserve_relations {
798                                    let unified = UnifiedRow::Copy(row.clone());
799                                    let (passes, orphan) = check_unified_fk_membership(
800                                        &unified,
801                                        table_schema,
802                                        runtimes,
803                                        cyclic_set,
804                                        &table_id,
805                                    );
806                                    if !passes {
807                                        fk_orphans += 1;
808                                        if orphan && config.strict_fk {
809                                            anyhow::bail!(
810                                                "FK integrity violation in table '{}': row references missing parent",
811                                                table_name
812                                            );
813                                        }
814                                        continue;
815                                    }
816                                }
817
818                                let pk_hash = row.pk.as_ref().map(hash_pk_tuple);
819                                reservoir.consider((current_idx, RowFormat::Copy, pk_hash));
820                            }
821                        }
822                    }
823                    _ => {}
824                }
825            }
826
827            // Extract selected indices and PKs from reservoir
828            let selected_items = reservoir.into_items();
829            if selected_items.is_empty() {
830                return Ok(StreamingSampleResult {
831                    rows_seen,
832                    rows_selected: 0,
833                    fk_orphans,
834                    pk_hashes: Vec::new(),
835                });
836            }
837
838            // Collect PK hashes and sort indices for second pass
839            let mut selected_indices: Vec<(u64, RowFormat)> =
840                Vec::with_capacity(selected_items.len());
841            for (idx, format, pk_hash) in selected_items {
842                if let Some(h) = pk_hash {
843                    selected_pk_hashes.push(h);
844                }
845                selected_indices.push((idx, format));
846            }
847            selected_indices.sort_by_key(|(idx, _)| *idx);
848
849            // Second pass: write selected rows to temp file
850            let file = File::open(table_file)?;
851            let mut parser = Parser::with_dialect(file, 64 * 1024, config.dialect);
852            let mut current_row_idx = 0u64;
853            let mut select_iter = selected_indices.iter().peekable();
854
855            temp_writer = Some(BufWriter::new(File::create(&temp_path)?));
856            let writer = temp_writer.as_mut().unwrap();
857
858            while let Some(stmt) = parser.read_statement()? {
859                if select_iter.peek().is_none() {
860                    break; // All selected rows written
861                }
862
863                let (stmt_type, _) =
864                    Parser::<&[u8]>::parse_statement_with_dialect(&stmt, config.dialect);
865
866                match stmt_type {
867                    StatementType::Insert => {
868                        let rows = parse_insert_rows_with(
869                            &stmt,
870                            table_schema,
871                            config.dialect,
872                            RowExtraction::PkFk,
873                        )?;
874                        for row in rows {
875                            if let Some((next_idx, _)) = select_iter.peek() {
876                                if current_row_idx == *next_idx {
877                                    writer.write_all(&[0u8])?;
878                                    writer.write_all(&row.raw)?;
879                                    writer.write_all(b"\n")?;
880                                    rows_selected += 1;
881                                    select_iter.next();
882                                }
883                            }
884                            current_row_idx += 1;
885                        }
886                    }
887                    StatementType::Copy => {
888                        let header = String::from_utf8_lossy(&stmt);
889                        copy_columns = parse_copy_columns(&header);
890                    }
891                    StatementType::Unknown if config.dialect == SqlDialect::Postgres => {
892                        if stmt.ends_with(b"\\.\n") || stmt.ends_with(b"\\.\r\n") {
893                            let rows = parse_postgres_copy_rows_with(
894                                &stmt,
895                                table_schema,
896                                copy_columns.clone(),
897                                RowExtraction::PkFk,
898                            )?;
899                            for row in rows {
900                                if let Some((next_idx, _)) = select_iter.peek() {
901                                    if current_row_idx == *next_idx {
902                                        writer.write_all(&[1u8])?;
903                                        writer.write_all(&row.raw)?;
904                                        writer.write_all(b"\n")?;
905                                        rows_selected += 1;
906                                        select_iter.next();
907                                    }
908                                }
909                                current_row_idx += 1;
910                            }
911                        }
912                    }
913                    _ => {}
914                }
915            }
916        }
917    }
918
919    // Flush temp file
920    if let Some(mut writer) = temp_writer {
921        writer.flush()?;
922    }
923
924    Ok(StreamingSampleResult {
925        rows_seen,
926        rows_selected,
927        fk_orphans,
928        pk_hashes: selected_pk_hashes,
929    })
930}
931
932/// Check FK membership for a unified row (works with both INSERT and COPY rows)
933/// Uses hash-based lookup for memory efficiency.
934fn check_unified_fk_membership(
935    row: &UnifiedRow,
936    table_schema: &crate::schema::TableSchema,
937    runtimes: &AHashMap<TableId, TableRuntime>,
938    cyclic_set: &ahash::AHashSet<TableId>,
939    current_table_id: &TableId,
940) -> (bool, bool) {
941    let mut passes = true;
942    let mut is_orphan = false;
943
944    for (fk_ref, fk_tuple) in row.fk_values() {
945        if let Some(fk) = table_schema.foreign_keys.get(fk_ref.fk_index as usize) {
946            if let Some(parent_id) = fk.referenced_table_id {
947                // Skip FK check for cyclic tables
948                if cyclic_set.contains(&parent_id) && cyclic_set.contains(current_table_id) {
949                    continue;
950                }
951
952                // Check if parent row exists in parent's pk_set using hash lookup
953                if let Some(parent_runtime) = runtimes.get(&parent_id) {
954                    let fk_hash = hash_pk_tuple(fk_tuple);
955                    if !parent_runtime.pk_set.contains(&fk_hash) {
956                        passes = false;
957                        is_orphan = true;
958                        break;
959                    }
960                }
961            }
962        }
963    }
964
965    (passes, is_orphan)
966}
967
968/// Write sampled output
969fn write_output(
970    config: &SampleConfig,
971    _graph: &SchemaGraph,
972    table_order: &[TableId],
973    runtimes: &AHashMap<TableId, TableRuntime>,
974    tables_dir: &Path,
975    stats: &SampleStats,
976) -> anyhow::Result<()> {
977    let mut writer: Box<dyn Write> = match &config.output {
978        Some(path) => {
979            if let Some(parent) = path.parent() {
980                fs::create_dir_all(parent)?;
981            }
982            Box::new(BufWriter::with_capacity(256 * 1024, File::create(path)?))
983        }
984        None => Box::new(BufWriter::new(std::io::stdout())),
985    };
986
987    // Write header comment
988    write_header(&mut writer, config, stats)?;
989
990    // Write dialect-specific header
991    write_dialect_header(&mut writer, config.dialect)?;
992
993    // Write schema for each table (if enabled)
994    if config.include_schema {
995        for &table_id in table_order {
996            let runtime = match runtimes.get(&table_id) {
997                Some(r) if !r.skip && r.rows_selected > 0 => r,
998                _ => continue,
999            };
1000
1001            let table_file = tables_dir.join(format!("{}.sql", runtime.name));
1002            if !table_file.exists() {
1003                continue;
1004            }
1005
1006            // Copy schema statements from table file
1007            let file = File::open(&table_file)?;
1008            let mut parser = Parser::with_dialect(file, 64 * 1024, config.dialect);
1009
1010            while let Some(stmt) = parser.read_statement()? {
1011                let (stmt_type, _) =
1012                    Parser::<&[u8]>::parse_statement_with_dialect(&stmt, config.dialect);
1013
1014                if stmt_type.is_schema() {
1015                    writer.write_all(&stmt)?;
1016                    writer.write_all(b"\n")?;
1017                }
1018            }
1019        }
1020    }
1021
1022    // Write data for each table (reading from temp files instead of memory)
1023    for &table_id in table_order {
1024        let runtime = match runtimes.get(&table_id) {
1025            Some(r) if !r.skip && r.rows_selected > 0 && r.selected_temp_path.is_some() => r,
1026            _ => continue,
1027        };
1028
1029        let table_name = &runtime.name;
1030        let row_count = runtime.rows_selected;
1031
1032        writeln!(writer, "\n-- Data: {} ({} rows)", table_name, row_count)?;
1033
1034        // Get the table name quoting based on dialect
1035        let quoted_name = match config.dialect {
1036            SqlDialect::MySql => format!("`{}`", table_name),
1037            SqlDialect::Postgres | SqlDialect::Sqlite => format!("\"{}\"", table_name),
1038            SqlDialect::Mssql => format!("[{}]", table_name),
1039        };
1040
1041        // Read rows from temp file and write INSERTs in chunks
1042        let temp_path = runtime.selected_temp_path.as_ref().unwrap();
1043        let temp_file = File::open(temp_path)?;
1044        let reader = std::io::BufReader::new(temp_file);
1045        use std::io::BufRead;
1046
1047        const CHUNK_SIZE: usize = 1000;
1048        let mut chunk_buffer: Vec<(RowFormat, Vec<u8>)> = Vec::with_capacity(CHUNK_SIZE);
1049
1050        for line in reader.lines() {
1051            let line = line?;
1052            if line.is_empty() {
1053                continue;
1054            }
1055
1056            let bytes = line.as_bytes();
1057            if bytes.is_empty() {
1058                continue;
1059            }
1060
1061            // First byte is format indicator (0=insert, 1=copy)
1062            let format = if bytes[0] == 0 {
1063                RowFormat::Insert
1064            } else {
1065                RowFormat::Copy
1066            };
1067            let row_bytes = bytes[1..].to_vec();
1068
1069            chunk_buffer.push((format, row_bytes));
1070
1071            if chunk_buffer.len() >= CHUNK_SIZE {
1072                write_insert_chunk(&mut writer, &quoted_name, &chunk_buffer, config.dialect)?;
1073                chunk_buffer.clear();
1074            }
1075        }
1076
1077        // Write remaining rows
1078        if !chunk_buffer.is_empty() {
1079            write_insert_chunk(&mut writer, &quoted_name, &chunk_buffer, config.dialect)?;
1080        }
1081    }
1082
1083    // Write dialect-specific footer
1084    write_dialect_footer(&mut writer, config.dialect)?;
1085
1086    writer.flush()?;
1087
1088    Ok(())
1089}
1090
1091/// Write header comment
1092fn write_header<W: Write>(
1093    writer: &mut W,
1094    config: &SampleConfig,
1095    stats: &SampleStats,
1096) -> std::io::Result<()> {
1097    writeln!(writer, "-- Sampled from: {}", config.input.display())?;
1098    writeln!(
1099        writer,
1100        "-- Date: {}",
1101        chrono::Local::now().format("%Y-%m-%d %H:%M:%S")
1102    )?;
1103    writeln!(
1104        writer,
1105        "-- Mode: {:?}{}",
1106        config.mode,
1107        if config.preserve_relations {
1108            ", preserve-relations"
1109        } else {
1110            ""
1111        }
1112    )?;
1113    writeln!(writer, "-- Seed: {}", config.seed)?;
1114    writeln!(writer, "-- Dialect: {}", config.dialect)?;
1115    writeln!(writer, "--")?;
1116    writeln!(writer, "-- Statistics:")?;
1117    writeln!(writer, "--   Tables sampled: {}", stats.tables_sampled)?;
1118    writeln!(writer, "--   Tables skipped: {}", stats.tables_skipped)?;
1119
1120    let percent = if stats.total_rows_seen > 0 {
1121        (stats.total_rows_selected as f64 / stats.total_rows_seen as f64) * 100.0
1122    } else {
1123        0.0
1124    };
1125    writeln!(
1126        writer,
1127        "--   Total rows: {} (from {} original, {:.1}%)",
1128        stats.total_rows_selected, stats.total_rows_seen, percent
1129    )?;
1130
1131    if stats.fk_orphans_rejected > 0 {
1132        writeln!(
1133            writer,
1134            "--   FK orphans rejected: {}",
1135            stats.fk_orphans_rejected
1136        )?;
1137    }
1138
1139    if !stats.warnings.is_empty() {
1140        writeln!(writer, "--   Warnings: {}", stats.warnings.len())?;
1141    }
1142
1143    writeln!(writer)?;
1144
1145    Ok(())
1146}
1147
1148/// Write dialect-specific header
1149fn write_dialect_header<W: Write>(writer: &mut W, dialect: SqlDialect) -> std::io::Result<()> {
1150    match dialect {
1151        SqlDialect::MySql => {
1152            writeln!(writer, "SET NAMES utf8mb4;")?;
1153            writeln!(writer, "SET FOREIGN_KEY_CHECKS = 0;")?;
1154        }
1155        SqlDialect::Postgres => {
1156            writeln!(writer, "SET client_encoding = 'UTF8';")?;
1157            writeln!(writer, "SET session_replication_role = replica;")?;
1158        }
1159        SqlDialect::Sqlite => {
1160            writeln!(writer, "PRAGMA foreign_keys = OFF;")?;
1161        }
1162        SqlDialect::Mssql => {
1163            writeln!(writer, "SET ANSI_NULLS ON;")?;
1164            writeln!(writer, "SET QUOTED_IDENTIFIER ON;")?;
1165            writeln!(writer, "SET NOCOUNT ON;")?;
1166        }
1167    }
1168    writeln!(writer)?;
1169    Ok(())
1170}
1171
1172/// Write dialect-specific footer
1173fn write_dialect_footer<W: Write>(writer: &mut W, dialect: SqlDialect) -> std::io::Result<()> {
1174    writeln!(writer)?;
1175    match dialect {
1176        SqlDialect::MySql => {
1177            writeln!(writer, "SET FOREIGN_KEY_CHECKS = 1;")?;
1178        }
1179        SqlDialect::Postgres => {
1180            writeln!(writer, "SET session_replication_role = DEFAULT;")?;
1181        }
1182        SqlDialect::Sqlite => {
1183            writeln!(writer, "PRAGMA foreign_keys = ON;")?;
1184        }
1185        SqlDialect::Mssql => {
1186            // No footer needed
1187        }
1188    }
1189    Ok(())
1190}
1191
1192/// Write a chunk of rows as an INSERT statement
1193fn write_insert_chunk<W: Write>(
1194    writer: &mut W,
1195    quoted_name: &str,
1196    chunk: &[(RowFormat, Vec<u8>)],
1197    dialect: SqlDialect,
1198) -> std::io::Result<()> {
1199    writeln!(writer, "INSERT INTO {} VALUES", quoted_name)?;
1200
1201    for (i, (format, row_bytes)) in chunk.iter().enumerate() {
1202        if i > 0 {
1203            writer.write_all(b",\n")?;
1204        }
1205
1206        let values = match format {
1207            RowFormat::Insert => match dialect {
1208                SqlDialect::Postgres => convert_row_to_postgres(row_bytes),
1209                _ => row_bytes.clone(),
1210            },
1211            RowFormat::Copy => convert_copy_to_insert_values(row_bytes, dialect),
1212        };
1213        writer.write_all(&values)?;
1214    }
1215
1216    writer.write_all(b";\n")?;
1217    Ok(())
1218}
1219
1220/// Convert a MySQL-style row to PostgreSQL syntax
1221fn convert_row_to_postgres(row: &[u8]) -> Vec<u8> {
1222    // Simple conversion: just replace escaped quotes
1223    // A full implementation would handle more edge cases
1224    let mut result = Vec::with_capacity(row.len());
1225    let mut i = 0;
1226
1227    while i < row.len() {
1228        if row[i] == b'\\' && i + 1 < row.len() && row[i + 1] == b'\'' {
1229            // MySQL: \' -> PostgreSQL: ''
1230            result.push(b'\'');
1231            result.push(b'\'');
1232            i += 2;
1233        } else {
1234            result.push(row[i]);
1235            i += 1;
1236        }
1237    }
1238
1239    result
1240}
1241
1242/// Convert PostgreSQL COPY format (tab-separated) to INSERT VALUES format
1243fn convert_copy_to_insert_values(row: &[u8], dialect: SqlDialect) -> Vec<u8> {
1244    let mut result = Vec::with_capacity(row.len() + 20);
1245    result.push(b'(');
1246
1247    let fields: Vec<&[u8]> = row.split(|&b| b == b'\t').collect();
1248
1249    for (i, field) in fields.iter().enumerate() {
1250        if i > 0 {
1251            result.extend_from_slice(b", ");
1252        }
1253
1254        // Check for NULL marker
1255        if *field == b"\\N" {
1256            result.extend_from_slice(b"NULL");
1257        } else if field.is_empty() {
1258            // Empty string
1259            match dialect {
1260                SqlDialect::MySql => result.extend_from_slice(b"''"),
1261                SqlDialect::Postgres | SqlDialect::Sqlite | SqlDialect::Mssql => {
1262                    result.extend_from_slice(b"''")
1263                }
1264            }
1265        } else if is_numeric(field) {
1266            // Numeric value - no quotes needed
1267            result.extend_from_slice(field);
1268        } else {
1269            // String value - needs quoting
1270            result.push(b'\'');
1271            for &b in *field {
1272                match b {
1273                    b'\'' => {
1274                        // Escape single quote
1275                        match dialect {
1276                            SqlDialect::MySql => result.extend_from_slice(b"\\'"),
1277                            SqlDialect::Postgres | SqlDialect::Sqlite | SqlDialect::Mssql => {
1278                                result.extend_from_slice(b"''")
1279                            }
1280                        }
1281                    }
1282                    b'\\' if dialect == SqlDialect::MySql => {
1283                        // Escape backslash in MySQL
1284                        result.extend_from_slice(b"\\\\");
1285                    }
1286                    _ => result.push(b),
1287                }
1288            }
1289            result.push(b'\'');
1290        }
1291    }
1292
1293    result.push(b')');
1294    result
1295}
1296
1297/// Check if a byte slice represents a numeric value
1298fn is_numeric(s: &[u8]) -> bool {
1299    if s.is_empty() {
1300        return false;
1301    }
1302
1303    let mut has_digit = false;
1304    let mut has_dot = false;
1305    let mut start = 0;
1306
1307    // Handle leading sign
1308    if s[0] == b'-' || s[0] == b'+' {
1309        start = 1;
1310    }
1311
1312    for &b in &s[start..] {
1313        match b {
1314            b'0'..=b'9' => has_digit = true,
1315            b'.' if !has_dot => has_dot = true,
1316            b'e' | b'E' => {
1317                // Scientific notation - just check rest is digits
1318                continue;
1319            }
1320            _ => return false,
1321        }
1322    }
1323
1324    has_digit
1325}