1mod epoch;
2
3#[allow(unused_imports)] pub use epoch::advance_epoch_boundary;
5use epoch::EpochDriver;
6
7use crate::parser::{determine_buffer_size, ContentFilter, Parser, SqlDialect, StatementType};
8use crate::progress::ProgressReader;
9use crate::writer::{
10 env_writer_count, probe_output_dir, Clock, Controller, IoStrategy, ParallelWriters,
11 ProfileKind, ProfileValues, RealClock, WriterProfile,
12};
13use ahash::AHashSet;
14use anyhow::Context;
15use serde::Serialize;
16use std::fs::File;
17use std::io::Read;
18use std::path::{Path, PathBuf};
19use std::sync::Arc;
20
21#[derive(Serialize)]
23pub struct Stats {
24 pub statements_processed: u64,
26 pub tables_found: usize,
28 pub bytes_processed: u64,
30 pub table_names: Vec<String>,
32 #[serde(skip)]
35 pub writers_used: usize,
36 #[serde(skip)]
39 pub io_transitions: Vec<String>,
40}
41
42#[derive(Default)]
44pub struct SplitterConfig {
45 pub dialect: SqlDialect,
47 pub dry_run: bool,
49 pub table_filter: Option<AHashSet<String>>,
51 pub progress_fn: Option<Box<dyn Fn(u64)>>,
53 pub content_filter: ContentFilter,
55 pub output_compression: Compression,
57 pub io_strategy: IoStrategy,
59 pub io_clock: Option<Arc<dyn Clock>>,
62}
63
64#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
66pub enum Compression {
67 #[default]
68 None,
69 Gzip,
70 Bzip2,
71 Xz,
72 Zstd,
73 Zip,
78}
79
80impl Compression {
81 pub fn from_path(path: &Path) -> Self {
83 let ext = path
84 .extension()
85 .and_then(|e| e.to_str())
86 .map(|e| e.to_lowercase());
87
88 match ext.as_deref() {
89 Some("gz" | "gzip") => Compression::Gzip,
90 Some("bz2" | "bzip2") => Compression::Bzip2,
91 Some("xz" | "lzma") => Compression::Xz,
92 Some("zst" | "zstd") => Compression::Zstd,
93 Some("zip") => Compression::Zip,
94 _ => Compression::None,
95 }
96 }
97
98 pub fn parse_output(s: &str) -> Result<Self, String> {
100 match s.to_lowercase().as_str() {
101 "none" | "" => Ok(Compression::None),
102 "gzip" | "gz" => Ok(Compression::Gzip),
103 "bzip2" | "bz2" => Ok(Compression::Bzip2),
104 "xz" | "lzma" => Ok(Compression::Xz),
105 "zstd" | "zst" => Ok(Compression::Zstd),
106 other => Err(format!(
107 "Unknown compression '{other}'. Valid: none, gzip, bzip2, xz, zstd"
108 )),
109 }
110 }
111
112 pub fn output_extension(&self) -> &'static str {
114 match self {
115 Compression::None => "",
116 Compression::Gzip => ".gz",
117 Compression::Bzip2 => ".bz2",
118 Compression::Xz => ".xz",
119 Compression::Zstd => ".zst",
120 Compression::Zip => "",
123 }
124 }
125
126 pub fn wrap_reader<'a>(
128 &self,
129 reader: Box<dyn Read + 'a>,
130 ) -> std::io::Result<Box<dyn Read + 'a>> {
131 Ok(match self {
132 Compression::None => reader,
133 #[cfg(feature = "compression")]
134 Compression::Gzip => Box::new(flate2::read::GzDecoder::new(reader)),
135 #[cfg(feature = "compression")]
136 Compression::Bzip2 => Box::new(bzip2::read::BzDecoder::new(reader)),
137 #[cfg(feature = "compression")]
138 Compression::Xz => Box::new(xz2::read::XzDecoder::new(reader)),
139 #[cfg(feature = "compression")]
140 Compression::Zstd => Box::new(zstd::stream::read::Decoder::new(reader)?),
141 Compression::Zip => {
145 return Err(std::io::Error::new(
146 std::io::ErrorKind::Unsupported,
147 "zip input must be opened via open_input(), not wrap_reader() (needs a seekable File)",
148 ))
149 }
150 #[cfg(not(feature = "compression"))]
151 _ => {
152 return Err(std::io::Error::new(
153 std::io::ErrorKind::Unsupported,
154 "compressed input requires the `compression` feature",
155 ))
156 }
157 })
158 }
159}
160
161impl std::fmt::Display for Compression {
162 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
163 match self {
164 Compression::None => write!(f, "none"),
165 Compression::Gzip => write!(f, "gzip"),
166 Compression::Bzip2 => write!(f, "bzip2"),
167 Compression::Xz => write!(f, "xz"),
168 Compression::Zstd => write!(f, "zstd"),
169 Compression::Zip => write!(f, "zip"),
170 }
171 }
172}
173
174pub fn open_input_opt_progress(
186 path: &Path,
187 progress_fn: Option<Box<dyn Fn(u64)>>,
188) -> anyhow::Result<Box<dyn Read>> {
189 let compression = Compression::from_path(path);
190
191 if compression == Compression::Zip {
192 #[cfg(feature = "archive")]
193 {
194 return crate::zip_input::open_zip_member(path, progress_fn);
195 }
196 #[cfg(not(feature = "archive"))]
197 {
198 anyhow::bail!("zip input requires the `archive` feature");
199 }
200 }
201
202 let file = File::open(path).with_context(|| format!("Failed to open input file: {path:?}"))?;
203 let reader: Box<dyn Read> = match progress_fn {
204 Some(cb) => Box::new(ProgressReader::new(file, cb)),
205 None => Box::new(file),
206 };
207 compression
208 .wrap_reader(reader)
209 .with_context(|| format!("Failed to initialize {compression} decompression for {path:?}"))
210}
211
212pub fn open_input(path: &Path) -> anyhow::Result<Box<dyn Read>> {
214 open_input_opt_progress(path, None)
215}
216
217pub fn open_input_with_progress(
219 path: &Path,
220 progress_fn: Box<dyn Fn(u64)>,
221) -> anyhow::Result<Box<dyn Read>> {
222 open_input_opt_progress(path, Some(progress_fn))
223}
224
225pub fn input_progress_len(path: &Path) -> u64 {
237 #[cfg(feature = "archive")]
238 if Compression::from_path(path) == Compression::Zip {
239 if let Ok(size) = crate::zip_input::sql_member_compressed_size(path) {
240 return size;
241 }
242 }
243 std::fs::metadata(path).map(|m| m.len()).unwrap_or(0)
244}
245
246#[doc(hidden)]
252pub fn estimate_uncompressed_size(file_size: u64, compression: Compression) -> u64 {
253 match compression {
254 Compression::None => file_size,
255 _ => file_size.saturating_mul(4),
256 }
257}
258
259pub struct Splitter {
260 input_file: PathBuf,
261 output_dir: PathBuf,
262 config: SplitterConfig,
263}
264
265impl Splitter {
266 pub fn new(input_file: PathBuf, output_dir: PathBuf) -> Self {
267 Self {
268 input_file,
269 output_dir,
270 config: SplitterConfig::default(),
271 }
272 }
273
274 pub fn with_dialect(mut self, dialect: SqlDialect) -> Self {
275 self.config.dialect = dialect;
276 self
277 }
278
279 pub fn with_dry_run(mut self, dry_run: bool) -> Self {
280 self.config.dry_run = dry_run;
281 self
282 }
283
284 pub fn with_table_filter(mut self, tables: Vec<String>) -> Self {
285 if !tables.is_empty() {
286 self.config.table_filter = Some(tables.into_iter().collect());
287 }
288 self
289 }
290
291 pub fn with_progress<F: Fn(u64) + 'static>(mut self, f: F) -> Self {
292 self.config.progress_fn = Some(Box::new(f));
293 self
294 }
295
296 pub fn with_content_filter(mut self, filter: ContentFilter) -> Self {
297 self.config.content_filter = filter;
298 self
299 }
300
301 pub fn with_output_compression(mut self, format: Compression) -> Self {
302 self.config.output_compression = format;
303 self
304 }
305
306 pub fn with_io_profile(mut self, profile: IoStrategy) -> Self {
310 self.config.io_strategy = profile;
311 self
312 }
313
314 #[doc(hidden)]
318 pub fn with_io_clock(mut self, clock: Arc<dyn Clock>) -> Self {
319 self.config.io_clock = Some(clock);
320 self
321 }
322
323 pub fn split(mut self) -> anyhow::Result<Stats> {
324 let file_size = std::fs::metadata(&self.input_file)
325 .with_context(|| format!("Failed to open input file: {:?}", self.input_file))?
326 .len();
327 let buffer_size = determine_buffer_size(file_size);
328 let dialect = self.config.dialect;
329 let content_filter = self.config.content_filter;
330
331 let reader: Box<dyn Read> =
334 open_input_opt_progress(&self.input_file, self.config.progress_fn.take())?;
335
336 let mut parser = Parser::with_dialect(reader, buffer_size, dialect);
337
338 let out_compression = self.config.output_compression;
343 let compressing = out_compression != Compression::None;
344 let cores = std::thread::available_parallelism()
345 .map(|n| n.get())
346 .unwrap_or(4);
347
348 let epoch_bytes = std::env::var("SQL_SPLITTER_EPOCH_BYTES")
352 .ok()
353 .and_then(|v| v.parse::<u64>().ok())
354 .filter(|&n| n > 0);
355 const DEFAULT_EPOCH_BYTES: u64 = 256 * 1024 * 1024;
364 const AUTO_MIN_FILE_SIZE: u64 = 64 * 1024 * 1024;
365 let input_size_estimate =
366 estimate_uncompressed_size(file_size, Compression::from_path(&self.input_file));
367 let adaptive = self.config.io_strategy == IoStrategy::Auto
368 && !self.config.dry_run
369 && (epoch_bytes.is_some() || input_size_estimate >= AUTO_MIN_FILE_SIZE);
370 let epoch_bytes = epoch_bytes
372 .unwrap_or_else(|| DEFAULT_EPOCH_BYTES.min((input_size_estimate / 4).max(1)));
373
374 let opening_kind = match self.config.io_strategy.pinned() {
375 Some(kind) => kind,
376 None if adaptive => probe_output_dir(&self.output_dir),
379 None => ProfileKind::Ssd,
380 };
381 let profile =
382 WriterProfile::for_kind(opening_kind, cores, compressing).with_env_overrides();
383
384 let initial_writers = if adaptive && !compressing {
396 env_writer_count().unwrap_or(1)
397 } else {
398 profile.writers
399 };
400 let fast_writers = if env_writer_count().is_some() {
401 initial_writers
402 } else {
403 WriterProfile::for_kind(ProfileKind::Ssd, cores, compressing).writers
404 };
405
406 let values = Arc::new(ProfileValues::new(&profile));
407 let mut writers = if self.config.dry_run {
408 None
409 } else {
410 let capacity = (profile.stage_cap / profile.flush_chunk.max(1)).clamp(4, 64);
414 Some(
415 ParallelWriters::new(
416 self.output_dir.clone(),
417 initial_writers,
418 capacity,
419 out_compression,
420 Arc::clone(&values),
421 )
422 .with_context(|| {
423 format!("Failed to create output directory: {:?}", self.output_dir)
424 })?,
425 )
426 };
427
428 let mut epoch_driver = adaptive.then(|| {
432 let ctrl = Controller::new(opening_kind, fast_writers);
433 let ctrl = if compressing {
434 ctrl.for_compressed_output()
435 } else {
436 ctrl
437 };
438 let clock: Arc<dyn Clock> = self
439 .config
440 .io_clock
441 .take()
442 .unwrap_or_else(|| Arc::new(RealClock::new()));
443 EpochDriver::new(
444 ctrl,
445 clock,
446 Arc::clone(&values),
447 epoch_bytes,
448 cores,
449 compressing,
450 )
451 });
452
453 let mut tables_seen: AHashSet<String> = AHashSet::new();
454 let mut stats = Stats {
455 statements_processed: 0,
456 tables_found: 0,
457 bytes_processed: 0,
458 table_names: Vec::new(),
459 writers_used: initial_writers,
460 io_transitions: Vec::new(),
461 };
462
463 let mut last_copy_table: Option<String> = None;
465
466 while let Some(stmt) = parser.read_statement()? {
467 let (stmt_type, mut table_name) =
468 Parser::<&[u8]>::parse_statement_with_dialect(&stmt, dialect);
469
470 if stmt_type == StatementType::Copy {
472 last_copy_table = Some(table_name.clone());
473 }
474
475 let is_copy_data = if stmt_type == StatementType::Unknown && last_copy_table.is_some() {
477 if stmt.ends_with(b"\\.\n") || stmt.ends_with(b"\\.\r\n") {
479 if let Some(copy_table) = last_copy_table.take() {
481 table_name = copy_table;
482 true
483 } else {
484 false
485 }
486 } else {
487 false
488 }
489 } else {
490 false
491 };
492
493 if !is_copy_data && (stmt_type == StatementType::Unknown || table_name.is_empty()) {
494 continue;
495 }
496
497 match content_filter {
499 ContentFilter::SchemaOnly => {
500 if !stmt_type.is_schema() {
501 continue;
502 }
503 }
504 ContentFilter::DataOnly => {
505 if !stmt_type.is_data() && !is_copy_data {
507 continue;
508 }
509 }
510 ContentFilter::All => {}
511 }
512
513 if let Some(ref filter) = self.config.table_filter {
514 if !filter.contains(&table_name) {
515 continue;
516 }
517 }
518
519 if !tables_seen.contains(&table_name) {
520 tables_seen.insert(table_name.clone());
521 stats.tables_found += 1;
522 stats.table_names.push(table_name.clone());
523 }
524
525 if let Some(w) = writers.as_mut() {
526 let suffix: &[u8] = if self.config.dialect == SqlDialect::Mssql {
530 let last = stmt
531 .iter()
532 .rev()
533 .find(|&&b| b != b'\n' && b != b'\r' && b != b' ' && b != b'\t');
534 if last != Some(&b';') {
535 b";"
536 } else {
537 b""
538 }
539 } else {
540 b""
541 };
542 w.write(&table_name, &stmt, suffix);
543
544 if w.errored() {
546 break;
547 }
548 }
549
550 stats.statements_processed += 1;
551 stats.bytes_processed += stmt.len() as u64;
552
553 if let (Some(driver), Some(w)) = (epoch_driver.as_mut(), writers.as_mut()) {
559 driver.on_bytes(w, &mut stats);
560 }
561 }
562
563 if let Some(w) = writers {
564 w.finish()
565 .with_context(|| format!("Failed writing output to {:?}", self.output_dir))?;
566 }
567
568 Ok(stats)
569 }
570}