1mod 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#[derive(Debug)]
32pub struct ShardConfig {
33 pub input: PathBuf,
35 pub output: Option<PathBuf>,
37 pub dialect: SqlDialect,
39 pub tenant_column: Option<String>,
41 pub tenant_value: String,
43 pub root_tables: Vec<String>,
45 pub include_global: GlobalTableMode,
47 pub dry_run: bool,
49 pub progress: bool,
51 pub config_file: Option<PathBuf>,
53 pub max_selected_rows: Option<usize>,
55 pub strict_fk: bool,
57 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#[derive(Debug, Default, serde::Serialize)]
83pub struct ShardStats {
84 pub tables_processed: usize,
86 pub tables_skipped: usize,
88 pub tables_with_data: usize,
90 pub total_rows_selected: u64,
92 pub total_rows_seen: u64,
94 pub table_stats: Vec<TableShardStats>,
96 pub warnings: Vec<String>,
98 pub fk_orphans_skipped: u64,
100 pub detected_tenant_column: Option<String>,
102}
103
104#[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
113struct TableRuntime {
115 name: String,
117 pk_set: PkSet,
119 source_pk_set: Option<PkSet>,
122 rows_seen: u64,
124 rows_selected: u64,
126 skip: bool,
128 classification: ShardTableClassification,
130 fk_orphans: u64,
132 tenant_column_index: Option<usize>,
134 selected_temp_path: Option<PathBuf>,
136}
137
138pub 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 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 if config.progress {
155 eprintln!("Building schema graph...");
156 }
157
158 let graph = build_schema_graph(&tables_dir, config.dialect)?;
159
160 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 let tenant_pk_value = parse_tenant_value(&config.tenant_value);
170
171 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 let tenant_root_ids = find_tenant_root_tables(&graph, &tenant_column, &config, &yaml_config);
190
191 let reachable_from_roots = compute_reachable_tables(&graph, &tenant_root_ids);
193
194 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 let selected_dir = temp_dir.path().join("selected");
237 fs::create_dir_all(&selected_dir)?;
238
239 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 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 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 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 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 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
418fn 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
457fn 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
483fn detect_tenant_column(
485 config: &ShardConfig,
486 yaml_config: &Option<ShardYamlConfig>,
487 graph: &SchemaGraph,
488) -> anyhow::Result<String> {
489 if let Some(ref col) = config.tenant_column {
491 return Ok(col.clone());
492 }
493
494 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 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
521fn 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
532fn 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 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
565fn 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
585fn 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 if let Some(ref yaml) = yaml_config {
596 if let Some(class) = yaml.get_classification(table_name) {
597 return class;
598 }
599 }
600
601 if tenant_roots.contains(&table_id) {
603 return ShardTableClassification::TenantRoot;
604 }
605
606 if reachable.contains(&table_id) {
608 if is_junction_table(table_name, table_id, graph) {
610 return ShardTableClassification::Junction;
611 }
612 return ShardTableClassification::TenantDependent;
613 }
614
615 if DefaultShardClassifier::is_system_table(table_name) {
617 return ShardTableClassification::System;
618 }
619
620 if DefaultShardClassifier::is_lookup_table(table_name) {
622 return ShardTableClassification::Lookup;
623 }
624
625 ShardTableClassification::Unknown
626}
627
628fn is_junction_table(table_name: &str, table_id: TableId, graph: &SchemaGraph) -> bool {
630 if DefaultShardClassifier::is_junction_table_by_name(table_name) {
632 return true;
633 }
634
635 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 if fk_count >= 2 && fk_col_count >= total_cols.saturating_sub(2) {
643 return true;
644 }
645 }
646
647 false
648}
649
650fn 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
658fn should_skip_table(
660 table_name: &str,
661 classification: ShardTableClassification,
662 config: &ShardConfig,
663 yaml_config: &Option<ShardYamlConfig>,
664) -> bool {
665 if let Some(ref yaml) = yaml_config {
667 if yaml.should_skip(table_name) {
668 return true;
669 }
670 }
671
672 if classification == ShardTableClassification::System {
674 return true;
675 }
676
677 if classification == ShardTableClassification::Lookup {
679 return config.include_global == GlobalTableMode::None;
680 }
681
682 false
683}
684
685#[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 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 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 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 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
747fn 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(&mut writer, config, stats)?;
768
769 write_dialect_header(&mut writer, config.dialect)?;
771
772 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 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 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, "ed_name, &chunk_buffer, config.dialect)?;
826 chunk_buffer.clear();
827 }
828 }
829
830 if !chunk_buffer.is_empty() {
832 write_insert_chunk(&mut writer, "ed_name, &chunk_buffer, config.dialect)?;
833 }
834 }
835
836 write_dialect_footer(&mut writer, config.dialect)?;
838
839 writer.flush()?;
840
841 Ok(())
842}
843
844fn 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}