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::{hash_pk_tuple, PkHashSet, RowExtraction};
15use crate::parser::{Parser, SqlDialect};
16use crate::schema::{SchemaGraph, TableId};
17use crate::transform_common::{
18    build_schema_graph, for_each_data_row, quote_ident, split_to_temp_tables, write_dialect_footer,
19    write_dialect_header, write_insert_chunk, RowFlow, RowFormat, RowSpillReader, RowSpillWriter,
20    UnifiedRow,
21};
22use ahash::AHashMap;
23use rand::rngs::StdRng;
24use rand::{RngExt, SeedableRng};
25use std::fs::{self, File};
26use std::io::{BufWriter, Write};
27use std::path::{Path, PathBuf};
28
29/// Sampling mode
30#[derive(Debug, Clone, Copy)]
31pub enum SampleMode {
32    /// Sample N% of rows from each table
33    Percent(u32),
34    /// Sample up to N rows from each table
35    Rows(usize),
36}
37
38/// Configuration for the sample command
39#[derive(Debug)]
40pub struct SampleConfig {
41    /// Input SQL file
42    pub input: PathBuf,
43    /// Output SQL file (None for stdout)
44    pub output: Option<PathBuf>,
45    /// SQL dialect
46    pub dialect: SqlDialect,
47    /// Sampling mode
48    pub mode: SampleMode,
49    /// Preserve foreign key relationships
50    pub preserve_relations: bool,
51    /// Only sample these tables (None = all)
52    pub tables_filter: Option<Vec<String>>,
53    /// Exclude these tables
54    pub exclude: Vec<String>,
55    /// Root tables for sampling (start from these)
56    pub root_tables: Vec<String>,
57    /// How to handle global/lookup tables
58    pub include_global: GlobalTableMode,
59    /// Random seed for reproducibility
60    pub seed: u64,
61    /// Dry run mode (show stats only)
62    pub dry_run: bool,
63    /// Show progress
64    pub progress: bool,
65    /// YAML config file path
66    pub config_file: Option<PathBuf>,
67    /// Maximum total rows to sample (explosion guard)
68    pub max_total_rows: Option<usize>,
69    /// Fail if any FK integrity issues detected
70    pub strict_fk: bool,
71    /// Include schema statements in output
72    pub include_schema: bool,
73}
74
75impl Default for SampleConfig {
76    fn default() -> Self {
77        Self {
78            input: PathBuf::new(),
79            output: None,
80            dialect: SqlDialect::MySql,
81            mode: SampleMode::Percent(10),
82            preserve_relations: false,
83            tables_filter: None,
84            exclude: Vec::new(),
85            root_tables: Vec::new(),
86            include_global: GlobalTableMode::Lookups,
87            seed: rand::random(),
88            dry_run: false,
89            progress: false,
90            config_file: None,
91            max_total_rows: None,
92            strict_fk: false,
93            include_schema: true,
94        }
95    }
96}
97
98/// Statistics from sample operation
99#[derive(Debug, Default, serde::Serialize)]
100pub struct SampleStats {
101    /// Number of tables sampled
102    pub tables_sampled: usize,
103    /// Number of tables skipped
104    pub tables_skipped: usize,
105    /// Total rows selected
106    pub total_rows_selected: u64,
107    /// Total rows seen
108    pub total_rows_seen: u64,
109    /// Per-table statistics
110    pub table_stats: Vec<TableSampleStats>,
111    /// Warning messages
112    pub warnings: Vec<String>,
113    /// FK orphan count (rows rejected due to missing parents)
114    pub fk_orphans_rejected: u64,
115}
116
117/// Per-table sampling statistics
118#[derive(Debug, Clone, serde::Serialize)]
119pub struct TableSampleStats {
120    pub name: String,
121    pub rows_seen: u64,
122    pub rows_selected: u64,
123    pub classification: TableClassification,
124}
125
126/// Runtime state for a table during sampling
127struct TableRuntime {
128    /// Table name
129    name: String,
130    /// Primary key hashes for FK membership checks (compact: 8 bytes per key)
131    pk_set: PkHashSet,
132    /// Rows seen count
133    rows_seen: u64,
134    /// Rows selected count
135    rows_selected: u64,
136    /// Whether to skip this table
137    skip: bool,
138    /// Table classification
139    classification: TableClassification,
140    /// FK orphans rejected for this table
141    fk_orphans: u64,
142    /// Path to temp file containing selected row bytes (None if no rows selected yet)
143    selected_temp_path: Option<PathBuf>,
144}
145
146/// Run the sample command
147pub fn run(config: SampleConfig) -> anyhow::Result<SampleStats> {
148    // Load YAML config if provided
149    let yaml_config = if let Some(ref path) = config.config_file {
150        Some(SampleYamlConfig::load(path)?)
151    } else {
152        None
153    };
154
155    let mut rng = StdRng::seed_from_u64(config.seed);
156    let mut stats = SampleStats::default();
157
158    // Split input into per-table files
159    let split_phase = split_to_temp_tables(&config.input, config.dialect, config.progress)?;
160    let temp_dir = split_phase.temp_dir;
161    let tables_dir = split_phase.tables_dir;
162
163    // Build the schema graph
164    if config.progress {
165        eprintln!("Building schema graph...");
166    }
167
168    let graph = build_schema_graph(&tables_dir, config.dialect)?;
169
170    let (topo_order, cyclic_tables) = graph.processing_order();
171
172    if !cyclic_tables.is_empty() {
173        let names: Vec<_> = cyclic_tables
174            .iter()
175            .filter_map(|&id| graph.table_name(id))
176            .collect();
177        let msg = format!(
178            "Warning: {} tables have FK cycles (intra-cycle FK enforcement disabled): {:?}",
179            cyclic_tables.len(),
180            names
181        );
182        if config.progress {
183            eprintln!("{}", msg);
184        }
185        stats.warnings.push(msg);
186    }
187
188    // Build set of cyclic table IDs for quick lookup
189    let cyclic_set: ahash::AHashSet<TableId> = cyclic_tables.iter().copied().collect();
190
191    // Determine root tables
192    let explicit_roots: ahash::AHashSet<String> = config
193        .root_tables
194        .iter()
195        .map(|s| s.to_lowercase())
196        .collect();
197
198    // Initialize table runtimes with classification
199    let mut runtimes: AHashMap<TableId, TableRuntime> = AHashMap::new();
200    for table in graph.schema.iter() {
201        let classification =
202            determine_classification(&table.name, &graph, table.id, &yaml_config, &explicit_roots);
203        let skip = should_skip_table(&table.name, &config, &yaml_config, classification);
204
205        runtimes.insert(
206            table.id,
207            TableRuntime {
208                name: table.name.clone(),
209                pk_set: PkHashSet::default(),
210                rows_seen: 0,
211                rows_selected: 0,
212                skip,
213                classification,
214                fk_orphans: 0,
215                selected_temp_path: None,
216            },
217        );
218    }
219
220    // Create directory for selected row temp files
221    let selected_dir = temp_dir.path().join("selected");
222    fs::create_dir_all(&selected_dir)?;
223
224    // Process tables in dependency order
225    if config.progress {
226        eprintln!(
227            "Sampling {} tables in dependency order...",
228            topo_order.len()
229        );
230    }
231
232    // Process acyclic tables first, then cyclic tables
233    let all_tables: Vec<TableId> = topo_order.into_iter().chain(cyclic_tables).collect();
234
235    let mut total_selected: u64 = 0;
236
237    for table_id in &all_tables {
238        let table_schema = match graph.schema.table(*table_id) {
239            Some(s) => s,
240            None => continue,
241        };
242
243        // Check if we should skip this table
244        let (should_skip, table_name, classification) = {
245            let runtime = match runtimes.get(table_id) {
246                Some(r) => r,
247                None => continue,
248            };
249            (runtime.skip, runtime.name.clone(), runtime.classification)
250        };
251
252        if should_skip {
253            stats.tables_skipped += 1;
254            continue;
255        }
256
257        // Handle lookup/global tables specially
258        let sample_mode = match classification {
259            TableClassification::Lookup => {
260                match config.include_global {
261                    GlobalTableMode::None => {
262                        stats.tables_skipped += 1;
263                        continue;
264                    }
265                    GlobalTableMode::Lookups | GlobalTableMode::All => {
266                        // Include all rows
267                        SampleMode::Percent(100)
268                    }
269                }
270            }
271            TableClassification::System => {
272                stats.tables_skipped += 1;
273                continue;
274            }
275            _ => get_table_sample_mode(&table_name, &config, &yaml_config),
276        };
277
278        let table_file = tables_dir.join(format!("{}.sql", table_name));
279        if !table_file.exists() {
280            continue;
281        }
282
283        // Process table with streaming sampling - rows go directly to temp file
284        let result = sample_table_streaming(
285            &table_file,
286            table_schema,
287            *table_id,
288            &table_name,
289            sample_mode,
290            &config,
291            &runtimes,
292            &cyclic_set,
293            &selected_dir,
294            &mut rng,
295        )?;
296
297        // Check max_total_rows guard
298        if let Some(max) = config.max_total_rows {
299            if total_selected + result.rows_selected > max as u64 {
300                let msg = format!(
301                    "Warning: Reached max_total_rows limit ({}) at table '{}'",
302                    max, table_name
303                );
304                stats.warnings.push(msg);
305                break;
306            }
307        }
308
309        // Update total count
310        total_selected += result.rows_selected;
311
312        // Update runtime state and add PK hashes for FK checks by children
313        // Safe: runtime existence was checked at loop start (line 323-326)
314        let runtime = runtimes
315            .get_mut(table_id)
316            .expect("runtime must exist - checked at loop start");
317        runtime.rows_seen = result.rows_seen;
318        runtime.rows_selected = result.rows_selected;
319        runtime.fk_orphans = result.fk_orphans;
320
321        // Add PK hashes for FK membership checks by child tables
322        for pk_hash in result.pk_hashes {
323            runtime.pk_set.insert(pk_hash);
324        }
325
326        // Set the temp file path if we selected any rows
327        if result.rows_selected > 0 {
328            let temp_path = selected_dir.join(format!("{}.rows", table_name));
329            if temp_path.exists() {
330                runtime.selected_temp_path = Some(temp_path);
331            }
332        }
333
334        stats.fk_orphans_rejected += result.fk_orphans;
335
336        stats.table_stats.push(TableSampleStats {
337            name: runtime.name.clone(),
338            rows_seen: result.rows_seen,
339            rows_selected: result.rows_selected,
340            classification: runtime.classification,
341        });
342    }
343
344    // Calculate totals
345    for table_stats in &stats.table_stats {
346        stats.total_rows_seen += table_stats.rows_seen;
347        stats.total_rows_selected += table_stats.rows_selected;
348    }
349    stats.tables_sampled = stats.table_stats.len();
350
351    if config.progress {
352        eprintln!("Sampling complete");
353    }
354
355    // Synthesize the output
356    if config.dry_run {
357        return Ok(stats);
358    }
359
360    if config.progress {
361        eprintln!("Writing output...");
362    }
363
364    write_output(&config, &graph, &all_tables, &runtimes, &tables_dir, &stats)?;
365
366    Ok(stats)
367}
368
369/// Determine table classification
370fn determine_classification(
371    name: &str,
372    graph: &SchemaGraph,
373    table_id: TableId,
374    yaml_config: &Option<SampleYamlConfig>,
375    explicit_roots: &ahash::AHashSet<String>,
376) -> TableClassification {
377    // Check explicit roots first
378    if explicit_roots.contains(&name.to_lowercase()) {
379        return TableClassification::Root;
380    }
381
382    // Check YAML config
383    if let Some(ref config) = yaml_config {
384        let class = config.get_classification(name);
385        if class != TableClassification::Normal {
386            return class;
387        }
388    }
389
390    // Check if it's a graph root (no parents)
391    if graph.parents[table_id.0 as usize].is_empty() {
392        return TableClassification::Root;
393    }
394
395    // Use default classifier
396    DefaultClassifier::classify(name)
397}
398
399/// Check if a table should be skipped
400fn should_skip_table(
401    name: &str,
402    config: &SampleConfig,
403    yaml_config: &Option<SampleYamlConfig>,
404    classification: TableClassification,
405) -> bool {
406    let name_lower = name.to_lowercase();
407
408    // Check exclude list
409    if config
410        .exclude
411        .iter()
412        .any(|e| e.to_lowercase() == name_lower)
413    {
414        return true;
415    }
416
417    // Check YAML skip
418    if let Some(ref yc) = yaml_config {
419        if yc.should_skip(name) {
420            return true;
421        }
422    }
423
424    // Check include filter
425    if let Some(ref filter) = config.tables_filter {
426        if !filter.iter().any(|f| f.to_lowercase() == name_lower) {
427            return true;
428        }
429    }
430
431    // Skip system tables by default
432    if classification == TableClassification::System {
433        return true;
434    }
435
436    false
437}
438
439/// Get sample mode for a specific table
440fn get_table_sample_mode(
441    name: &str,
442    config: &SampleConfig,
443    yaml_config: &Option<SampleYamlConfig>,
444) -> SampleMode {
445    // Check YAML config first
446    if let Some(ref yc) = yaml_config {
447        if let Some(rows) = yc.get_rows(name) {
448            return SampleMode::Rows(rows);
449        }
450        if let Some(percent) = yc.get_percent(name) {
451            return SampleMode::Percent(percent);
452        }
453    }
454
455    // Fall back to global config
456    config.mode
457}
458
459/// Result from streaming sampling
460struct StreamingSampleResult {
461    rows_seen: u64,
462    rows_selected: u64,
463    fk_orphans: u64,
464    /// PK hashes of selected rows (for FK checks by children)
465    pk_hashes: Vec<u64>,
466}
467
468/// Apply the preserve-relations FK check to a row.
469///
470/// Returns `Ok(true)` if the row passes (or checking is disabled), `Ok(false)`
471/// if the row is an orphan that should be skipped, and an error when strict FK
472/// mode is enabled and an orphan is found.
473fn passes_fk_or_bail(
474    row: &UnifiedRow,
475    table_schema: &crate::schema::TableSchema,
476    table_id: TableId,
477    table_name: &str,
478    config: &SampleConfig,
479    runtimes: &AHashMap<TableId, TableRuntime>,
480    cyclic_set: &ahash::AHashSet<TableId>,
481) -> anyhow::Result<bool> {
482    if !config.preserve_relations {
483        return Ok(true);
484    }
485
486    let (passes, orphan) =
487        check_unified_fk_membership(row, table_schema, runtimes, cyclic_set, &table_id);
488    if !passes {
489        if orphan && config.strict_fk {
490            anyhow::bail!(
491                "FK integrity violation in table '{}': row references missing parent",
492                table_name
493            );
494        }
495        return Ok(false);
496    }
497    Ok(true)
498}
499
500/// Stream-sample a table: parse rows, apply FK checks, sample inline, write to temp file.
501/// Returns StreamingSampleResult with stats and PK hashes.
502/// Uses Bernoulli sampling for --percent mode (single pass).
503/// For --rows mode, we use reservoir sampling on row indices with a second pass.
504#[allow(clippy::too_many_arguments)]
505fn sample_table_streaming(
506    table_file: &Path,
507    table_schema: &crate::schema::TableSchema,
508    table_id: TableId,
509    table_name: &str,
510    sample_mode: SampleMode,
511    config: &SampleConfig,
512    runtimes: &AHashMap<TableId, TableRuntime>,
513    cyclic_set: &ahash::AHashSet<TableId>,
514    selected_dir: &Path,
515    rng: &mut StdRng,
516) -> anyhow::Result<StreamingSampleResult> {
517    let mut rows_seen = 0u64;
518    let mut rows_selected = 0u64;
519    let mut fk_orphans = 0u64;
520
521    // Temp file for selected rows
522    let temp_path = selected_dir.join(format!("{}.rows", table_name));
523
524    // Track PKs of selected rows (for children's FK checks)
525    let mut selected_pk_hashes: Vec<u64> = Vec::new();
526
527    match sample_mode {
528        SampleMode::Percent(p) => {
529            // Bernoulli sampling: decide immediately for each row
530            let prob = p as f64 / 100.0;
531            let mut spill: Option<RowSpillWriter> = None;
532
533            for_each_data_row(
534                table_file,
535                table_schema,
536                config.dialect,
537                RowExtraction::PkFk,
538                |row| {
539                    rows_seen += 1;
540
541                    // FK check
542                    if !passes_fk_or_bail(
543                        &row,
544                        table_schema,
545                        table_id,
546                        table_name,
547                        config,
548                        runtimes,
549                        cyclic_set,
550                    )? {
551                        fk_orphans += 1;
552                        return Ok(RowFlow::Continue);
553                    }
554
555                    // Bernoulli sample
556                    if rng.random::<f64>() < prob {
557                        if spill.is_none() {
558                            spill = Some(RowSpillWriter::create(&temp_path)?);
559                        }
560                        spill.as_mut().unwrap().write_row(row.format(), row.raw())?;
561
562                        // Track PK hash
563                        if let Some(pk) = row.pk() {
564                            selected_pk_hashes.push(hash_pk_tuple(pk));
565                        }
566                        rows_selected += 1;
567                    }
568
569                    Ok(RowFlow::Continue)
570                },
571            )?;
572
573            if let Some(spill) = spill {
574                spill.finish()?;
575            }
576        }
577        SampleMode::Rows(n) => {
578            // Reservoir sampling: collect eligible row indices in first pass,
579            // then write selected rows in second pass
580            let mut reservoir: Reservoir<(u64, Option<u64>)> =
581                Reservoir::new(n, StdRng::from_rng(&mut *rng));
582
583            // First pass: build reservoir of (row_index, pk_hash)
584            for_each_data_row(
585                table_file,
586                table_schema,
587                config.dialect,
588                RowExtraction::PkFk,
589                |row| {
590                    let current_idx = rows_seen;
591                    rows_seen += 1;
592
593                    if !passes_fk_or_bail(
594                        &row,
595                        table_schema,
596                        table_id,
597                        table_name,
598                        config,
599                        runtimes,
600                        cyclic_set,
601                    )? {
602                        fk_orphans += 1;
603                        return Ok(RowFlow::Continue);
604                    }
605
606                    let pk_hash = row.pk().map(hash_pk_tuple);
607                    reservoir.consider((current_idx, pk_hash));
608                    Ok(RowFlow::Continue)
609                },
610            )?;
611
612            // Extract selected indices and PKs from reservoir
613            let selected_items = reservoir.into_items();
614            if selected_items.is_empty() {
615                return Ok(StreamingSampleResult {
616                    rows_seen,
617                    rows_selected: 0,
618                    fk_orphans,
619                    pk_hashes: Vec::new(),
620                });
621            }
622
623            // Collect PK hashes and sort indices for second pass
624            let mut selected_indices: Vec<u64> = Vec::with_capacity(selected_items.len());
625            for (idx, pk_hash) in selected_items {
626                if let Some(h) = pk_hash {
627                    selected_pk_hashes.push(h);
628                }
629                selected_indices.push(idx);
630            }
631            selected_indices.sort_unstable();
632
633            // Second pass: write selected rows to temp file
634            let mut spill = RowSpillWriter::create(&temp_path)?;
635            let mut current_row_idx = 0u64;
636            let mut select_iter = selected_indices.iter().peekable();
637
638            for_each_data_row(
639                table_file,
640                table_schema,
641                config.dialect,
642                RowExtraction::PkFk,
643                |row| {
644                    let Some(&&next_idx) = select_iter.peek() else {
645                        return Ok(RowFlow::Stop); // All selected rows written
646                    };
647                    if current_row_idx == next_idx {
648                        spill.write_row(row.format(), row.raw())?;
649                        rows_selected += 1;
650                        select_iter.next();
651                    }
652                    current_row_idx += 1;
653                    Ok(RowFlow::Continue)
654                },
655            )?;
656
657            spill.finish()?;
658        }
659    }
660
661    Ok(StreamingSampleResult {
662        rows_seen,
663        rows_selected,
664        fk_orphans,
665        pk_hashes: selected_pk_hashes,
666    })
667}
668
669/// Check FK membership for a unified row (works with both INSERT and COPY rows)
670/// Uses hash-based lookup for memory efficiency.
671fn check_unified_fk_membership(
672    row: &UnifiedRow,
673    table_schema: &crate::schema::TableSchema,
674    runtimes: &AHashMap<TableId, TableRuntime>,
675    cyclic_set: &ahash::AHashSet<TableId>,
676    current_table_id: &TableId,
677) -> (bool, bool) {
678    let mut passes = true;
679    let mut is_orphan = false;
680
681    for (fk_ref, fk_tuple) in row.fk_values() {
682        if let Some(fk) = table_schema.foreign_keys.get(fk_ref.fk_index as usize) {
683            if let Some(parent_id) = fk.referenced_table_id {
684                // Skip FK check for cyclic tables
685                if cyclic_set.contains(&parent_id) && cyclic_set.contains(current_table_id) {
686                    continue;
687                }
688
689                // Check if parent row exists in parent's pk_set using hash lookup
690                if let Some(parent_runtime) = runtimes.get(&parent_id) {
691                    let fk_hash = hash_pk_tuple(fk_tuple);
692                    if !parent_runtime.pk_set.contains(&fk_hash) {
693                        passes = false;
694                        is_orphan = true;
695                        break;
696                    }
697                }
698            }
699        }
700    }
701
702    (passes, is_orphan)
703}
704
705/// Write sampled output
706fn write_output(
707    config: &SampleConfig,
708    _graph: &SchemaGraph,
709    table_order: &[TableId],
710    runtimes: &AHashMap<TableId, TableRuntime>,
711    tables_dir: &Path,
712    stats: &SampleStats,
713) -> anyhow::Result<()> {
714    let mut writer: Box<dyn Write> = match &config.output {
715        Some(path) => {
716            if let Some(parent) = path.parent() {
717                fs::create_dir_all(parent)?;
718            }
719            Box::new(BufWriter::with_capacity(256 * 1024, File::create(path)?))
720        }
721        None => Box::new(BufWriter::new(std::io::stdout())),
722    };
723
724    // Write header comment
725    write_header(&mut writer, config, stats)?;
726
727    // Write dialect-specific header
728    write_dialect_header(&mut writer, config.dialect)?;
729
730    // Write schema for each table (if enabled)
731    if config.include_schema {
732        for &table_id in table_order {
733            let runtime = match runtimes.get(&table_id) {
734                Some(r) if !r.skip && r.rows_selected > 0 => r,
735                _ => continue,
736            };
737
738            let table_file = tables_dir.join(format!("{}.sql", runtime.name));
739            if !table_file.exists() {
740                continue;
741            }
742
743            // Copy schema statements from table file
744            let file = File::open(&table_file)?;
745            let mut parser = Parser::with_dialect(file, 64 * 1024, config.dialect);
746
747            while let Some(stmt) = parser.read_statement()? {
748                let (stmt_type, _) =
749                    Parser::<&[u8]>::parse_statement_with_dialect(&stmt, config.dialect);
750
751                if stmt_type.is_schema() {
752                    writer.write_all(&stmt)?;
753                    writer.write_all(b"\n")?;
754                }
755            }
756        }
757    }
758
759    // Write data for each table (reading from temp files instead of memory)
760    for &table_id in table_order {
761        let runtime = match runtimes.get(&table_id) {
762            Some(r) if !r.skip && r.rows_selected > 0 && r.selected_temp_path.is_some() => r,
763            _ => continue,
764        };
765
766        let table_name = &runtime.name;
767        let row_count = runtime.rows_selected;
768
769        writeln!(writer, "\n-- Data: {} ({} rows)", table_name, row_count)?;
770
771        // Get the table name quoting based on dialect
772        let quoted_name = quote_ident(config.dialect, table_name);
773
774        // Read rows from temp file and write INSERTs in chunks
775        let temp_path = runtime.selected_temp_path.as_ref().unwrap();
776        let mut spill_reader = RowSpillReader::open(temp_path)?;
777
778        const CHUNK_SIZE: usize = 1000;
779        let mut chunk_buffer: Vec<(RowFormat, Vec<u8>)> = Vec::with_capacity(CHUNK_SIZE);
780
781        while let Some((format, row_bytes)) = spill_reader.next_row()? {
782            chunk_buffer.push((format, row_bytes));
783
784            if chunk_buffer.len() >= CHUNK_SIZE {
785                write_insert_chunk(&mut writer, &quoted_name, &chunk_buffer, config.dialect)?;
786                chunk_buffer.clear();
787            }
788        }
789
790        // Write remaining rows
791        if !chunk_buffer.is_empty() {
792            write_insert_chunk(&mut writer, &quoted_name, &chunk_buffer, config.dialect)?;
793        }
794    }
795
796    // Write dialect-specific footer
797    write_dialect_footer(&mut writer, config.dialect)?;
798
799    writer.flush()?;
800
801    Ok(())
802}
803
804/// Write header comment
805fn write_header<W: Write>(
806    writer: &mut W,
807    config: &SampleConfig,
808    stats: &SampleStats,
809) -> std::io::Result<()> {
810    writeln!(writer, "-- Sampled from: {}", config.input.display())?;
811    writeln!(
812        writer,
813        "-- Date: {}",
814        chrono::Local::now().format("%Y-%m-%d %H:%M:%S")
815    )?;
816    writeln!(
817        writer,
818        "-- Mode: {:?}{}",
819        config.mode,
820        if config.preserve_relations {
821            ", preserve-relations"
822        } else {
823            ""
824        }
825    )?;
826    writeln!(writer, "-- Seed: {}", config.seed)?;
827    writeln!(writer, "-- Dialect: {}", config.dialect)?;
828    writeln!(writer, "--")?;
829    writeln!(writer, "-- Statistics:")?;
830    writeln!(writer, "--   Tables sampled: {}", stats.tables_sampled)?;
831    writeln!(writer, "--   Tables skipped: {}", stats.tables_skipped)?;
832
833    let percent = if stats.total_rows_seen > 0 {
834        (stats.total_rows_selected as f64 / stats.total_rows_seen as f64) * 100.0
835    } else {
836        0.0
837    };
838    writeln!(
839        writer,
840        "--   Total rows: {} (from {} original, {:.1}%)",
841        stats.total_rows_selected, stats.total_rows_seen, percent
842    )?;
843
844    if stats.fk_orphans_rejected > 0 {
845        writeln!(
846            writer,
847            "--   FK orphans rejected: {}",
848            stats.fk_orphans_rejected
849        )?;
850    }
851
852    if !stats.warnings.is_empty() {
853        writeln!(writer, "--   Warnings: {}", stats.warnings.len())?;
854    }
855
856    writeln!(writer)?;
857
858    Ok(())
859}