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    /// All primary keys present in the source, indexed only for strict FK
120    /// validation so cross-tenant exclusions are not reported as orphans.
121    source_pk_set: Option<PkSet>,
122    /// Rows seen count
123    rows_seen: u64,
124    /// Rows selected count
125    rows_selected: u64,
126    /// Whether to skip this table
127    skip: bool,
128    /// Table classification
129    classification: ShardTableClassification,
130    /// FK orphans encountered
131    fk_orphans: u64,
132    /// Column index for tenant column (if this is a tenant root)
133    tenant_column_index: Option<usize>,
134    /// Path to temp file containing selected row bytes (None if no rows selected)
135    selected_temp_path: Option<PathBuf>,
136}
137
138/// Run the shard command
139pub fn run(config: ShardConfig) -> anyhow::Result<ShardStats> {
140    let yaml_config = if let Some(ref path) = config.config_file {
141        Some(ShardYamlConfig::load(path)?)
142    } else {
143        None
144    };
145
146    let mut stats = ShardStats::default();
147
148    // Split input into per-table files
149    let split_phase = split_to_temp_tables(&config.input, config.dialect, config.progress)?;
150    let temp_dir = split_phase.temp_dir;
151    let tables_dir = split_phase.tables_dir;
152
153    // Build the schema graph
154    if config.progress {
155        eprintln!("Building schema graph...");
156    }
157
158    let graph = build_schema_graph(&tables_dir, config.dialect)?;
159
160    // Detect or use configured tenant column
161    let tenant_column = detect_tenant_column(&config, &yaml_config, &graph)?;
162    stats.detected_tenant_column = Some(tenant_column.clone());
163
164    if config.progress {
165        eprintln!("Using tenant column: {}", tenant_column);
166    }
167
168    // Parse tenant value
169    let tenant_pk_value = parse_tenant_value(&config.tenant_value);
170
171    // Classify tables and build runtimes
172    let (topo_order, cyclic_tables) = graph.processing_order();
173
174    if !cyclic_tables.is_empty() {
175        let names: Vec<_> = cyclic_tables
176            .iter()
177            .filter_map(|&id| graph.table_name(id))
178            .collect();
179        stats.warnings.push(format!(
180            "{} tables have FK cycles (relaxed FK enforcement): {:?}",
181            cyclic_tables.len(),
182            names
183        ));
184    }
185
186    let cyclic_set: AHashSet<TableId> = cyclic_tables.iter().copied().collect();
187
188    // Determine tenant root tables
189    let tenant_root_ids = find_tenant_root_tables(&graph, &tenant_column, &config, &yaml_config);
190
191    // Build reachability from tenant roots
192    let reachable_from_roots = compute_reachable_tables(&graph, &tenant_root_ids);
193
194    // Initialize table runtimes with classification
195    let mut runtimes: AHashMap<TableId, TableRuntime> = AHashMap::new();
196    for table in graph.schema.iter() {
197        let classification = classify_table(
198            &table.name,
199            table.id,
200            &graph,
201            &tenant_root_ids,
202            &reachable_from_roots,
203            &yaml_config,
204        );
205
206        let tenant_column_index = if classification == ShardTableClassification::TenantRoot {
207            find_tenant_column_index(table, &tenant_column)
208        } else {
209            None
210        };
211
212        let skip = should_skip_table(&table.name, classification, &config, &yaml_config);
213
214        runtimes.insert(
215            table.id,
216            TableRuntime {
217                name: table.name.clone(),
218                pk_set: PkSet::default(),
219                source_pk_set: config.strict_fk.then(PkSet::default),
220                rows_seen: 0,
221                rows_selected: 0,
222                skip,
223                classification,
224                fk_orphans: 0,
225                tenant_column_index,
226                selected_temp_path: None,
227            },
228        );
229    }
230
231    if config.strict_fk {
232        index_source_primary_keys(&graph, &tables_dir, config.dialect, &mut runtimes)?;
233    }
234
235    // Create directory for selected row temp files
236    let selected_dir = temp_dir.path().join("selected");
237    fs::create_dir_all(&selected_dir)?;
238
239    // Process tables in dependency order
240    if config.progress {
241        eprintln!(
242            "Processing {} tables for tenant {}...",
243            topo_order.len() + cyclic_tables.len(),
244            config.tenant_value
245        );
246    }
247
248    let all_tables: Vec<TableId> = topo_order.into_iter().chain(cyclic_tables).collect();
249    let mut total_selected: u64 = 0;
250
251    for &table_id in &all_tables {
252        let table_schema = match graph.schema.table(table_id) {
253            Some(s) => s,
254            None => continue,
255        };
256
257        let (should_skip, table_name, classification, tenant_col_idx) = {
258            let runtime = match runtimes.get(&table_id) {
259                Some(r) => r,
260                None => continue,
261            };
262            (
263                runtime.skip,
264                runtime.name.clone(),
265                runtime.classification,
266                runtime.tenant_column_index,
267            )
268        };
269
270        if should_skip {
271            stats.tables_skipped += 1;
272            continue;
273        }
274
275        // Handle lookup/system tables
276        let include_all = match classification {
277            ShardTableClassification::Lookup => match config.include_global {
278                GlobalTableMode::None => {
279                    stats.tables_skipped += 1;
280                    continue;
281                }
282                GlobalTableMode::Lookups | GlobalTableMode::All => true,
283            },
284            ShardTableClassification::System => {
285                stats.tables_skipped += 1;
286                continue;
287            }
288            ShardTableClassification::Unknown => match config.include_global {
289                GlobalTableMode::All => true,
290                _ => {
291                    stats.tables_skipped += 1;
292                    continue;
293                }
294            },
295            _ => false,
296        };
297
298        let table_file = tables_dir.join(format!("{}.sql", table_name));
299        if !table_file.exists() {
300            continue;
301        }
302
303        let temp_path = selected_dir.join(format!("{}.rows", table_name));
304        let mut spill: Option<RowSpillWriter> = None;
305
306        let mut rows_seen = 0u64;
307        let fk_orphans = 0u64;
308        let mut rows_selected = 0u64;
309
310        for_each_data_row(
311            &table_file,
312            table_schema,
313            config.dialect,
314            RowExtraction::Full,
315            |row| {
316                rows_seen += 1;
317
318                if config.strict_fk && has_source_fk_orphan(&row, table_schema, &runtimes) {
319                    anyhow::bail!(
320                        "FK integrity violation in table '{}': row references missing parent",
321                        table_name
322                    );
323                }
324
325                let should_include = include_all
326                    || should_include_row(
327                        &row,
328                        table_schema,
329                        classification,
330                        tenant_col_idx,
331                        &tenant_pk_value,
332                        &runtimes,
333                        &cyclic_set,
334                        &table_id,
335                    );
336
337                if !should_include {
338                    return Ok(RowFlow::Continue);
339                }
340
341                // Check max_selected_rows guard
342                if let Some(max) = config.max_selected_rows {
343                    if total_selected >= max as u64 {
344                        if row.format() == RowFormat::Insert {
345                            stats.warnings.push(format!(
346                                "Reached max_selected_rows limit ({}) at table '{}'",
347                                max, table_name
348                            ));
349                        }
350                        return Ok(RowFlow::SkipStatement);
351                    }
352                }
353
354                total_selected += 1;
355
356                let runtime = runtimes.get_mut(&table_id).unwrap();
357                if let Some(pk) = row.pk() {
358                    runtime.pk_set.insert(pk.clone());
359                }
360
361                // Spill the selected row to a temp file (bounded memory)
362                if spill.is_none() {
363                    spill = Some(RowSpillWriter::create(&temp_path)?);
364                }
365                spill.as_mut().unwrap().write_row(row.format(), row.raw())?;
366                rows_selected += 1;
367
368                Ok(RowFlow::Continue)
369            },
370        )?;
371
372        if let Some(spill) = spill {
373            spill.finish()?;
374        }
375
376        let runtime = runtimes.get_mut(&table_id).unwrap();
377        runtime.rows_seen = rows_seen;
378        runtime.fk_orphans = fk_orphans;
379        runtime.rows_selected = rows_selected;
380        if rows_selected > 0 && temp_path.exists() {
381            runtime.selected_temp_path = Some(temp_path);
382        }
383        stats.fk_orphans_skipped += fk_orphans;
384
385        if rows_selected > 0 {
386            stats.tables_with_data += 1;
387        }
388
389        stats.table_stats.push(TableShardStats {
390            name: runtime.name.clone(),
391            rows_seen: runtime.rows_seen,
392            rows_selected: runtime.rows_selected,
393            classification: runtime.classification,
394        });
395    }
396
397    // Calculate totals
398    for table_stat in &stats.table_stats {
399        stats.total_rows_seen += table_stat.rows_seen;
400        stats.total_rows_selected += table_stat.rows_selected;
401    }
402    stats.tables_processed = stats.table_stats.len();
403
404    if config.progress {
405        eprintln!("Processing complete");
406    }
407
408    // Synthesize the output
409    if config.dry_run {
410        return Ok(stats);
411    }
412
413    write_output(&config, &graph, &all_tables, &runtimes, &tables_dir, &stats)?;
414
415    Ok(stats)
416}
417
418/// Index every source primary key for strict-FK validation.
419///
420/// The normal sharding path stores only selected parent keys. In strict mode,
421/// that is not enough to distinguish a malformed source reference from a valid
422/// parent that belongs to another tenant and is intentionally excluded.
423fn index_source_primary_keys(
424    graph: &SchemaGraph,
425    tables_dir: &Path,
426    dialect: SqlDialect,
427    runtimes: &mut AHashMap<TableId, TableRuntime>,
428) -> anyhow::Result<()> {
429    for table_schema in graph.schema.iter() {
430        let table_file = tables_dir.join(format!("{}.sql", table_schema.name));
431        if !table_file.exists() {
432            continue;
433        }
434
435        let mut source_pk_set = PkSet::default();
436        for_each_data_row(
437            &table_file,
438            table_schema,
439            dialect,
440            RowExtraction::PkFk,
441            |row| {
442                if let Some(pk) = row.pk() {
443                    source_pk_set.insert(pk.clone());
444                }
445                Ok(RowFlow::Continue)
446            },
447        )?;
448
449        if let Some(runtime) = runtimes.get_mut(&table_schema.id) {
450            runtime.source_pk_set = Some(source_pk_set);
451        }
452    }
453
454    Ok(())
455}
456
457/// Check whether a row references a parent PK absent from the source dump.
458///
459/// A missing selected parent is not an orphan here: it may be a valid
460/// cross-tenant reference that sharding excludes by design.
461fn has_source_fk_orphan(
462    row: &UnifiedRow,
463    table_schema: &TableSchema,
464    runtimes: &AHashMap<TableId, TableRuntime>,
465) -> bool {
466    row.fk_values().iter().any(|(fk_ref, fk_tuple)| {
467        let Some(fk) = table_schema.foreign_keys.get(fk_ref.fk_index as usize) else {
468            return false;
469        };
470        let Some(parent_id) = fk.referenced_table_id else {
471            return false;
472        };
473        let Some(parent_runtime) = runtimes.get(&parent_id) else {
474            return false;
475        };
476        parent_runtime
477            .source_pk_set
478            .as_ref()
479            .is_some_and(|source_keys| !source_keys.contains(fk_tuple))
480    })
481}
482
483/// Detect tenant column from config or by scanning schema
484fn detect_tenant_column(
485    config: &ShardConfig,
486    yaml_config: &Option<ShardYamlConfig>,
487    graph: &SchemaGraph,
488) -> anyhow::Result<String> {
489    // Check CLI option first
490    if let Some(ref col) = config.tenant_column {
491        return Ok(col.clone());
492    }
493
494    // Check YAML config
495    if let Some(ref yaml) = yaml_config {
496        if let Some(ref col) = yaml.tenant.column {
497            return Ok(col.clone());
498        }
499    }
500
501    // Auto-detect from schema
502    for candidate in DefaultShardClassifier::TENANT_COLUMNS {
503        let mut found_in_tables = 0;
504        for table in graph.schema.iter() {
505            if table.get_column(candidate).is_some() {
506                found_in_tables += 1;
507            }
508        }
509        if found_in_tables >= 2 {
510            return Ok(candidate.to_string());
511        }
512    }
513
514    anyhow::bail!(
515        "Could not auto-detect tenant column. Please specify with --tenant-column. \
516         Looked for: {:?}",
517        DefaultShardClassifier::TENANT_COLUMNS
518    )
519}
520
521/// Parse tenant value string into PkValue
522fn parse_tenant_value(value: &str) -> PkValue {
523    if let Ok(i) = value.parse::<i64>() {
524        PkValue::Int(i)
525    } else if let Ok(i) = value.parse::<i128>() {
526        PkValue::BigInt(i)
527    } else {
528        PkValue::Text(value.into())
529    }
530}
531
532/// Find tables that have the tenant column
533fn find_tenant_root_tables(
534    graph: &SchemaGraph,
535    tenant_column: &str,
536    config: &ShardConfig,
537    yaml_config: &Option<ShardYamlConfig>,
538) -> AHashSet<TableId> {
539    let mut roots = AHashSet::new();
540
541    // Explicit roots from config
542    let explicit_roots: AHashSet<String> = config
543        .root_tables
544        .iter()
545        .chain(
546            yaml_config
547                .as_ref()
548                .map(|y| &y.tenant.root_tables)
549                .unwrap_or(&Vec::new()),
550        )
551        .map(|s| s.to_lowercase())
552        .collect();
553
554    for table in graph.schema.iter() {
555        let lower_name = table.name.to_lowercase();
556
557        if explicit_roots.contains(&lower_name) || table.get_column(tenant_column).is_some() {
558            roots.insert(table.id);
559        }
560    }
561
562    roots
563}
564
565/// Compute tables reachable from tenant roots via FK relationships
566fn compute_reachable_tables(
567    graph: &SchemaGraph,
568    tenant_roots: &AHashSet<TableId>,
569) -> AHashSet<TableId> {
570    let mut reachable = tenant_roots.clone();
571    let mut queue: Vec<TableId> = tenant_roots.iter().copied().collect();
572
573    while let Some(table_id) = queue.pop() {
574        for &child_id in &graph.children[table_id.0 as usize] {
575            if !reachable.contains(&child_id) {
576                reachable.insert(child_id);
577                queue.push(child_id);
578            }
579        }
580    }
581
582    reachable
583}
584
585/// Classify a table for sharding
586fn classify_table(
587    table_name: &str,
588    table_id: TableId,
589    graph: &SchemaGraph,
590    tenant_roots: &AHashSet<TableId>,
591    reachable: &AHashSet<TableId>,
592    yaml_config: &Option<ShardYamlConfig>,
593) -> ShardTableClassification {
594    // Check YAML override first
595    if let Some(ref yaml) = yaml_config {
596        if let Some(class) = yaml.get_classification(table_name) {
597            return class;
598        }
599    }
600
601    // Check if it's a tenant root
602    if tenant_roots.contains(&table_id) {
603        return ShardTableClassification::TenantRoot;
604    }
605
606    // Check if reachable from tenant roots (dependent)
607    if reachable.contains(&table_id) {
608        // Check if it might be a junction table
609        if is_junction_table(table_name, table_id, graph) {
610            return ShardTableClassification::Junction;
611        }
612        return ShardTableClassification::TenantDependent;
613    }
614
615    // Check system patterns
616    if DefaultShardClassifier::is_system_table(table_name) {
617        return ShardTableClassification::System;
618    }
619
620    // Check lookup patterns
621    if DefaultShardClassifier::is_lookup_table(table_name) {
622        return ShardTableClassification::Lookup;
623    }
624
625    ShardTableClassification::Unknown
626}
627
628/// Check if a table is a junction table
629fn is_junction_table(table_name: &str, table_id: TableId, graph: &SchemaGraph) -> bool {
630    // Name-based heuristic
631    if DefaultShardClassifier::is_junction_table_by_name(table_name) {
632        return true;
633    }
634
635    // Structure-based: table with multiple FKs and few/no other columns
636    if let Some(table) = graph.schema.table(table_id) {
637        let fk_count = table.foreign_keys.len();
638        let fk_col_count: usize = table.foreign_keys.iter().map(|fk| fk.columns.len()).sum();
639        let total_cols = table.columns.len();
640
641        // Junction tables typically have mostly FK columns
642        if fk_count >= 2 && fk_col_count >= total_cols.saturating_sub(2) {
643            return true;
644        }
645    }
646
647    false
648}
649
650/// Find the index of the tenant column in a table
651fn find_tenant_column_index(table: &TableSchema, tenant_column: &str) -> Option<usize> {
652    table
653        .columns
654        .iter()
655        .position(|c| c.name.eq_ignore_ascii_case(tenant_column))
656}
657
658/// Determine if a table should be skipped
659fn should_skip_table(
660    table_name: &str,
661    classification: ShardTableClassification,
662    config: &ShardConfig,
663    yaml_config: &Option<ShardYamlConfig>,
664) -> bool {
665    // Check YAML skip override
666    if let Some(ref yaml) = yaml_config {
667        if yaml.should_skip(table_name) {
668            return true;
669        }
670    }
671
672    // System tables always skipped
673    if classification == ShardTableClassification::System {
674        return true;
675    }
676
677    // Lookup tables depend on config
678    if classification == ShardTableClassification::Lookup {
679        return config.include_global == GlobalTableMode::None;
680    }
681
682    false
683}
684
685/// Check if a row should be included in the shard
686#[allow(clippy::too_many_arguments)]
687fn should_include_row(
688    row: &UnifiedRow,
689    table_schema: &TableSchema,
690    classification: ShardTableClassification,
691    tenant_column_index: Option<usize>,
692    tenant_value: &PkValue,
693    runtimes: &AHashMap<TableId, TableRuntime>,
694    cyclic_set: &AHashSet<TableId>,
695    current_table_id: &TableId,
696) -> bool {
697    match classification {
698        ShardTableClassification::TenantRoot => {
699            // Check tenant column value using column_map for correct mapping
700            if let Some(idx) = tenant_column_index {
701                if let Some(val) = row.get_column_value(idx) {
702                    return val == tenant_value;
703                }
704            }
705            false
706        }
707        ShardTableClassification::TenantDependent => {
708            // Check if any FK points to a selected row
709            for (fk_ref, fk_tuple) in row.fk_values() {
710                if let Some(fk) = table_schema.foreign_keys.get(fk_ref.fk_index as usize) {
711                    if let Some(parent_id) = fk.referenced_table_id {
712                        // Skip FK check for cyclic tables
713                        if cyclic_set.contains(&parent_id) && cyclic_set.contains(current_table_id)
714                        {
715                            continue;
716                        }
717
718                        if let Some(parent_runtime) = runtimes.get(&parent_id) {
719                            if parent_runtime.pk_set.contains(fk_tuple) {
720                                return true;
721                            }
722                        }
723                    }
724                }
725            }
726            false
727        }
728        ShardTableClassification::Junction => {
729            // Include if ANY FK points to a selected row
730            for (fk_ref, fk_tuple) in row.fk_values() {
731                if let Some(fk) = table_schema.foreign_keys.get(fk_ref.fk_index as usize) {
732                    if let Some(parent_id) = fk.referenced_table_id {
733                        if let Some(parent_runtime) = runtimes.get(&parent_id) {
734                            if parent_runtime.pk_set.contains(fk_tuple) {
735                                return true;
736                            }
737                        }
738                    }
739                }
740            }
741            false
742        }
743        _ => false,
744    }
745}
746
747/// Write the sharded output
748fn write_output(
749    config: &ShardConfig,
750    _graph: &SchemaGraph,
751    table_order: &[TableId],
752    runtimes: &AHashMap<TableId, TableRuntime>,
753    tables_dir: &Path,
754    stats: &ShardStats,
755) -> anyhow::Result<()> {
756    let mut writer: Box<dyn Write> = match &config.output {
757        Some(path) => {
758            if let Some(parent) = path.parent() {
759                fs::create_dir_all(parent)?;
760            }
761            Box::new(BufWriter::with_capacity(256 * 1024, File::create(path)?))
762        }
763        None => Box::new(BufWriter::new(std::io::stdout())),
764    };
765
766    // Write header comment
767    write_header(&mut writer, config, stats)?;
768
769    // Write dialect-specific header
770    write_dialect_header(&mut writer, config.dialect)?;
771
772    // Write schema for each table (if enabled)
773    if config.include_schema {
774        for &table_id in table_order {
775            let runtime = match runtimes.get(&table_id) {
776                Some(r) if !r.skip && r.rows_selected > 0 => r,
777                _ => continue,
778            };
779
780            let table_file = tables_dir.join(format!("{}.sql", runtime.name));
781            if !table_file.exists() {
782                continue;
783            }
784
785            let file = File::open(&table_file)?;
786            let mut parser = Parser::with_dialect(file, 64 * 1024, config.dialect);
787
788            while let Some(stmt) = parser.read_statement()? {
789                let (stmt_type, _) =
790                    Parser::<&[u8]>::parse_statement_with_dialect(&stmt, config.dialect);
791
792                if stmt_type.is_schema() {
793                    writer.write_all(&stmt)?;
794                    writer.write_all(b"\n")?;
795                }
796            }
797        }
798    }
799
800    // Write data for each table (reading from temp files instead of memory)
801    for &table_id in table_order {
802        let runtime = match runtimes.get(&table_id) {
803            Some(r) if !r.skip && r.rows_selected > 0 && r.selected_temp_path.is_some() => r,
804            _ => continue,
805        };
806
807        let table_name = &runtime.name;
808        let row_count = runtime.rows_selected;
809
810        writeln!(writer, "\n-- Data: {} ({} rows)", table_name, row_count)?;
811
812        let quoted_name = quote_ident(config.dialect, table_name);
813
814        // Read rows from temp file and write INSERTs in chunks
815        let temp_path = runtime.selected_temp_path.as_ref().unwrap();
816        let mut spill_reader = RowSpillReader::open(temp_path)?;
817
818        const CHUNK_SIZE: usize = 1000;
819        let mut chunk_buffer: Vec<(RowFormat, Vec<u8>)> = Vec::with_capacity(CHUNK_SIZE);
820
821        while let Some((format, row_bytes)) = spill_reader.next_row()? {
822            chunk_buffer.push((format, row_bytes));
823
824            if chunk_buffer.len() >= CHUNK_SIZE {
825                write_insert_chunk(&mut writer, &quoted_name, &chunk_buffer, config.dialect)?;
826                chunk_buffer.clear();
827            }
828        }
829
830        // Write remaining rows
831        if !chunk_buffer.is_empty() {
832            write_insert_chunk(&mut writer, &quoted_name, &chunk_buffer, config.dialect)?;
833        }
834    }
835
836    // Write dialect-specific footer
837    write_dialect_footer(&mut writer, config.dialect)?;
838
839    writer.flush()?;
840
841    Ok(())
842}
843
844/// Write header comment
845fn write_header<W: Write>(
846    writer: &mut W,
847    config: &ShardConfig,
848    stats: &ShardStats,
849) -> std::io::Result<()> {
850    writeln!(writer, "-- Sharded from: {}", config.input.display())?;
851    writeln!(
852        writer,
853        "-- Date: {}",
854        chrono::Local::now().format("%Y-%m-%d %H:%M:%S")
855    )?;
856    if let Some(ref col) = stats.detected_tenant_column {
857        writeln!(writer, "-- Tenant column: {}", col)?;
858    }
859    writeln!(writer, "-- Tenant value: {}", config.tenant_value)?;
860    writeln!(writer, "-- Dialect: {}", config.dialect)?;
861    writeln!(writer, "--")?;
862    writeln!(writer, "-- Statistics:")?;
863    writeln!(writer, "--   Tables processed: {}", stats.tables_processed)?;
864    writeln!(writer, "--   Tables with data: {}", stats.tables_with_data)?;
865    writeln!(writer, "--   Tables skipped: {}", stats.tables_skipped)?;
866
867    let percent = if stats.total_rows_seen > 0 {
868        (stats.total_rows_selected as f64 / stats.total_rows_seen as f64) * 100.0
869    } else {
870        0.0
871    };
872    writeln!(
873        writer,
874        "--   Total rows: {} (from {} original, {:.1}%)",
875        stats.total_rows_selected, stats.total_rows_seen, percent
876    )?;
877
878    if stats.fk_orphans_skipped > 0 {
879        writeln!(
880            writer,
881            "--   FK orphans skipped: {}",
882            stats.fk_orphans_skipped
883        )?;
884    }
885
886    if !stats.warnings.is_empty() {
887        writeln!(writer, "--   Warnings: {}", stats.warnings.len())?;
888    }
889
890    writeln!(writer)?;
891
892    Ok(())
893}