1mod 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#[derive(Debug, Clone, Copy)]
31pub enum SampleMode {
32 Percent(u32),
34 Rows(usize),
36}
37
38#[derive(Debug)]
40pub struct SampleConfig {
41 pub input: PathBuf,
43 pub output: Option<PathBuf>,
45 pub dialect: SqlDialect,
47 pub mode: SampleMode,
49 pub preserve_relations: bool,
51 pub tables_filter: Option<Vec<String>>,
53 pub exclude: Vec<String>,
55 pub root_tables: Vec<String>,
57 pub include_global: GlobalTableMode,
59 pub seed: u64,
61 pub dry_run: bool,
63 pub progress: bool,
65 pub config_file: Option<PathBuf>,
67 pub max_total_rows: Option<usize>,
69 pub strict_fk: bool,
71 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#[derive(Debug, Default, serde::Serialize)]
100pub struct SampleStats {
101 pub tables_sampled: usize,
103 pub tables_skipped: usize,
105 pub total_rows_selected: u64,
107 pub total_rows_seen: u64,
109 pub table_stats: Vec<TableSampleStats>,
111 pub warnings: Vec<String>,
113 pub fk_orphans_rejected: u64,
115}
116
117#[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
126struct TableRuntime {
128 name: String,
130 pk_set: PkHashSet,
132 rows_seen: u64,
134 rows_selected: u64,
136 skip: bool,
138 classification: TableClassification,
140 fk_orphans: u64,
142 selected_temp_path: Option<PathBuf>,
144}
145
146pub fn run(config: SampleConfig) -> anyhow::Result<SampleStats> {
148 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 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 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 let cyclic_set: ahash::AHashSet<TableId> = cyclic_tables.iter().copied().collect();
190
191 let explicit_roots: ahash::AHashSet<String> = config
193 .root_tables
194 .iter()
195 .map(|s| s.to_lowercase())
196 .collect();
197
198 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 let selected_dir = temp_dir.path().join("selected");
222 fs::create_dir_all(&selected_dir)?;
223
224 if config.progress {
226 eprintln!(
227 "Sampling {} tables in dependency order...",
228 topo_order.len()
229 );
230 }
231
232 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 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 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 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 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 total_selected += result.rows_selected;
312
313 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 for pk_hash in result.pk_hashes {
324 runtime.pk_set.insert(pk_hash);
325 }
326
327 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 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 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
380fn 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 if explicit_roots
390 .iter()
391 .any(|pattern| table_name_matches(pattern, name))
392 {
393 return TableClassification::Root;
394 }
395
396 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 if graph.parents[table_id.0 as usize].is_empty() {
406 return TableClassification::Root;
407 }
408
409 DefaultClassifier::classify(name)
411}
412
413fn should_skip_table(
415 name: &str,
416 config: &SampleConfig,
417 yaml_config: &Option<SampleYamlConfig>,
418 classification: TableClassification,
419) -> bool {
420 if config
422 .exclude
423 .iter()
424 .any(|pattern| table_name_matches(pattern, name))
425 {
426 return true;
427 }
428
429 if let Some(ref yc) = yaml_config {
431 if yc.should_skip(name) {
432 return true;
433 }
434 }
435
436 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 if classification == TableClassification::System {
448 return true;
449 }
450
451 false
452}
453
454fn 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
467fn 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
498fn get_table_sample_mode(
500 name: &str,
501 config: &SampleConfig,
502 yaml_config: &Option<SampleYamlConfig>,
503) -> SampleMode {
504 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 config.mode
516}
517
518struct StreamingSampleResult {
520 rows_seen: u64,
521 rows_selected: u64,
522 fk_orphans: u64,
523 pk_hashes: Vec<u64>,
525}
526
527fn 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#[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 let temp_path = selected_dir.join(format!("{}.rows", table_name));
583
584 let mut selected_pk_hashes: Vec<u64> = Vec::new();
586
587 match sample_mode {
588 SampleMode::Percent(p) => {
589 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 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 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 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 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 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 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 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 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); };
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
746fn 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#[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 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 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
874fn 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
883fn 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
901fn 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 if parent_id == *current_table_id {
919 continue;
920 }
921 if cyclic_set.contains(&parent_id) && cyclic_set.contains(current_table_id) {
923 continue;
924 }
925
926 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
942fn 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(&mut writer, config, stats)?;
963
964 write_dialect_header(&mut writer, config.dialect)?;
966
967 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 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 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 let quoted_name = quote_ident(config.dialect, table_name);
1010
1011 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, "ed_name, &chunk_buffer, config.dialect)?;
1023 chunk_buffer.clear();
1024 }
1025 }
1026
1027 if !chunk_buffer.is_empty() {
1029 write_insert_chunk(&mut writer, "ed_name, &chunk_buffer, config.dialect)?;
1030 }
1031 }
1032
1033 write_dialect_footer(&mut writer, config.dialect)?;
1035
1036 writer.flush()?;
1037
1038 Ok(())
1039}
1040
1041fn 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}