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 rows_seen: u64,
121 rows_selected: u64,
123 skip: bool,
125 classification: ShardTableClassification,
127 fk_orphans: u64,
129 tenant_column_index: Option<usize>,
131 selected_temp_path: Option<PathBuf>,
133}
134
135pub 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 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 if config.progress {
152 eprintln!("Building schema graph...");
153 }
154
155 let graph = build_schema_graph(&tables_dir, config.dialect)?;
156
157 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 let tenant_pk_value = parse_tenant_value(&config.tenant_value);
167
168 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 let tenant_root_ids = find_tenant_root_tables(&graph, &tenant_column, &config, &yaml_config);
187
188 let reachable_from_roots = compute_reachable_tables(&graph, &tenant_root_ids);
190
191 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 let selected_dir = temp_dir.path().join("selected");
229 fs::create_dir_all(&selected_dir)?;
230
231 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 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 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 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 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 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
406fn detect_tenant_column(
408 config: &ShardConfig,
409 yaml_config: &Option<ShardYamlConfig>,
410 graph: &SchemaGraph,
411) -> anyhow::Result<String> {
412 if let Some(ref col) = config.tenant_column {
414 return Ok(col.clone());
415 }
416
417 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 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
444fn 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
455fn 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 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
488fn 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
508fn 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 if let Some(ref yaml) = yaml_config {
519 if let Some(class) = yaml.get_classification(table_name) {
520 return class;
521 }
522 }
523
524 if tenant_roots.contains(&table_id) {
526 return ShardTableClassification::TenantRoot;
527 }
528
529 if reachable.contains(&table_id) {
531 if is_junction_table(table_name, table_id, graph) {
533 return ShardTableClassification::Junction;
534 }
535 return ShardTableClassification::TenantDependent;
536 }
537
538 if DefaultShardClassifier::is_system_table(table_name) {
540 return ShardTableClassification::System;
541 }
542
543 if DefaultShardClassifier::is_lookup_table(table_name) {
545 return ShardTableClassification::Lookup;
546 }
547
548 ShardTableClassification::Unknown
549}
550
551fn is_junction_table(table_name: &str, table_id: TableId, graph: &SchemaGraph) -> bool {
553 if DefaultShardClassifier::is_junction_table_by_name(table_name) {
555 return true;
556 }
557
558 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 if fk_count >= 2 && fk_col_count >= total_cols.saturating_sub(2) {
566 return true;
567 }
568 }
569
570 false
571}
572
573fn 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
581fn should_skip_table(
583 table_name: &str,
584 classification: ShardTableClassification,
585 config: &ShardConfig,
586 yaml_config: &Option<ShardYamlConfig>,
587) -> bool {
588 if let Some(ref yaml) = yaml_config {
590 if yaml.should_skip(table_name) {
591 return true;
592 }
593 }
594
595 if classification == ShardTableClassification::System {
597 return true;
598 }
599
600 if classification == ShardTableClassification::Lookup {
602 return config.include_global == GlobalTableMode::None;
603 }
604
605 false
606}
607
608#[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 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 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 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 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
670fn 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(&mut writer, config, stats)?;
691
692 write_dialect_header(&mut writer, config.dialect)?;
694
695 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 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 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, "ed_name, &chunk_buffer, config.dialect)?;
749 chunk_buffer.clear();
750 }
751 }
752
753 if !chunk_buffer.is_empty() {
755 write_insert_chunk(&mut writer, "ed_name, &chunk_buffer, config.dialect)?;
756 }
757 }
758
759 write_dialect_footer(&mut writer, config.dialect)?;
761
762 writer.flush()?;
763
764 Ok(())
765}
766
767fn 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}