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, parse_mysql_insert_rows, ParsedRow, PkHashSet};
15use crate::parser::postgres_copy::{parse_copy_columns, parse_postgres_copy_rows, ParsedCopyRow};
16use crate::parser::{ContentFilter, Parser, SqlDialect, StatementType};
17use crate::schema::{SchemaBuilder, SchemaGraph, TableId};
18use crate::splitter::Splitter;
19use ahash::AHashMap;
20use indicatif::{ProgressBar, ProgressStyle};
21use rand::rngs::StdRng;
22use rand::{Rng, SeedableRng};
23use std::fs::{self, File};
24use std::io::{BufWriter, Write};
25use std::path::{Path, PathBuf};
26use tempfile::TempDir;
27
28#[derive(Debug, Clone, Copy)]
30pub enum SampleMode {
31 Percent(u32),
33 Rows(usize),
35}
36
37#[derive(Debug)]
39pub struct SampleConfig {
40 pub input: PathBuf,
42 pub output: Option<PathBuf>,
44 pub dialect: SqlDialect,
46 pub mode: SampleMode,
48 pub preserve_relations: bool,
50 pub tables_filter: Option<Vec<String>>,
52 pub exclude: Vec<String>,
54 pub root_tables: Vec<String>,
56 pub include_global: GlobalTableMode,
58 pub seed: u64,
60 pub dry_run: bool,
62 pub progress: bool,
64 pub config_file: Option<PathBuf>,
66 pub max_total_rows: Option<usize>,
68 pub strict_fk: bool,
70 pub include_schema: bool,
72}
73
74impl Default for SampleConfig {
75 fn default() -> Self {
76 Self {
77 input: PathBuf::new(),
78 output: None,
79 dialect: SqlDialect::MySql,
80 mode: SampleMode::Percent(10),
81 preserve_relations: false,
82 tables_filter: None,
83 exclude: Vec::new(),
84 root_tables: Vec::new(),
85 include_global: GlobalTableMode::Lookups,
86 seed: rand::random(),
87 dry_run: false,
88 progress: false,
89 config_file: None,
90 max_total_rows: None,
91 strict_fk: false,
92 include_schema: true,
93 }
94 }
95}
96
97#[derive(Debug, Default, serde::Serialize)]
99pub struct SampleStats {
100 pub tables_sampled: usize,
102 pub tables_skipped: usize,
104 pub total_rows_selected: u64,
106 pub total_rows_seen: u64,
108 pub table_stats: Vec<TableSampleStats>,
110 pub warnings: Vec<String>,
112 pub fk_orphans_rejected: u64,
114}
115
116#[derive(Debug, Clone, serde::Serialize)]
118pub struct TableSampleStats {
119 pub name: String,
120 pub rows_seen: u64,
121 pub rows_selected: u64,
122 pub classification: TableClassification,
123}
124
125struct TableRuntime {
127 name: String,
129 pk_set: PkHashSet,
131 rows_seen: u64,
133 rows_selected: u64,
135 skip: bool,
137 classification: TableClassification,
139 fk_orphans: u64,
141 selected_temp_path: Option<PathBuf>,
143}
144
145enum UnifiedRow {
147 Insert(ParsedRow),
148 Copy(ParsedCopyRow),
149}
150
151#[derive(Debug, Clone, Copy, PartialEq)]
153enum RowFormat {
154 Insert,
155 Copy,
156}
157
158impl UnifiedRow {
159 fn pk(&self) -> Option<&smallvec::SmallVec<[crate::parser::mysql_insert::PkValue; 2]>> {
160 match self {
161 UnifiedRow::Insert(r) => r.pk.as_ref(),
162 UnifiedRow::Copy(r) => r.pk.as_ref(),
163 }
164 }
165
166 fn fk_values(
167 &self,
168 ) -> &[(
169 crate::parser::mysql_insert::FkRef,
170 smallvec::SmallVec<[crate::parser::mysql_insert::PkValue; 2]>,
171 )] {
172 match self {
173 UnifiedRow::Insert(r) => &r.fk_values,
174 UnifiedRow::Copy(r) => &r.fk_values,
175 }
176 }
177}
178
179pub fn run(config: SampleConfig) -> anyhow::Result<SampleStats> {
181 let yaml_config = if let Some(ref path) = config.config_file {
183 Some(SampleYamlConfig::load(path)?)
184 } else {
185 None
186 };
187
188 let mut rng = StdRng::seed_from_u64(config.seed);
189 let mut stats = SampleStats::default();
190
191 let file_size = std::fs::metadata(&config.input)?.len();
193
194 let progress_bar = if config.progress {
196 let pb = ProgressBar::new(file_size);
197 pb.set_style(
198 ProgressStyle::with_template(
199 "{spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] {bytes}/{total_bytes} ({percent}%) {msg}",
200 )
201 .unwrap()
202 .progress_chars("█▓▒░ ")
203 .tick_chars("⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"),
204 );
205 pb.enable_steady_tick(std::time::Duration::from_millis(100));
206 pb.set_message("Splitting dump...");
207 Some(pb)
208 } else {
209 None
210 };
211
212 let temp_dir = TempDir::new()?;
214 let tables_dir = temp_dir.path().join("tables");
215
216 let mut splitter = Splitter::new(config.input.clone(), tables_dir.clone())
217 .with_dialect(config.dialect)
218 .with_content_filter(ContentFilter::All);
219
220 if let Some(ref pb) = progress_bar {
221 let pb_clone = pb.clone();
222 splitter = splitter.with_progress(move |bytes| {
223 pb_clone.set_position(bytes);
224 });
225 }
226
227 let split_stats = splitter.split()?;
228
229 if let Some(ref pb) = progress_bar {
231 pb.finish_and_clear();
232 }
233
234 if config.progress {
235 eprintln!(
236 "Split complete: {} tables, {} statements",
237 split_stats.tables_found, split_stats.statements_processed
238 );
239 }
240
241 if config.progress {
243 eprintln!("Building schema graph...");
244 }
245
246 let graph = build_schema_graph(&tables_dir, &config)?;
247
248 let (topo_order, cyclic_tables) = graph.processing_order();
249
250 if !cyclic_tables.is_empty() {
251 let names: Vec<_> = cyclic_tables
252 .iter()
253 .filter_map(|&id| graph.table_name(id))
254 .collect();
255 let msg = format!(
256 "Warning: {} tables have FK cycles (intra-cycle FK enforcement disabled): {:?}",
257 cyclic_tables.len(),
258 names
259 );
260 if config.progress {
261 eprintln!("{}", msg);
262 }
263 stats.warnings.push(msg);
264 }
265
266 let cyclic_set: ahash::AHashSet<TableId> = cyclic_tables.iter().copied().collect();
268
269 let explicit_roots: ahash::AHashSet<String> = config
271 .root_tables
272 .iter()
273 .map(|s| s.to_lowercase())
274 .collect();
275
276 let mut runtimes: AHashMap<TableId, TableRuntime> = AHashMap::new();
278 for table in graph.schema.iter() {
279 let classification =
280 determine_classification(&table.name, &graph, table.id, &yaml_config, &explicit_roots);
281 let skip = should_skip_table(&table.name, &config, &yaml_config, classification);
282
283 runtimes.insert(
284 table.id,
285 TableRuntime {
286 name: table.name.clone(),
287 pk_set: PkHashSet::default(),
288 rows_seen: 0,
289 rows_selected: 0,
290 skip,
291 classification,
292 fk_orphans: 0,
293 selected_temp_path: None,
294 },
295 );
296 }
297
298 let selected_dir = temp_dir.path().join("selected");
300 fs::create_dir_all(&selected_dir)?;
301
302 if config.progress {
304 eprintln!(
305 "Sampling {} tables in dependency order...",
306 topo_order.len()
307 );
308 }
309
310 let all_tables: Vec<TableId> = topo_order.into_iter().chain(cyclic_tables).collect();
312
313 let mut total_selected: u64 = 0;
314
315 for table_id in &all_tables {
316 let table_schema = match graph.schema.table(*table_id) {
317 Some(s) => s,
318 None => continue,
319 };
320
321 let (should_skip, table_name, classification) = {
323 let runtime = match runtimes.get(table_id) {
324 Some(r) => r,
325 None => continue,
326 };
327 (runtime.skip, runtime.name.clone(), runtime.classification)
328 };
329
330 if should_skip {
331 stats.tables_skipped += 1;
332 continue;
333 }
334
335 let sample_mode = match classification {
337 TableClassification::Lookup => {
338 match config.include_global {
339 GlobalTableMode::None => {
340 stats.tables_skipped += 1;
341 continue;
342 }
343 GlobalTableMode::Lookups | GlobalTableMode::All => {
344 SampleMode::Percent(100)
346 }
347 }
348 }
349 TableClassification::System => {
350 stats.tables_skipped += 1;
351 continue;
352 }
353 _ => get_table_sample_mode(&table_name, &config, &yaml_config),
354 };
355
356 let table_file = tables_dir.join(format!("{}.sql", table_name));
357 if !table_file.exists() {
358 continue;
359 }
360
361 let result = sample_table_streaming(
363 &table_file,
364 table_schema,
365 *table_id,
366 &table_name,
367 sample_mode,
368 &config,
369 &runtimes,
370 &cyclic_set,
371 &selected_dir,
372 &mut rng,
373 )?;
374
375 if let Some(max) = config.max_total_rows {
377 if total_selected + result.rows_selected > max as u64 {
378 let msg = format!(
379 "Warning: Reached max_total_rows limit ({}) at table '{}'",
380 max, table_name
381 );
382 stats.warnings.push(msg);
383 break;
384 }
385 }
386
387 total_selected += result.rows_selected;
389
390 let runtime = runtimes.get_mut(table_id).unwrap();
392 runtime.rows_seen = result.rows_seen;
393 runtime.rows_selected = result.rows_selected;
394 runtime.fk_orphans = result.fk_orphans;
395
396 for pk_hash in result.pk_hashes {
398 runtime.pk_set.insert(pk_hash);
399 }
400
401 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 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 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
444fn 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
477fn 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 if explicit_roots.contains(&name.to_lowercase()) {
487 return TableClassification::Root;
488 }
489
490 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 if graph.parents[table_id.0 as usize].is_empty() {
500 return TableClassification::Root;
501 }
502
503 DefaultClassifier::classify(name)
505}
506
507fn 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 if config
518 .exclude
519 .iter()
520 .any(|e| e.to_lowercase() == name_lower)
521 {
522 return true;
523 }
524
525 if let Some(ref yc) = yaml_config {
527 if yc.should_skip(name) {
528 return true;
529 }
530 }
531
532 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 if classification == TableClassification::System {
541 return true;
542 }
543
544 false
545}
546
547fn get_table_sample_mode(
549 name: &str,
550 config: &SampleConfig,
551 yaml_config: &Option<SampleYamlConfig>,
552) -> SampleMode {
553 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 config.mode
565}
566
567struct StreamingSampleResult {
569 rows_seen: u64,
570 rows_selected: u64,
571 fk_orphans: u64,
572 pk_hashes: Vec<u64>,
574}
575
576#[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 let temp_path = selected_dir.join(format!("{}.rows", table_name));
599 let mut temp_writer: Option<BufWriter<File>> = None;
600
601 let mut selected_pk_hashes: Vec<u64> = Vec::new();
603
604 let mut copy_columns: Vec<String> = Vec::new();
606
607 match sample_mode {
608 SampleMode::Percent(p) => {
609 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_mysql_insert_rows(&stmt, table_schema)?;
622 for row in rows {
623 rows_seen += 1;
624
625 if config.preserve_relations {
627 let unified = UnifiedRow::Insert(row.clone());
628 let (passes, orphan) = check_unified_fk_membership(
629 &unified,
630 table_schema,
631 runtimes,
632 cyclic_set,
633 &table_id,
634 );
635 if !passes {
636 fk_orphans += 1;
637 if orphan && config.strict_fk {
638 anyhow::bail!(
639 "FK integrity violation in table '{}': row references missing parent",
640 table_name
641 );
642 }
643 continue;
644 }
645 }
646
647 if rng.gen::<f64>() < prob {
649 if temp_writer.is_none() {
651 temp_writer = Some(BufWriter::new(File::create(&temp_path)?));
652 }
653 let writer = temp_writer.as_mut().unwrap();
654 writer.write_all(&[0u8])?;
656 writer.write_all(&row.raw)?;
657 writer.write_all(b"\n")?;
658
659 if let Some(pk) = &row.pk {
661 selected_pk_hashes.push(hash_pk_tuple(pk));
662 }
663 rows_selected += 1;
664 }
665 }
666 }
667 StatementType::Copy => {
668 let header = String::from_utf8_lossy(&stmt);
669 copy_columns = parse_copy_columns(&header);
670 }
671 StatementType::Unknown if config.dialect == SqlDialect::Postgres => {
672 if stmt.ends_with(b"\\.\n") || stmt.ends_with(b"\\.\r\n") {
673 let rows = parse_postgres_copy_rows(
674 &stmt,
675 table_schema,
676 copy_columns.clone(),
677 )?;
678 for row in rows {
679 rows_seen += 1;
680
681 if config.preserve_relations {
682 let unified = UnifiedRow::Copy(row.clone());
683 let (passes, orphan) = check_unified_fk_membership(
684 &unified,
685 table_schema,
686 runtimes,
687 cyclic_set,
688 &table_id,
689 );
690 if !passes {
691 fk_orphans += 1;
692 if orphan && config.strict_fk {
693 anyhow::bail!(
694 "FK integrity violation in table '{}': row references missing parent",
695 table_name
696 );
697 }
698 continue;
699 }
700 }
701
702 if rng.gen::<f64>() < prob {
703 if temp_writer.is_none() {
704 temp_writer =
705 Some(BufWriter::new(File::create(&temp_path)?));
706 }
707 let writer = temp_writer.as_mut().unwrap();
708 writer.write_all(&[1u8])?;
709 writer.write_all(&row.raw)?;
710 writer.write_all(b"\n")?;
711
712 if let Some(pk) = &row.pk {
713 selected_pk_hashes.push(hash_pk_tuple(pk));
714 }
715 rows_selected += 1;
716 }
717 }
718 }
719 }
720 _ => {}
721 }
722 }
723 }
724 SampleMode::Rows(n) => {
725 let mut reservoir: Reservoir<(u64, RowFormat, Option<u64>)> =
728 Reservoir::new(n, StdRng::from_rng(&mut *rng)?);
729
730 let file = File::open(table_file)?;
732 let mut parser = Parser::with_dialect(file, 64 * 1024, config.dialect);
733
734 while let Some(stmt) = parser.read_statement()? {
735 let (stmt_type, _) =
736 Parser::<&[u8]>::parse_statement_with_dialect(&stmt, config.dialect);
737
738 match stmt_type {
739 StatementType::Insert => {
740 let rows = parse_mysql_insert_rows(&stmt, table_schema)?;
741 for row in rows {
742 let current_idx = rows_seen;
743 rows_seen += 1;
744
745 if config.preserve_relations {
746 let unified = UnifiedRow::Insert(row.clone());
747 let (passes, orphan) = check_unified_fk_membership(
748 &unified,
749 table_schema,
750 runtimes,
751 cyclic_set,
752 &table_id,
753 );
754 if !passes {
755 fk_orphans += 1;
756 if orphan && config.strict_fk {
757 anyhow::bail!(
758 "FK integrity violation in table '{}': row references missing parent",
759 table_name
760 );
761 }
762 continue;
763 }
764 }
765
766 let pk_hash = row.pk.as_ref().map(hash_pk_tuple);
767 reservoir.consider((current_idx, RowFormat::Insert, pk_hash));
768 }
769 }
770 StatementType::Copy => {
771 let header = String::from_utf8_lossy(&stmt);
772 copy_columns = parse_copy_columns(&header);
773 }
774 StatementType::Unknown if config.dialect == SqlDialect::Postgres => {
775 if stmt.ends_with(b"\\.\n") || stmt.ends_with(b"\\.\r\n") {
776 let rows = parse_postgres_copy_rows(
777 &stmt,
778 table_schema,
779 copy_columns.clone(),
780 )?;
781 for row in rows {
782 let current_idx = rows_seen;
783 rows_seen += 1;
784
785 if config.preserve_relations {
786 let unified = UnifiedRow::Copy(row.clone());
787 let (passes, orphan) = check_unified_fk_membership(
788 &unified,
789 table_schema,
790 runtimes,
791 cyclic_set,
792 &table_id,
793 );
794 if !passes {
795 fk_orphans += 1;
796 if orphan && config.strict_fk {
797 anyhow::bail!(
798 "FK integrity violation in table '{}': row references missing parent",
799 table_name
800 );
801 }
802 continue;
803 }
804 }
805
806 let pk_hash = row.pk.as_ref().map(hash_pk_tuple);
807 reservoir.consider((current_idx, RowFormat::Copy, pk_hash));
808 }
809 }
810 }
811 _ => {}
812 }
813 }
814
815 let selected_items = reservoir.into_items();
817 if selected_items.is_empty() {
818 return Ok(StreamingSampleResult {
819 rows_seen,
820 rows_selected: 0,
821 fk_orphans,
822 pk_hashes: Vec::new(),
823 });
824 }
825
826 let mut selected_indices: Vec<(u64, RowFormat)> =
828 Vec::with_capacity(selected_items.len());
829 for (idx, format, pk_hash) in selected_items {
830 if let Some(h) = pk_hash {
831 selected_pk_hashes.push(h);
832 }
833 selected_indices.push((idx, format));
834 }
835 selected_indices.sort_by_key(|(idx, _)| *idx);
836
837 let file = File::open(table_file)?;
839 let mut parser = Parser::with_dialect(file, 64 * 1024, config.dialect);
840 let mut current_row_idx = 0u64;
841 let mut select_iter = selected_indices.iter().peekable();
842
843 temp_writer = Some(BufWriter::new(File::create(&temp_path)?));
844 let writer = temp_writer.as_mut().unwrap();
845
846 while let Some(stmt) = parser.read_statement()? {
847 if select_iter.peek().is_none() {
848 break; }
850
851 let (stmt_type, _) =
852 Parser::<&[u8]>::parse_statement_with_dialect(&stmt, config.dialect);
853
854 match stmt_type {
855 StatementType::Insert => {
856 let rows = parse_mysql_insert_rows(&stmt, table_schema)?;
857 for row in rows {
858 if let Some((next_idx, _)) = select_iter.peek() {
859 if current_row_idx == *next_idx {
860 writer.write_all(&[0u8])?;
861 writer.write_all(&row.raw)?;
862 writer.write_all(b"\n")?;
863 rows_selected += 1;
864 select_iter.next();
865 }
866 }
867 current_row_idx += 1;
868 }
869 }
870 StatementType::Copy => {
871 let header = String::from_utf8_lossy(&stmt);
872 copy_columns = parse_copy_columns(&header);
873 }
874 StatementType::Unknown if config.dialect == SqlDialect::Postgres => {
875 if stmt.ends_with(b"\\.\n") || stmt.ends_with(b"\\.\r\n") {
876 let rows = parse_postgres_copy_rows(
877 &stmt,
878 table_schema,
879 copy_columns.clone(),
880 )?;
881 for row in rows {
882 if let Some((next_idx, _)) = select_iter.peek() {
883 if current_row_idx == *next_idx {
884 writer.write_all(&[1u8])?;
885 writer.write_all(&row.raw)?;
886 writer.write_all(b"\n")?;
887 rows_selected += 1;
888 select_iter.next();
889 }
890 }
891 current_row_idx += 1;
892 }
893 }
894 }
895 _ => {}
896 }
897 }
898 }
899 }
900
901 if let Some(mut writer) = temp_writer {
903 writer.flush()?;
904 }
905
906 Ok(StreamingSampleResult {
907 rows_seen,
908 rows_selected,
909 fk_orphans,
910 pk_hashes: selected_pk_hashes,
911 })
912}
913
914fn check_unified_fk_membership(
917 row: &UnifiedRow,
918 table_schema: &crate::schema::TableSchema,
919 runtimes: &AHashMap<TableId, TableRuntime>,
920 cyclic_set: &ahash::AHashSet<TableId>,
921 current_table_id: &TableId,
922) -> (bool, bool) {
923 let mut passes = true;
924 let mut is_orphan = false;
925
926 for (fk_ref, fk_tuple) in row.fk_values() {
927 if let Some(fk) = table_schema.foreign_keys.get(fk_ref.fk_index as usize) {
928 if let Some(parent_id) = fk.referenced_table_id {
929 if cyclic_set.contains(&parent_id) && cyclic_set.contains(current_table_id) {
931 continue;
932 }
933
934 if let Some(parent_runtime) = runtimes.get(&parent_id) {
936 let fk_hash = hash_pk_tuple(fk_tuple);
937 if !parent_runtime.pk_set.contains(&fk_hash) {
938 passes = false;
939 is_orphan = true;
940 break;
941 }
942 }
943 }
944 }
945 }
946
947 (passes, is_orphan)
948}
949
950fn write_output(
952 config: &SampleConfig,
953 _graph: &SchemaGraph,
954 table_order: &[TableId],
955 runtimes: &AHashMap<TableId, TableRuntime>,
956 tables_dir: &Path,
957 stats: &SampleStats,
958) -> anyhow::Result<()> {
959 let mut writer: Box<dyn Write> = match &config.output {
960 Some(path) => {
961 if let Some(parent) = path.parent() {
962 fs::create_dir_all(parent)?;
963 }
964 Box::new(BufWriter::with_capacity(256 * 1024, File::create(path)?))
965 }
966 None => Box::new(BufWriter::new(std::io::stdout())),
967 };
968
969 write_header(&mut writer, config, stats)?;
971
972 write_dialect_header(&mut writer, config.dialect)?;
974
975 if config.include_schema {
977 for &table_id in table_order {
978 let runtime = match runtimes.get(&table_id) {
979 Some(r) if !r.skip && r.rows_selected > 0 => r,
980 _ => continue,
981 };
982
983 let table_file = tables_dir.join(format!("{}.sql", runtime.name));
984 if !table_file.exists() {
985 continue;
986 }
987
988 let file = File::open(&table_file)?;
990 let mut parser = Parser::with_dialect(file, 64 * 1024, config.dialect);
991
992 while let Some(stmt) = parser.read_statement()? {
993 let (stmt_type, _) =
994 Parser::<&[u8]>::parse_statement_with_dialect(&stmt, config.dialect);
995
996 if stmt_type.is_schema() {
997 writer.write_all(&stmt)?;
998 writer.write_all(b"\n")?;
999 }
1000 }
1001 }
1002 }
1003
1004 for &table_id in table_order {
1006 let runtime = match runtimes.get(&table_id) {
1007 Some(r) if !r.skip && r.rows_selected > 0 && r.selected_temp_path.is_some() => r,
1008 _ => continue,
1009 };
1010
1011 let table_name = &runtime.name;
1012 let row_count = runtime.rows_selected;
1013
1014 writeln!(writer, "\n-- Data: {} ({} rows)", table_name, row_count)?;
1015
1016 let quoted_name = match config.dialect {
1018 SqlDialect::MySql => format!("`{}`", table_name),
1019 SqlDialect::Postgres | SqlDialect::Sqlite => format!("\"{}\"", table_name),
1020 };
1021
1022 let temp_path = runtime.selected_temp_path.as_ref().unwrap();
1024 let temp_file = File::open(temp_path)?;
1025 let reader = std::io::BufReader::new(temp_file);
1026 use std::io::BufRead;
1027
1028 const CHUNK_SIZE: usize = 1000;
1029 let mut chunk_buffer: Vec<(RowFormat, Vec<u8>)> = Vec::with_capacity(CHUNK_SIZE);
1030
1031 for line in reader.lines() {
1032 let line = line?;
1033 if line.is_empty() {
1034 continue;
1035 }
1036
1037 let bytes = line.as_bytes();
1038 if bytes.is_empty() {
1039 continue;
1040 }
1041
1042 let format = if bytes[0] == 0 {
1044 RowFormat::Insert
1045 } else {
1046 RowFormat::Copy
1047 };
1048 let row_bytes = bytes[1..].to_vec();
1049
1050 chunk_buffer.push((format, row_bytes));
1051
1052 if chunk_buffer.len() >= CHUNK_SIZE {
1053 write_insert_chunk(&mut writer, "ed_name, &chunk_buffer, config.dialect)?;
1054 chunk_buffer.clear();
1055 }
1056 }
1057
1058 if !chunk_buffer.is_empty() {
1060 write_insert_chunk(&mut writer, "ed_name, &chunk_buffer, config.dialect)?;
1061 }
1062 }
1063
1064 write_dialect_footer(&mut writer, config.dialect)?;
1066
1067 writer.flush()?;
1068
1069 Ok(())
1070}
1071
1072fn write_header<W: Write>(
1074 writer: &mut W,
1075 config: &SampleConfig,
1076 stats: &SampleStats,
1077) -> std::io::Result<()> {
1078 writeln!(writer, "-- Sampled from: {}", config.input.display())?;
1079 writeln!(
1080 writer,
1081 "-- Date: {}",
1082 chrono::Local::now().format("%Y-%m-%d %H:%M:%S")
1083 )?;
1084 writeln!(
1085 writer,
1086 "-- Mode: {:?}{}",
1087 config.mode,
1088 if config.preserve_relations {
1089 ", preserve-relations"
1090 } else {
1091 ""
1092 }
1093 )?;
1094 writeln!(writer, "-- Seed: {}", config.seed)?;
1095 writeln!(writer, "-- Dialect: {}", config.dialect)?;
1096 writeln!(writer, "--")?;
1097 writeln!(writer, "-- Statistics:")?;
1098 writeln!(writer, "-- Tables sampled: {}", stats.tables_sampled)?;
1099 writeln!(writer, "-- Tables skipped: {}", stats.tables_skipped)?;
1100
1101 let percent = if stats.total_rows_seen > 0 {
1102 (stats.total_rows_selected as f64 / stats.total_rows_seen as f64) * 100.0
1103 } else {
1104 0.0
1105 };
1106 writeln!(
1107 writer,
1108 "-- Total rows: {} (from {} original, {:.1}%)",
1109 stats.total_rows_selected, stats.total_rows_seen, percent
1110 )?;
1111
1112 if stats.fk_orphans_rejected > 0 {
1113 writeln!(
1114 writer,
1115 "-- FK orphans rejected: {}",
1116 stats.fk_orphans_rejected
1117 )?;
1118 }
1119
1120 if !stats.warnings.is_empty() {
1121 writeln!(writer, "-- Warnings: {}", stats.warnings.len())?;
1122 }
1123
1124 writeln!(writer)?;
1125
1126 Ok(())
1127}
1128
1129fn write_dialect_header<W: Write>(writer: &mut W, dialect: SqlDialect) -> std::io::Result<()> {
1131 match dialect {
1132 SqlDialect::MySql => {
1133 writeln!(writer, "SET NAMES utf8mb4;")?;
1134 writeln!(writer, "SET FOREIGN_KEY_CHECKS = 0;")?;
1135 }
1136 SqlDialect::Postgres => {
1137 writeln!(writer, "SET client_encoding = 'UTF8';")?;
1138 writeln!(writer, "SET session_replication_role = replica;")?;
1139 }
1140 SqlDialect::Sqlite => {
1141 writeln!(writer, "PRAGMA foreign_keys = OFF;")?;
1142 }
1143 }
1144 writeln!(writer)?;
1145 Ok(())
1146}
1147
1148fn write_dialect_footer<W: Write>(writer: &mut W, dialect: SqlDialect) -> std::io::Result<()> {
1150 writeln!(writer)?;
1151 match dialect {
1152 SqlDialect::MySql => {
1153 writeln!(writer, "SET FOREIGN_KEY_CHECKS = 1;")?;
1154 }
1155 SqlDialect::Postgres => {
1156 writeln!(writer, "SET session_replication_role = DEFAULT;")?;
1157 }
1158 SqlDialect::Sqlite => {
1159 writeln!(writer, "PRAGMA foreign_keys = ON;")?;
1160 }
1161 }
1162 Ok(())
1163}
1164
1165fn write_insert_chunk<W: Write>(
1167 writer: &mut W,
1168 quoted_name: &str,
1169 chunk: &[(RowFormat, Vec<u8>)],
1170 dialect: SqlDialect,
1171) -> std::io::Result<()> {
1172 writeln!(writer, "INSERT INTO {} VALUES", quoted_name)?;
1173
1174 for (i, (format, row_bytes)) in chunk.iter().enumerate() {
1175 if i > 0 {
1176 writer.write_all(b",\n")?;
1177 }
1178
1179 let values = match format {
1180 RowFormat::Insert => match dialect {
1181 SqlDialect::Postgres => convert_row_to_postgres(row_bytes),
1182 _ => row_bytes.clone(),
1183 },
1184 RowFormat::Copy => convert_copy_to_insert_values(row_bytes, dialect),
1185 };
1186 writer.write_all(&values)?;
1187 }
1188
1189 writer.write_all(b";\n")?;
1190 Ok(())
1191}
1192
1193fn convert_row_to_postgres(row: &[u8]) -> Vec<u8> {
1195 let mut result = Vec::with_capacity(row.len());
1198 let mut i = 0;
1199
1200 while i < row.len() {
1201 if row[i] == b'\\' && i + 1 < row.len() && row[i + 1] == b'\'' {
1202 result.push(b'\'');
1204 result.push(b'\'');
1205 i += 2;
1206 } else {
1207 result.push(row[i]);
1208 i += 1;
1209 }
1210 }
1211
1212 result
1213}
1214
1215fn convert_copy_to_insert_values(row: &[u8], dialect: SqlDialect) -> Vec<u8> {
1217 let mut result = Vec::with_capacity(row.len() + 20);
1218 result.push(b'(');
1219
1220 let fields: Vec<&[u8]> = row.split(|&b| b == b'\t').collect();
1221
1222 for (i, field) in fields.iter().enumerate() {
1223 if i > 0 {
1224 result.extend_from_slice(b", ");
1225 }
1226
1227 if *field == b"\\N" {
1229 result.extend_from_slice(b"NULL");
1230 } else if field.is_empty() {
1231 match dialect {
1233 SqlDialect::MySql => result.extend_from_slice(b"''"),
1234 SqlDialect::Postgres | SqlDialect::Sqlite => result.extend_from_slice(b"''"),
1235 }
1236 } else if is_numeric(field) {
1237 result.extend_from_slice(field);
1239 } else {
1240 result.push(b'\'');
1242 for &b in *field {
1243 match b {
1244 b'\'' => {
1245 match dialect {
1247 SqlDialect::MySql => result.extend_from_slice(b"\\'"),
1248 SqlDialect::Postgres | SqlDialect::Sqlite => {
1249 result.extend_from_slice(b"''")
1250 }
1251 }
1252 }
1253 b'\\' if dialect == SqlDialect::MySql => {
1254 result.extend_from_slice(b"\\\\");
1256 }
1257 _ => result.push(b),
1258 }
1259 }
1260 result.push(b'\'');
1261 }
1262 }
1263
1264 result.push(b')');
1265 result
1266}
1267
1268fn is_numeric(s: &[u8]) -> bool {
1270 if s.is_empty() {
1271 return false;
1272 }
1273
1274 let mut has_digit = false;
1275 let mut has_dot = false;
1276 let mut start = 0;
1277
1278 if s[0] == b'-' || s[0] == b'+' {
1280 start = 1;
1281 }
1282
1283 for &b in &s[start..] {
1284 match b {
1285 b'0'..=b'9' => has_digit = true,
1286 b'.' if !has_dot => has_dot = true,
1287 b'e' | b'E' => {
1288 continue;
1290 }
1291 _ => return false,
1292 }
1293 }
1294
1295 has_digit
1296}