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        let remaining_capacity = config.max_total_rows.map(|max| {
284            usize::try_from((max as u64).saturating_sub(total_selected)).unwrap_or(usize::MAX)
285        });
286        if remaining_capacity == Some(0) {
287            stats.warnings.push(format!(
288                "Warning: Reached max_total_rows limit ({}) at table '{}'",
289                config.max_total_rows.unwrap_or_default(),
290                table_name
291            ));
292            break;
293        }
294
295        // Process table with streaming sampling - rows go directly to temp file
296        let result = sample_table_streaming(
297            &table_file,
298            table_schema,
299            *table_id,
300            &table_name,
301            sample_mode,
302            &config,
303            &runtimes,
304            &cyclic_set,
305            &selected_dir,
306            &mut rng,
307            remaining_capacity,
308        )?;
309
310        // Update total count
311        total_selected += result.rows_selected;
312
313        // Update runtime state and add PK hashes for FK checks by children
314        // Safe: runtime existence was checked at loop start (line 323-326)
315        let runtime = runtimes
316            .get_mut(table_id)
317            .expect("runtime must exist - checked at loop start");
318        runtime.rows_seen = result.rows_seen;
319        runtime.rows_selected = result.rows_selected;
320        runtime.fk_orphans = result.fk_orphans;
321
322        // Add PK hashes for FK membership checks by child tables
323        for pk_hash in result.pk_hashes {
324            runtime.pk_set.insert(pk_hash);
325        }
326
327        // Set the temp file path if we selected any rows
328        if result.rows_selected > 0 {
329            let temp_path = selected_dir.join(format!("{}.rows", table_name));
330            if temp_path.exists() {
331                runtime.selected_temp_path = Some(temp_path);
332            }
333        }
334
335        stats.fk_orphans_rejected += result.fk_orphans;
336
337        stats.table_stats.push(TableSampleStats {
338            name: runtime.name.clone(),
339            rows_seen: result.rows_seen,
340            rows_selected: result.rows_selected,
341            classification: runtime.classification,
342        });
343
344        if let Some(max) = config.max_total_rows {
345            if total_selected >= max as u64 {
346                stats.warnings.push(format!(
347                    "Warning: Reached max_total_rows limit ({}) at table '{}'",
348                    max, table_name
349                ));
350                break;
351            }
352        }
353    }
354
355    // Calculate totals
356    for table_stats in &stats.table_stats {
357        stats.total_rows_seen += table_stats.rows_seen;
358        stats.total_rows_selected += table_stats.rows_selected;
359    }
360    stats.tables_sampled = stats.table_stats.len();
361
362    if config.progress {
363        eprintln!("Sampling complete");
364    }
365
366    // Synthesize the output
367    if config.dry_run {
368        return Ok(stats);
369    }
370
371    if config.progress {
372        eprintln!("Writing output...");
373    }
374
375    write_output(&config, &graph, &all_tables, &runtimes, &tables_dir, &stats)?;
376
377    Ok(stats)
378}
379
380/// Determine table classification
381fn determine_classification(
382    name: &str,
383    graph: &SchemaGraph,
384    table_id: TableId,
385    yaml_config: &Option<SampleYamlConfig>,
386    explicit_roots: &ahash::AHashSet<String>,
387) -> TableClassification {
388    // Check explicit roots first
389    if explicit_roots
390        .iter()
391        .any(|pattern| table_name_matches(pattern, name))
392    {
393        return TableClassification::Root;
394    }
395
396    // Check YAML config
397    if let Some(ref config) = yaml_config {
398        let class = config.get_classification(name);
399        if class != TableClassification::Normal {
400            return class;
401        }
402    }
403
404    // Check if it's a graph root (no parents)
405    if graph.parents[table_id.0 as usize].is_empty() {
406        return TableClassification::Root;
407    }
408
409    // Use default classifier
410    DefaultClassifier::classify(name)
411}
412
413/// Check if a table should be skipped
414fn should_skip_table(
415    name: &str,
416    config: &SampleConfig,
417    yaml_config: &Option<SampleYamlConfig>,
418    classification: TableClassification,
419) -> bool {
420    // Check exclude list
421    if config
422        .exclude
423        .iter()
424        .any(|pattern| table_name_matches(pattern, name))
425    {
426        return true;
427    }
428
429    // Check YAML skip
430    if let Some(ref yc) = yaml_config {
431        if yc.should_skip(name) {
432            return true;
433        }
434    }
435
436    // Check include filter
437    if let Some(ref filter) = config.tables_filter {
438        if !filter
439            .iter()
440            .any(|pattern| table_name_matches(pattern, name))
441        {
442            return true;
443        }
444    }
445
446    // Skip system tables by default
447    if classification == TableClassification::System {
448        return true;
449    }
450
451    false
452}
453
454/// Match a configured table name against a parsed name.
455///
456/// Qualified dump names are preserved internally. Existing configuration that
457/// uses an unqualified table name still matches the final name component;
458/// qualified configuration remains an exact match and can disambiguate
459/// schemas.
460fn table_name_matches(pattern: &str, table_name: &str) -> bool {
461    pattern.eq_ignore_ascii_case(table_name)
462        || (!pattern.contains('.')
463            && final_identifier_component(table_name)
464                .is_some_and(|bare_name| pattern.eq_ignore_ascii_case(bare_name)))
465}
466
467/// Return the final identifier component, without treating dots inside quoted
468/// components as qualification separators.
469fn final_identifier_component(name: &str) -> Option<&str> {
470    let bytes = name.as_bytes();
471    let mut quote = None;
472    let mut final_start = 0;
473    let mut index = 0;
474
475    while index < bytes.len() {
476        match quote {
477            Some(close) if bytes[index] == close => {
478                if bytes.get(index + 1) == Some(&close) {
479                    index += 2;
480                    continue;
481                }
482                quote = None;
483            }
484            Some(_) => {}
485            None => match bytes[index] {
486                b'`' | b'"' => quote = Some(bytes[index]),
487                b'[' => quote = Some(b']'),
488                b'.' => final_start = index + 1,
489                _ => {}
490            },
491        }
492        index += 1;
493    }
494
495    (final_start > 0).then(|| &name[final_start..])
496}
497
498/// Get sample mode for a specific table
499fn get_table_sample_mode(
500    name: &str,
501    config: &SampleConfig,
502    yaml_config: &Option<SampleYamlConfig>,
503) -> SampleMode {
504    // Check YAML config first
505    if let Some(ref yc) = yaml_config {
506        if let Some(rows) = yc.get_rows(name) {
507            return SampleMode::Rows(rows);
508        }
509        if let Some(percent) = yc.get_percent(name) {
510            return SampleMode::Percent(percent);
511        }
512    }
513
514    // Fall back to global config
515    config.mode
516}
517
518/// Result from streaming sampling
519struct StreamingSampleResult {
520    rows_seen: u64,
521    rows_selected: u64,
522    fk_orphans: u64,
523    /// PK hashes of selected rows (for FK checks by children)
524    pk_hashes: Vec<u64>,
525}
526
527/// Apply the preserve-relations FK check to a row.
528///
529/// Returns `Ok(true)` if the row passes (or checking is disabled), `Ok(false)`
530/// if the row is an orphan that should be skipped, and an error when strict FK
531/// mode is enabled and an orphan is found.
532fn passes_fk_or_bail(
533    row: &UnifiedRow,
534    table_schema: &crate::schema::TableSchema,
535    table_id: TableId,
536    table_name: &str,
537    config: &SampleConfig,
538    runtimes: &AHashMap<TableId, TableRuntime>,
539    cyclic_set: &ahash::AHashSet<TableId>,
540) -> anyhow::Result<bool> {
541    if !config.preserve_relations {
542        return Ok(true);
543    }
544
545    let (passes, orphan) =
546        check_unified_fk_membership(row, table_schema, runtimes, cyclic_set, &table_id);
547    if !passes {
548        if orphan && config.strict_fk {
549            anyhow::bail!(
550                "FK integrity violation in table '{}': row references missing parent",
551                table_name
552            );
553        }
554        return Ok(false);
555    }
556    Ok(true)
557}
558
559/// Stream-sample a table: parse rows, apply FK checks, sample inline, write to temp file.
560/// Returns StreamingSampleResult with stats and PK hashes.
561/// Uses Bernoulli sampling for --percent mode (single pass).
562/// For --rows mode, we use reservoir sampling on row indices with a second pass.
563#[allow(clippy::too_many_arguments)]
564fn sample_table_streaming(
565    table_file: &Path,
566    table_schema: &crate::schema::TableSchema,
567    table_id: TableId,
568    table_name: &str,
569    sample_mode: SampleMode,
570    config: &SampleConfig,
571    runtimes: &AHashMap<TableId, TableRuntime>,
572    cyclic_set: &ahash::AHashSet<TableId>,
573    selected_dir: &Path,
574    rng: &mut StdRng,
575    remaining_capacity: Option<usize>,
576) -> anyhow::Result<StreamingSampleResult> {
577    let mut rows_seen = 0u64;
578    let mut rows_selected = 0u64;
579    let mut fk_orphans = 0u64;
580
581    // Temp file for selected rows
582    let temp_path = selected_dir.join(format!("{}.rows", table_name));
583
584    // Track PKs of selected rows (for children's FK checks)
585    let mut selected_pk_hashes: Vec<u64> = Vec::new();
586
587    match sample_mode {
588        SampleMode::Percent(p) => {
589            // Bernoulli sampling: decide immediately for each row
590            let prob = p as f64 / 100.0;
591            let mut spill: Option<RowSpillWriter> = None;
592
593            for_each_data_row(
594                table_file,
595                table_schema,
596                config.dialect,
597                RowExtraction::PkFk,
598                |row| {
599                    rows_seen += 1;
600
601                    // FK check
602                    if !passes_fk_or_bail(
603                        &row,
604                        table_schema,
605                        table_id,
606                        table_name,
607                        config,
608                        runtimes,
609                        cyclic_set,
610                    )? {
611                        fk_orphans += 1;
612                        return Ok(RowFlow::Continue);
613                    }
614
615                    // Bernoulli sample
616                    if rng.random::<f64>() < prob
617                        && remaining_capacity.is_none_or(|max| rows_selected < max as u64)
618                    {
619                        if spill.is_none() {
620                            spill = Some(RowSpillWriter::create(&temp_path)?);
621                        }
622                        spill.as_mut().unwrap().write_row(row.format(), row.raw())?;
623
624                        // Track PK hash
625                        if let Some(pk) = row.pk() {
626                            selected_pk_hashes.push(hash_pk_tuple(pk));
627                        }
628                        rows_selected += 1;
629                    }
630
631                    Ok(RowFlow::Continue)
632                },
633            )?;
634
635            if let Some(spill) = spill {
636                spill.finish()?;
637            }
638        }
639        SampleMode::Rows(n) => {
640            // Reservoir sampling: collect eligible row indices in first pass,
641            // then write selected rows in second pass
642            let capacity = remaining_capacity.map_or(n, |max| n.min(max));
643            let mut reservoir: Reservoir<(u64, Option<u64>)> =
644                Reservoir::new(capacity, StdRng::from_rng(&mut *rng));
645
646            // First pass: build reservoir of (row_index, pk_hash)
647            for_each_data_row(
648                table_file,
649                table_schema,
650                config.dialect,
651                RowExtraction::PkFk,
652                |row| {
653                    let current_idx = rows_seen;
654                    rows_seen += 1;
655
656                    if !passes_fk_or_bail(
657                        &row,
658                        table_schema,
659                        table_id,
660                        table_name,
661                        config,
662                        runtimes,
663                        cyclic_set,
664                    )? {
665                        fk_orphans += 1;
666                        return Ok(RowFlow::Continue);
667                    }
668
669                    let pk_hash = row.pk().map(hash_pk_tuple);
670                    reservoir.consider((current_idx, pk_hash));
671                    Ok(RowFlow::Continue)
672                },
673            )?;
674
675            // Extract selected indices and PKs from reservoir
676            let selected_items = reservoir.into_items();
677            if selected_items.is_empty() {
678                return Ok(StreamingSampleResult {
679                    rows_seen,
680                    rows_selected: 0,
681                    fk_orphans,
682                    pk_hashes: Vec::new(),
683                });
684            }
685
686            // Collect PK hashes and sort indices for second pass
687            let mut selected_indices: Vec<u64> = Vec::with_capacity(selected_items.len());
688            for (idx, pk_hash) in selected_items {
689                if let Some(h) = pk_hash {
690                    selected_pk_hashes.push(h);
691                }
692                selected_indices.push(idx);
693            }
694            selected_indices.sort_unstable();
695
696            // Second pass: write selected rows to temp file
697            let mut spill = RowSpillWriter::create(&temp_path)?;
698            let mut current_row_idx = 0u64;
699            let mut select_iter = selected_indices.iter().peekable();
700
701            for_each_data_row(
702                table_file,
703                table_schema,
704                config.dialect,
705                RowExtraction::PkFk,
706                |row| {
707                    let Some(&&next_idx) = select_iter.peek() else {
708                        return Ok(RowFlow::Stop); // All selected rows written
709                    };
710                    if current_row_idx == next_idx {
711                        spill.write_row(row.format(), row.raw())?;
712                        rows_selected += 1;
713                        select_iter.next();
714                    }
715                    current_row_idx += 1;
716                    Ok(RowFlow::Continue)
717                },
718            )?;
719
720            spill.finish()?;
721        }
722    }
723
724    if config.preserve_relations && has_self_referential_fk(table_schema, table_id) {
725        extend_self_reference_closure(
726            table_file,
727            table_schema,
728            table_id,
729            config,
730            selected_dir,
731            &temp_path,
732            &mut selected_pk_hashes,
733            &mut rows_selected,
734            remaining_capacity,
735        )?;
736    }
737
738    Ok(StreamingSampleResult {
739        rows_seen,
740        rows_selected,
741        fk_orphans,
742        pk_hashes: selected_pk_hashes,
743    })
744}
745
746/// Return true when a table has an FK that references the table itself.
747fn has_self_referential_fk(table_schema: &crate::schema::TableSchema, table_id: TableId) -> bool {
748    table_schema
749        .foreign_keys
750        .iter()
751        .any(|fk| fk.referenced_table_id == Some(table_id))
752}
753
754/// Add selected ancestors for self-referencing FKs.
755///
756/// Self references cannot use the normal parent-table PK set because the
757/// table is still being sampled. The initial sample is retained, then each
758/// pass adds one level of missing selected ancestors to its spill file. This
759/// keeps only selected PK hashes in memory and works when parents appear
760/// after children in the dump.
761#[allow(clippy::too_many_arguments)]
762fn extend_self_reference_closure(
763    table_file: &Path,
764    table_schema: &crate::schema::TableSchema,
765    table_id: TableId,
766    config: &SampleConfig,
767    selected_dir: &Path,
768    temp_path: &Path,
769    selected_pk_hashes: &mut Vec<u64>,
770    rows_selected: &mut u64,
771    remaining_capacity: Option<usize>,
772) -> anyhow::Result<()> {
773    if selected_pk_hashes.is_empty() {
774        return Ok(());
775    }
776
777    let mut included: PkHashSet = selected_pk_hashes.iter().copied().collect();
778    let mut required_parents = PkHashSet::default();
779
780    // Find direct parents for the initially selected rows.
781    for_each_data_row(
782        table_file,
783        table_schema,
784        config.dialect,
785        RowExtraction::PkFk,
786        |row| {
787            if row
788                .pk()
789                .is_some_and(|pk| included.contains(&hash_pk_tuple(pk)))
790            {
791                add_self_referenced_parent_hashes(
792                    &row,
793                    table_schema,
794                    table_id,
795                    &mut required_parents,
796                );
797            }
798            Ok(RowFlow::Continue)
799        },
800    )?;
801
802    let closure_path = temp_path.to_path_buf();
803    let mut pass = 0usize;
804
805    loop {
806        let pending: PkHashSet = required_parents
807            .iter()
808            .filter(|hash| !included.contains(hash))
809            .copied()
810            .collect();
811        if pending.is_empty() {
812            break;
813        }
814
815        let next_path = selected_dir.join(format!("{}.closure-{}.rows", table_schema.name, pass));
816        let mut writer = RowSpillWriter::create(&next_path)?;
817        copy_spill_rows(&closure_path, &mut writer)?;
818        let mut added = 0usize;
819
820        for_each_data_row(
821            table_file,
822            table_schema,
823            config.dialect,
824            RowExtraction::PkFk,
825            |row| {
826                let Some(pk) = row.pk() else {
827                    return Ok(RowFlow::Continue);
828                };
829                let pk_hash = hash_pk_tuple(pk);
830                if !pending.contains(&pk_hash) {
831                    return Ok(RowFlow::Continue);
832                }
833                if remaining_capacity.is_some_and(|max| *rows_selected >= max as u64) {
834                    return Ok(RowFlow::SkipStatement);
835                }
836
837                writer.write_row(row.format(), row.raw())?;
838                included.insert(pk_hash);
839                selected_pk_hashes.push(pk_hash);
840                *rows_selected += 1;
841                added += 1;
842                add_self_referenced_parent_hashes(
843                    &row,
844                    table_schema,
845                    table_id,
846                    &mut required_parents,
847                );
848                Ok(RowFlow::Continue)
849            },
850        )?;
851
852        writer.finish()?;
853        // `rename` replaces an existing destination on Unix but not Windows.
854        // This is an internal spill file, so remove the previous generation
855        // first and keep the closure update portable.
856        fs::remove_file(&closure_path)?;
857        fs::rename(&next_path, &closure_path)?;
858
859        if added == 0 {
860            if config.strict_fk {
861                anyhow::bail!(
862                    "FK integrity violation in table '{}': selected row references missing parent",
863                    table_schema.name
864                );
865            }
866            break;
867        }
868        pass += 1;
869    }
870
871    Ok(())
872}
873
874/// Copy a spill file into an open spill writer without materializing all rows.
875fn copy_spill_rows(path: &Path, writer: &mut RowSpillWriter) -> anyhow::Result<()> {
876    let mut reader = RowSpillReader::open(path)?;
877    while let Some((format, raw)) = reader.next_row()? {
878        writer.write_row(format, &raw)?;
879    }
880    Ok(())
881}
882
883/// Add the parent PKs referenced by this table's self-referencing FKs.
884fn add_self_referenced_parent_hashes(
885    row: &UnifiedRow,
886    table_schema: &crate::schema::TableSchema,
887    table_id: TableId,
888    parent_hashes: &mut PkHashSet,
889) {
890    for (fk_ref, fk_tuple) in row.fk_values() {
891        if table_schema
892            .foreign_keys
893            .get(fk_ref.fk_index as usize)
894            .is_some_and(|fk| fk.referenced_table_id == Some(table_id))
895        {
896            parent_hashes.insert(hash_pk_tuple(fk_tuple));
897        }
898    }
899}
900
901/// Check FK membership for a unified row (works with both INSERT and COPY rows)
902/// Uses hash-based lookup for memory efficiency.
903fn check_unified_fk_membership(
904    row: &UnifiedRow,
905    table_schema: &crate::schema::TableSchema,
906    runtimes: &AHashMap<TableId, TableRuntime>,
907    cyclic_set: &ahash::AHashSet<TableId>,
908    current_table_id: &TableId,
909) -> (bool, bool) {
910    let mut passes = true;
911    let mut is_orphan = false;
912
913    for (fk_ref, fk_tuple) in row.fk_values() {
914        if let Some(fk) = table_schema.foreign_keys.get(fk_ref.fk_index as usize) {
915            if let Some(parent_id) = fk.referenced_table_id {
916                // A self-referencing table is handled by
917                // `extend_self_reference_closure` after initial sampling.
918                if parent_id == *current_table_id {
919                    continue;
920                }
921                // Skip FK check for cyclic tables
922                if cyclic_set.contains(&parent_id) && cyclic_set.contains(current_table_id) {
923                    continue;
924                }
925
926                // Check if parent row exists in parent's pk_set using hash lookup
927                if let Some(parent_runtime) = runtimes.get(&parent_id) {
928                    let fk_hash = hash_pk_tuple(fk_tuple);
929                    if !parent_runtime.pk_set.contains(&fk_hash) {
930                        passes = false;
931                        is_orphan = true;
932                        break;
933                    }
934                }
935            }
936        }
937    }
938
939    (passes, is_orphan)
940}
941
942/// Write sampled output
943fn write_output(
944    config: &SampleConfig,
945    _graph: &SchemaGraph,
946    table_order: &[TableId],
947    runtimes: &AHashMap<TableId, TableRuntime>,
948    tables_dir: &Path,
949    stats: &SampleStats,
950) -> anyhow::Result<()> {
951    let mut writer: Box<dyn Write> = match &config.output {
952        Some(path) => {
953            if let Some(parent) = path.parent() {
954                fs::create_dir_all(parent)?;
955            }
956            Box::new(BufWriter::with_capacity(256 * 1024, File::create(path)?))
957        }
958        None => Box::new(BufWriter::new(std::io::stdout())),
959    };
960
961    // Write header comment
962    write_header(&mut writer, config, stats)?;
963
964    // Write dialect-specific header
965    write_dialect_header(&mut writer, config.dialect)?;
966
967    // Write schema for each table (if enabled)
968    if config.include_schema {
969        for &table_id in table_order {
970            let runtime = match runtimes.get(&table_id) {
971                Some(r) if !r.skip && r.rows_selected > 0 => r,
972                _ => continue,
973            };
974
975            let table_file = tables_dir.join(format!("{}.sql", runtime.name));
976            if !table_file.exists() {
977                continue;
978            }
979
980            // Copy schema statements from table file
981            let file = File::open(&table_file)?;
982            let mut parser = Parser::with_dialect(file, 64 * 1024, config.dialect);
983
984            while let Some(stmt) = parser.read_statement()? {
985                let (stmt_type, _) =
986                    Parser::<&[u8]>::parse_statement_with_dialect(&stmt, config.dialect);
987
988                if stmt_type.is_schema() {
989                    writer.write_all(&stmt)?;
990                    writer.write_all(b"\n")?;
991                }
992            }
993        }
994    }
995
996    // Write data for each table (reading from temp files instead of memory)
997    for &table_id in table_order {
998        let runtime = match runtimes.get(&table_id) {
999            Some(r) if !r.skip && r.rows_selected > 0 && r.selected_temp_path.is_some() => r,
1000            _ => continue,
1001        };
1002
1003        let table_name = &runtime.name;
1004        let row_count = runtime.rows_selected;
1005
1006        writeln!(writer, "\n-- Data: {} ({} rows)", table_name, row_count)?;
1007
1008        // Get the table name quoting based on dialect
1009        let quoted_name = quote_ident(config.dialect, table_name);
1010
1011        // Read rows from temp file and write INSERTs in chunks
1012        let temp_path = runtime.selected_temp_path.as_ref().unwrap();
1013        let mut spill_reader = RowSpillReader::open(temp_path)?;
1014
1015        const CHUNK_SIZE: usize = 1000;
1016        let mut chunk_buffer: Vec<(RowFormat, Vec<u8>)> = Vec::with_capacity(CHUNK_SIZE);
1017
1018        while let Some((format, row_bytes)) = spill_reader.next_row()? {
1019            chunk_buffer.push((format, row_bytes));
1020
1021            if chunk_buffer.len() >= CHUNK_SIZE {
1022                write_insert_chunk(&mut writer, &quoted_name, &chunk_buffer, config.dialect)?;
1023                chunk_buffer.clear();
1024            }
1025        }
1026
1027        // Write remaining rows
1028        if !chunk_buffer.is_empty() {
1029            write_insert_chunk(&mut writer, &quoted_name, &chunk_buffer, config.dialect)?;
1030        }
1031    }
1032
1033    // Write dialect-specific footer
1034    write_dialect_footer(&mut writer, config.dialect)?;
1035
1036    writer.flush()?;
1037
1038    Ok(())
1039}
1040
1041/// Write header comment
1042fn write_header<W: Write>(
1043    writer: &mut W,
1044    config: &SampleConfig,
1045    stats: &SampleStats,
1046) -> std::io::Result<()> {
1047    writeln!(writer, "-- Sampled from: {}", config.input.display())?;
1048    writeln!(
1049        writer,
1050        "-- Date: {}",
1051        chrono::Local::now().format("%Y-%m-%d %H:%M:%S")
1052    )?;
1053    writeln!(
1054        writer,
1055        "-- Mode: {:?}{}",
1056        config.mode,
1057        if config.preserve_relations {
1058            ", preserve-relations"
1059        } else {
1060            ""
1061        }
1062    )?;
1063    writeln!(writer, "-- Seed: {}", config.seed)?;
1064    writeln!(writer, "-- Dialect: {}", config.dialect)?;
1065    writeln!(writer, "--")?;
1066    writeln!(writer, "-- Statistics:")?;
1067    writeln!(writer, "--   Tables sampled: {}", stats.tables_sampled)?;
1068    writeln!(writer, "--   Tables skipped: {}", stats.tables_skipped)?;
1069
1070    let percent = if stats.total_rows_seen > 0 {
1071        (stats.total_rows_selected as f64 / stats.total_rows_seen as f64) * 100.0
1072    } else {
1073        0.0
1074    };
1075    writeln!(
1076        writer,
1077        "--   Total rows: {} (from {} original, {:.1}%)",
1078        stats.total_rows_selected, stats.total_rows_seen, percent
1079    )?;
1080
1081    if stats.fk_orphans_rejected > 0 {
1082        writeln!(
1083            writer,
1084            "--   FK orphans rejected: {}",
1085            stats.fk_orphans_rejected
1086        )?;
1087    }
1088
1089    if !stats.warnings.is_empty() {
1090        writeln!(writer, "--   Warnings: {}", stats.warnings.len())?;
1091    }
1092
1093    writeln!(writer)?;
1094
1095    Ok(())
1096}