Skip to main content

sql_splitter/shard/
mod.rs

1//! Shard command for extracting tenant-specific data from SQL dumps.
2//!
3//! The shard command extracts data belonging to a specific tenant by:
4//! - Identifying tables with the tenant column (tenant roots)
5//! - Following FK chains to include dependent data
6//! - Including junction/pivot tables where any FK matches tenant data
7//! - Optionally including global/lookup tables
8//!
9//! Supports MySQL, PostgreSQL, and SQLite dialects.
10
11mod config;
12
13pub use config::{
14    DefaultShardClassifier, GlobalTableMode, ShardTableClassification, ShardYamlConfig,
15};
16
17use crate::parser::mysql_insert::{PkSet, PkValue, RowExtraction};
18use crate::parser::{Parser, SqlDialect};
19use crate::schema::{SchemaGraph, TableId, TableSchema};
20use crate::transform_common::{
21    build_schema_graph, for_each_data_row, quote_ident, split_to_temp_tables, write_dialect_footer,
22    write_dialect_header, write_insert_chunk, RowFlow, RowFormat, RowSpillReader, RowSpillWriter,
23    UnifiedRow,
24};
25use ahash::{AHashMap, AHashSet};
26use std::fs::{self, File};
27use std::io::{BufWriter, Write};
28use std::path::{Path, PathBuf};
29
30/// Configuration for the shard command
31#[derive(Debug)]
32pub struct ShardConfig {
33    /// Input SQL file
34    pub input: PathBuf,
35    /// Output SQL file (None for stdout)
36    pub output: Option<PathBuf>,
37    /// SQL dialect
38    pub dialect: SqlDialect,
39    /// Tenant column name (auto-detected if None)
40    pub tenant_column: Option<String>,
41    /// Tenant value to extract
42    pub tenant_value: String,
43    /// Explicit root tables (tables that have the tenant column)
44    pub root_tables: Vec<String>,
45    /// How to handle global/lookup tables
46    pub include_global: GlobalTableMode,
47    /// Dry run mode (show stats only)
48    pub dry_run: bool,
49    /// Show progress
50    pub progress: bool,
51    /// YAML config file path
52    pub config_file: Option<PathBuf>,
53    /// Maximum selected rows (memory guard)
54    pub max_selected_rows: Option<usize>,
55    /// Fail if any FK integrity issues detected
56    pub strict_fk: bool,
57    /// Include schema statements in output
58    pub include_schema: bool,
59}
60
61impl Default for ShardConfig {
62    fn default() -> Self {
63        Self {
64            input: PathBuf::new(),
65            output: None,
66            dialect: SqlDialect::MySql,
67            tenant_column: None,
68            tenant_value: String::new(),
69            root_tables: Vec::new(),
70            include_global: GlobalTableMode::Lookups,
71            dry_run: false,
72            progress: false,
73            config_file: None,
74            max_selected_rows: Some(10_000_000),
75            strict_fk: false,
76            include_schema: true,
77        }
78    }
79}
80
81/// Statistics from shard operation
82#[derive(Debug, Default, serde::Serialize)]
83pub struct ShardStats {
84    /// Number of tables processed
85    pub tables_processed: usize,
86    /// Number of tables skipped
87    pub tables_skipped: usize,
88    /// Number of tables with data included
89    pub tables_with_data: usize,
90    /// Total rows selected
91    pub total_rows_selected: u64,
92    /// Total rows seen
93    pub total_rows_seen: u64,
94    /// Per-table statistics
95    pub table_stats: Vec<TableShardStats>,
96    /// Warning messages
97    pub warnings: Vec<String>,
98    /// FK orphan count (rows with missing parents)
99    pub fk_orphans_skipped: u64,
100    /// Detected tenant column
101    pub detected_tenant_column: Option<String>,
102}
103
104/// Per-table sharding statistics
105#[derive(Debug, Clone, serde::Serialize)]
106pub struct TableShardStats {
107    pub name: String,
108    pub rows_seen: u64,
109    pub rows_selected: u64,
110    pub classification: ShardTableClassification,
111}
112
113/// Runtime state for a table during sharding
114struct TableRuntime {
115    /// Table name
116    name: String,
117    /// Primary key set for FK membership checks
118    pk_set: PkSet,
119    /// Rows seen count
120    rows_seen: u64,
121    /// Rows selected count
122    rows_selected: u64,
123    /// Whether to skip this table
124    skip: bool,
125    /// Table classification
126    classification: ShardTableClassification,
127    /// FK orphans encountered
128    fk_orphans: u64,
129    /// Column index for tenant column (if this is a tenant root)
130    tenant_column_index: Option<usize>,
131    /// Path to temp file containing selected row bytes (None if no rows selected)
132    selected_temp_path: Option<PathBuf>,
133}
134
135/// Run the shard command
136pub fn run(config: ShardConfig) -> anyhow::Result<ShardStats> {
137    let yaml_config = if let Some(ref path) = config.config_file {
138        Some(ShardYamlConfig::load(path)?)
139    } else {
140        None
141    };
142
143    let mut stats = ShardStats::default();
144
145    // Split input into per-table files
146    let split_phase = split_to_temp_tables(&config.input, config.dialect, config.progress)?;
147    let temp_dir = split_phase.temp_dir;
148    let tables_dir = split_phase.tables_dir;
149
150    // Build the schema graph
151    if config.progress {
152        eprintln!("Building schema graph...");
153    }
154
155    let graph = build_schema_graph(&tables_dir, config.dialect)?;
156
157    // Detect or use configured tenant column
158    let tenant_column = detect_tenant_column(&config, &yaml_config, &graph)?;
159    stats.detected_tenant_column = Some(tenant_column.clone());
160
161    if config.progress {
162        eprintln!("Using tenant column: {}", tenant_column);
163    }
164
165    // Parse tenant value
166    let tenant_pk_value = parse_tenant_value(&config.tenant_value);
167
168    // Classify tables and build runtimes
169    let (topo_order, cyclic_tables) = graph.processing_order();
170
171    if !cyclic_tables.is_empty() {
172        let names: Vec<_> = cyclic_tables
173            .iter()
174            .filter_map(|&id| graph.table_name(id))
175            .collect();
176        stats.warnings.push(format!(
177            "{} tables have FK cycles (relaxed FK enforcement): {:?}",
178            cyclic_tables.len(),
179            names
180        ));
181    }
182
183    let cyclic_set: AHashSet<TableId> = cyclic_tables.iter().copied().collect();
184
185    // Determine tenant root tables
186    let tenant_root_ids = find_tenant_root_tables(&graph, &tenant_column, &config, &yaml_config);
187
188    // Build reachability from tenant roots
189    let reachable_from_roots = compute_reachable_tables(&graph, &tenant_root_ids);
190
191    // Initialize table runtimes with classification
192    let mut runtimes: AHashMap<TableId, TableRuntime> = AHashMap::new();
193    for table in graph.schema.iter() {
194        let classification = classify_table(
195            &table.name,
196            table.id,
197            &graph,
198            &tenant_root_ids,
199            &reachable_from_roots,
200            &yaml_config,
201        );
202
203        let tenant_column_index = if classification == ShardTableClassification::TenantRoot {
204            find_tenant_column_index(table, &tenant_column)
205        } else {
206            None
207        };
208
209        let skip = should_skip_table(&table.name, classification, &config, &yaml_config);
210
211        runtimes.insert(
212            table.id,
213            TableRuntime {
214                name: table.name.clone(),
215                pk_set: PkSet::default(),
216                rows_seen: 0,
217                rows_selected: 0,
218                skip,
219                classification,
220                fk_orphans: 0,
221                tenant_column_index,
222                selected_temp_path: None,
223            },
224        );
225    }
226
227    // Create directory for selected row temp files
228    let selected_dir = temp_dir.path().join("selected");
229    fs::create_dir_all(&selected_dir)?;
230
231    // Process tables in dependency order
232    if config.progress {
233        eprintln!(
234            "Processing {} tables for tenant {}...",
235            topo_order.len() + cyclic_tables.len(),
236            config.tenant_value
237        );
238    }
239
240    let all_tables: Vec<TableId> = topo_order.into_iter().chain(cyclic_tables).collect();
241    let mut total_selected: u64 = 0;
242
243    for &table_id in &all_tables {
244        let table_schema = match graph.schema.table(table_id) {
245            Some(s) => s,
246            None => continue,
247        };
248
249        let (should_skip, table_name, classification, tenant_col_idx) = {
250            let runtime = match runtimes.get(&table_id) {
251                Some(r) => r,
252                None => continue,
253            };
254            (
255                runtime.skip,
256                runtime.name.clone(),
257                runtime.classification,
258                runtime.tenant_column_index,
259            )
260        };
261
262        if should_skip {
263            stats.tables_skipped += 1;
264            continue;
265        }
266
267        // Handle lookup/system tables
268        let include_all = match classification {
269            ShardTableClassification::Lookup => match config.include_global {
270                GlobalTableMode::None => {
271                    stats.tables_skipped += 1;
272                    continue;
273                }
274                GlobalTableMode::Lookups | GlobalTableMode::All => true,
275            },
276            ShardTableClassification::System => {
277                stats.tables_skipped += 1;
278                continue;
279            }
280            ShardTableClassification::Unknown => match config.include_global {
281                GlobalTableMode::All => true,
282                _ => {
283                    stats.tables_skipped += 1;
284                    continue;
285                }
286            },
287            _ => false,
288        };
289
290        let table_file = tables_dir.join(format!("{}.sql", table_name));
291        if !table_file.exists() {
292            continue;
293        }
294
295        let temp_path = selected_dir.join(format!("{}.rows", table_name));
296        let mut spill: Option<RowSpillWriter> = None;
297
298        let mut rows_seen = 0u64;
299        let mut fk_orphans = 0u64;
300        let mut rows_selected = 0u64;
301
302        for_each_data_row(
303            &table_file,
304            table_schema,
305            config.dialect,
306            RowExtraction::Full,
307            |row| {
308                rows_seen += 1;
309
310                let should_include = include_all
311                    || should_include_row(
312                        &row,
313                        table_schema,
314                        classification,
315                        tenant_col_idx,
316                        &tenant_pk_value,
317                        &runtimes,
318                        &cyclic_set,
319                        &table_id,
320                    );
321
322                if !should_include {
323                    if classification == ShardTableClassification::TenantDependent {
324                        fk_orphans += 1;
325                    }
326                    return Ok(RowFlow::Continue);
327                }
328
329                // Check max_selected_rows guard
330                if let Some(max) = config.max_selected_rows {
331                    if total_selected >= max as u64 {
332                        if row.format() == RowFormat::Insert {
333                            stats.warnings.push(format!(
334                                "Reached max_selected_rows limit ({}) at table '{}'",
335                                max, table_name
336                            ));
337                        }
338                        return Ok(RowFlow::SkipStatement);
339                    }
340                }
341
342                total_selected += 1;
343
344                let runtime = runtimes.get_mut(&table_id).unwrap();
345                if let Some(pk) = row.pk() {
346                    runtime.pk_set.insert(pk.clone());
347                }
348
349                // Spill the selected row to a temp file (bounded memory)
350                if spill.is_none() {
351                    spill = Some(RowSpillWriter::create(&temp_path)?);
352                }
353                spill.as_mut().unwrap().write_row(row.format(), row.raw())?;
354                rows_selected += 1;
355
356                Ok(RowFlow::Continue)
357            },
358        )?;
359
360        if let Some(spill) = spill {
361            spill.finish()?;
362        }
363
364        let runtime = runtimes.get_mut(&table_id).unwrap();
365        runtime.rows_seen = rows_seen;
366        runtime.fk_orphans = fk_orphans;
367        runtime.rows_selected = rows_selected;
368        if rows_selected > 0 && temp_path.exists() {
369            runtime.selected_temp_path = Some(temp_path);
370        }
371        stats.fk_orphans_skipped += fk_orphans;
372
373        if rows_selected > 0 {
374            stats.tables_with_data += 1;
375        }
376
377        stats.table_stats.push(TableShardStats {
378            name: runtime.name.clone(),
379            rows_seen: runtime.rows_seen,
380            rows_selected: runtime.rows_selected,
381            classification: runtime.classification,
382        });
383    }
384
385    // Calculate totals
386    for table_stat in &stats.table_stats {
387        stats.total_rows_seen += table_stat.rows_seen;
388        stats.total_rows_selected += table_stat.rows_selected;
389    }
390    stats.tables_processed = stats.table_stats.len();
391
392    if config.progress {
393        eprintln!("Processing complete");
394    }
395
396    // Synthesize the output
397    if config.dry_run {
398        return Ok(stats);
399    }
400
401    write_output(&config, &graph, &all_tables, &runtimes, &tables_dir, &stats)?;
402
403    Ok(stats)
404}
405
406/// Detect tenant column from config or by scanning schema
407fn detect_tenant_column(
408    config: &ShardConfig,
409    yaml_config: &Option<ShardYamlConfig>,
410    graph: &SchemaGraph,
411) -> anyhow::Result<String> {
412    // Check CLI option first
413    if let Some(ref col) = config.tenant_column {
414        return Ok(col.clone());
415    }
416
417    // Check YAML config
418    if let Some(ref yaml) = yaml_config {
419        if let Some(ref col) = yaml.tenant.column {
420            return Ok(col.clone());
421        }
422    }
423
424    // Auto-detect from schema
425    for candidate in DefaultShardClassifier::TENANT_COLUMNS {
426        let mut found_in_tables = 0;
427        for table in graph.schema.iter() {
428            if table.get_column(candidate).is_some() {
429                found_in_tables += 1;
430            }
431        }
432        if found_in_tables >= 2 {
433            return Ok(candidate.to_string());
434        }
435    }
436
437    anyhow::bail!(
438        "Could not auto-detect tenant column. Please specify with --tenant-column. \
439         Looked for: {:?}",
440        DefaultShardClassifier::TENANT_COLUMNS
441    )
442}
443
444/// Parse tenant value string into PkValue
445fn parse_tenant_value(value: &str) -> PkValue {
446    if let Ok(i) = value.parse::<i64>() {
447        PkValue::Int(i)
448    } else if let Ok(i) = value.parse::<i128>() {
449        PkValue::BigInt(i)
450    } else {
451        PkValue::Text(value.into())
452    }
453}
454
455/// Find tables that have the tenant column
456fn find_tenant_root_tables(
457    graph: &SchemaGraph,
458    tenant_column: &str,
459    config: &ShardConfig,
460    yaml_config: &Option<ShardYamlConfig>,
461) -> AHashSet<TableId> {
462    let mut roots = AHashSet::new();
463
464    // Explicit roots from config
465    let explicit_roots: AHashSet<String> = config
466        .root_tables
467        .iter()
468        .chain(
469            yaml_config
470                .as_ref()
471                .map(|y| &y.tenant.root_tables)
472                .unwrap_or(&Vec::new()),
473        )
474        .map(|s| s.to_lowercase())
475        .collect();
476
477    for table in graph.schema.iter() {
478        let lower_name = table.name.to_lowercase();
479
480        if explicit_roots.contains(&lower_name) || table.get_column(tenant_column).is_some() {
481            roots.insert(table.id);
482        }
483    }
484
485    roots
486}
487
488/// Compute tables reachable from tenant roots via FK relationships
489fn compute_reachable_tables(
490    graph: &SchemaGraph,
491    tenant_roots: &AHashSet<TableId>,
492) -> AHashSet<TableId> {
493    let mut reachable = tenant_roots.clone();
494    let mut queue: Vec<TableId> = tenant_roots.iter().copied().collect();
495
496    while let Some(table_id) = queue.pop() {
497        for &child_id in &graph.children[table_id.0 as usize] {
498            if !reachable.contains(&child_id) {
499                reachable.insert(child_id);
500                queue.push(child_id);
501            }
502        }
503    }
504
505    reachable
506}
507
508/// Classify a table for sharding
509fn classify_table(
510    table_name: &str,
511    table_id: TableId,
512    graph: &SchemaGraph,
513    tenant_roots: &AHashSet<TableId>,
514    reachable: &AHashSet<TableId>,
515    yaml_config: &Option<ShardYamlConfig>,
516) -> ShardTableClassification {
517    // Check YAML override first
518    if let Some(ref yaml) = yaml_config {
519        if let Some(class) = yaml.get_classification(table_name) {
520            return class;
521        }
522    }
523
524    // Check if it's a tenant root
525    if tenant_roots.contains(&table_id) {
526        return ShardTableClassification::TenantRoot;
527    }
528
529    // Check if reachable from tenant roots (dependent)
530    if reachable.contains(&table_id) {
531        // Check if it might be a junction table
532        if is_junction_table(table_name, table_id, graph) {
533            return ShardTableClassification::Junction;
534        }
535        return ShardTableClassification::TenantDependent;
536    }
537
538    // Check system patterns
539    if DefaultShardClassifier::is_system_table(table_name) {
540        return ShardTableClassification::System;
541    }
542
543    // Check lookup patterns
544    if DefaultShardClassifier::is_lookup_table(table_name) {
545        return ShardTableClassification::Lookup;
546    }
547
548    ShardTableClassification::Unknown
549}
550
551/// Check if a table is a junction table
552fn is_junction_table(table_name: &str, table_id: TableId, graph: &SchemaGraph) -> bool {
553    // Name-based heuristic
554    if DefaultShardClassifier::is_junction_table_by_name(table_name) {
555        return true;
556    }
557
558    // Structure-based: table with multiple FKs and few/no other columns
559    if let Some(table) = graph.schema.table(table_id) {
560        let fk_count = table.foreign_keys.len();
561        let fk_col_count: usize = table.foreign_keys.iter().map(|fk| fk.columns.len()).sum();
562        let total_cols = table.columns.len();
563
564        // Junction tables typically have mostly FK columns
565        if fk_count >= 2 && fk_col_count >= total_cols.saturating_sub(2) {
566            return true;
567        }
568    }
569
570    false
571}
572
573/// Find the index of the tenant column in a table
574fn find_tenant_column_index(table: &TableSchema, tenant_column: &str) -> Option<usize> {
575    table
576        .columns
577        .iter()
578        .position(|c| c.name.eq_ignore_ascii_case(tenant_column))
579}
580
581/// Determine if a table should be skipped
582fn should_skip_table(
583    table_name: &str,
584    classification: ShardTableClassification,
585    config: &ShardConfig,
586    yaml_config: &Option<ShardYamlConfig>,
587) -> bool {
588    // Check YAML skip override
589    if let Some(ref yaml) = yaml_config {
590        if yaml.should_skip(table_name) {
591            return true;
592        }
593    }
594
595    // System tables always skipped
596    if classification == ShardTableClassification::System {
597        return true;
598    }
599
600    // Lookup tables depend on config
601    if classification == ShardTableClassification::Lookup {
602        return config.include_global == GlobalTableMode::None;
603    }
604
605    false
606}
607
608/// Check if a row should be included in the shard
609#[allow(clippy::too_many_arguments)]
610fn should_include_row(
611    row: &UnifiedRow,
612    table_schema: &TableSchema,
613    classification: ShardTableClassification,
614    tenant_column_index: Option<usize>,
615    tenant_value: &PkValue,
616    runtimes: &AHashMap<TableId, TableRuntime>,
617    cyclic_set: &AHashSet<TableId>,
618    current_table_id: &TableId,
619) -> bool {
620    match classification {
621        ShardTableClassification::TenantRoot => {
622            // Check tenant column value using column_map for correct mapping
623            if let Some(idx) = tenant_column_index {
624                if let Some(val) = row.get_column_value(idx) {
625                    return val == tenant_value;
626                }
627            }
628            false
629        }
630        ShardTableClassification::TenantDependent => {
631            // Check if any FK points to a selected row
632            for (fk_ref, fk_tuple) in row.fk_values() {
633                if let Some(fk) = table_schema.foreign_keys.get(fk_ref.fk_index as usize) {
634                    if let Some(parent_id) = fk.referenced_table_id {
635                        // Skip FK check for cyclic tables
636                        if cyclic_set.contains(&parent_id) && cyclic_set.contains(current_table_id)
637                        {
638                            continue;
639                        }
640
641                        if let Some(parent_runtime) = runtimes.get(&parent_id) {
642                            if parent_runtime.pk_set.contains(fk_tuple) {
643                                return true;
644                            }
645                        }
646                    }
647                }
648            }
649            false
650        }
651        ShardTableClassification::Junction => {
652            // Include if ANY FK points to a selected row
653            for (fk_ref, fk_tuple) in row.fk_values() {
654                if let Some(fk) = table_schema.foreign_keys.get(fk_ref.fk_index as usize) {
655                    if let Some(parent_id) = fk.referenced_table_id {
656                        if let Some(parent_runtime) = runtimes.get(&parent_id) {
657                            if parent_runtime.pk_set.contains(fk_tuple) {
658                                return true;
659                            }
660                        }
661                    }
662                }
663            }
664            false
665        }
666        _ => false,
667    }
668}
669
670/// Write the sharded output
671fn write_output(
672    config: &ShardConfig,
673    _graph: &SchemaGraph,
674    table_order: &[TableId],
675    runtimes: &AHashMap<TableId, TableRuntime>,
676    tables_dir: &Path,
677    stats: &ShardStats,
678) -> anyhow::Result<()> {
679    let mut writer: Box<dyn Write> = match &config.output {
680        Some(path) => {
681            if let Some(parent) = path.parent() {
682                fs::create_dir_all(parent)?;
683            }
684            Box::new(BufWriter::with_capacity(256 * 1024, File::create(path)?))
685        }
686        None => Box::new(BufWriter::new(std::io::stdout())),
687    };
688
689    // Write header comment
690    write_header(&mut writer, config, stats)?;
691
692    // Write dialect-specific header
693    write_dialect_header(&mut writer, config.dialect)?;
694
695    // Write schema for each table (if enabled)
696    if config.include_schema {
697        for &table_id in table_order {
698            let runtime = match runtimes.get(&table_id) {
699                Some(r) if !r.skip && r.rows_selected > 0 => r,
700                _ => continue,
701            };
702
703            let table_file = tables_dir.join(format!("{}.sql", runtime.name));
704            if !table_file.exists() {
705                continue;
706            }
707
708            let file = File::open(&table_file)?;
709            let mut parser = Parser::with_dialect(file, 64 * 1024, config.dialect);
710
711            while let Some(stmt) = parser.read_statement()? {
712                let (stmt_type, _) =
713                    Parser::<&[u8]>::parse_statement_with_dialect(&stmt, config.dialect);
714
715                if stmt_type.is_schema() {
716                    writer.write_all(&stmt)?;
717                    writer.write_all(b"\n")?;
718                }
719            }
720        }
721    }
722
723    // Write data for each table (reading from temp files instead of memory)
724    for &table_id in table_order {
725        let runtime = match runtimes.get(&table_id) {
726            Some(r) if !r.skip && r.rows_selected > 0 && r.selected_temp_path.is_some() => r,
727            _ => continue,
728        };
729
730        let table_name = &runtime.name;
731        let row_count = runtime.rows_selected;
732
733        writeln!(writer, "\n-- Data: {} ({} rows)", table_name, row_count)?;
734
735        let quoted_name = quote_ident(config.dialect, table_name);
736
737        // Read rows from temp file and write INSERTs in chunks
738        let temp_path = runtime.selected_temp_path.as_ref().unwrap();
739        let mut spill_reader = RowSpillReader::open(temp_path)?;
740
741        const CHUNK_SIZE: usize = 1000;
742        let mut chunk_buffer: Vec<(RowFormat, Vec<u8>)> = Vec::with_capacity(CHUNK_SIZE);
743
744        while let Some((format, row_bytes)) = spill_reader.next_row()? {
745            chunk_buffer.push((format, row_bytes));
746
747            if chunk_buffer.len() >= CHUNK_SIZE {
748                write_insert_chunk(&mut writer, &quoted_name, &chunk_buffer, config.dialect)?;
749                chunk_buffer.clear();
750            }
751        }
752
753        // Write remaining rows
754        if !chunk_buffer.is_empty() {
755            write_insert_chunk(&mut writer, &quoted_name, &chunk_buffer, config.dialect)?;
756        }
757    }
758
759    // Write dialect-specific footer
760    write_dialect_footer(&mut writer, config.dialect)?;
761
762    writer.flush()?;
763
764    Ok(())
765}
766
767/// Write header comment
768fn write_header<W: Write>(
769    writer: &mut W,
770    config: &ShardConfig,
771    stats: &ShardStats,
772) -> std::io::Result<()> {
773    writeln!(writer, "-- Sharded from: {}", config.input.display())?;
774    writeln!(
775        writer,
776        "-- Date: {}",
777        chrono::Local::now().format("%Y-%m-%d %H:%M:%S")
778    )?;
779    if let Some(ref col) = stats.detected_tenant_column {
780        writeln!(writer, "-- Tenant column: {}", col)?;
781    }
782    writeln!(writer, "-- Tenant value: {}", config.tenant_value)?;
783    writeln!(writer, "-- Dialect: {}", config.dialect)?;
784    writeln!(writer, "--")?;
785    writeln!(writer, "-- Statistics:")?;
786    writeln!(writer, "--   Tables processed: {}", stats.tables_processed)?;
787    writeln!(writer, "--   Tables with data: {}", stats.tables_with_data)?;
788    writeln!(writer, "--   Tables skipped: {}", stats.tables_skipped)?;
789
790    let percent = if stats.total_rows_seen > 0 {
791        (stats.total_rows_selected as f64 / stats.total_rows_seen as f64) * 100.0
792    } else {
793        0.0
794    };
795    writeln!(
796        writer,
797        "--   Total rows: {} (from {} original, {:.1}%)",
798        stats.total_rows_selected, stats.total_rows_seen, percent
799    )?;
800
801    if stats.fk_orphans_skipped > 0 {
802        writeln!(
803            writer,
804            "--   FK orphans skipped: {}",
805            stats.fk_orphans_skipped
806        )?;
807    }
808
809    if !stats.warnings.is_empty() {
810        writeln!(writer, "--   Warnings: {}", stats.warnings.len())?;
811    }
812
813    writeln!(writer)?;
814
815    Ok(())
816}