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")]
138 Compression::Gzip => Box::new(flate2::read::MultiGzDecoder::new(reader)),
139 #[cfg(feature = "compression")]
140 Compression::Bzip2 => Box::new(bzip2::read::MultiBzDecoder::new(reader)),
141 #[cfg(feature = "compression")]
142 Compression::Xz => Box::new(xz2::read::XzDecoder::new_multi_decoder(reader)),
143 #[cfg(feature = "compression")]
144 Compression::Zstd => Box::new(zstd::stream::read::Decoder::new(reader)?),
145 Compression::Zip => {
149 return Err(std::io::Error::new(
150 std::io::ErrorKind::Unsupported,
151 "zip input must be opened via open_input(), not wrap_reader() (needs a seekable File)",
152 ))
153 }
154 #[cfg(not(feature = "compression"))]
155 _ => {
156 return Err(std::io::Error::new(
157 std::io::ErrorKind::Unsupported,
158 "compressed input requires the `compression` feature",
159 ))
160 }
161 })
162 }
163}
164
165impl std::fmt::Display for Compression {
166 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
167 match self {
168 Compression::None => write!(f, "none"),
169 Compression::Gzip => write!(f, "gzip"),
170 Compression::Bzip2 => write!(f, "bzip2"),
171 Compression::Xz => write!(f, "xz"),
172 Compression::Zstd => write!(f, "zstd"),
173 Compression::Zip => write!(f, "zip"),
174 }
175 }
176}
177
178pub fn open_input_opt_progress(
190 path: &Path,
191 progress_fn: Option<Box<dyn Fn(u64)>>,
192) -> anyhow::Result<Box<dyn Read>> {
193 let compression = Compression::from_path(path);
194
195 if compression == Compression::Zip {
196 #[cfg(feature = "archive")]
197 {
198 return crate::zip_input::open_zip_member(path, progress_fn);
199 }
200 #[cfg(not(feature = "archive"))]
201 {
202 anyhow::bail!("zip input requires the `archive` feature");
203 }
204 }
205
206 let file = File::open(path).with_context(|| format!("Failed to open input file: {path:?}"))?;
207 let reader: Box<dyn Read> = match progress_fn {
208 Some(cb) => Box::new(ProgressReader::new(file, cb)),
209 None => Box::new(file),
210 };
211 compression
212 .wrap_reader(reader)
213 .with_context(|| format!("Failed to initialize {compression} decompression for {path:?}"))
214}
215
216pub fn open_input(path: &Path) -> anyhow::Result<Box<dyn Read>> {
218 open_input_opt_progress(path, None)
219}
220
221pub fn open_input_with_progress(
223 path: &Path,
224 progress_fn: Box<dyn Fn(u64)>,
225) -> anyhow::Result<Box<dyn Read>> {
226 open_input_opt_progress(path, Some(progress_fn))
227}
228
229pub fn input_progress_len(path: &Path) -> u64 {
241 #[cfg(feature = "archive")]
242 if Compression::from_path(path) == Compression::Zip {
243 if let Ok(size) = crate::zip_input::sql_member_compressed_size(path) {
244 return size;
245 }
246 }
247 std::fs::metadata(path).map(|m| m.len()).unwrap_or(0)
248}
249
250#[doc(hidden)]
256pub fn estimate_uncompressed_size(file_size: u64, compression: Compression) -> u64 {
257 match compression {
258 Compression::None => file_size,
259 _ => file_size.saturating_mul(4),
260 }
261}
262
263pub struct Splitter {
264 input_file: PathBuf,
265 output_dir: PathBuf,
266 config: SplitterConfig,
267}
268
269impl Splitter {
270 pub fn new(input_file: PathBuf, output_dir: PathBuf) -> Self {
271 Self {
272 input_file,
273 output_dir,
274 config: SplitterConfig::default(),
275 }
276 }
277
278 pub fn with_dialect(mut self, dialect: SqlDialect) -> Self {
279 self.config.dialect = dialect;
280 self
281 }
282
283 pub fn with_dry_run(mut self, dry_run: bool) -> Self {
284 self.config.dry_run = dry_run;
285 self
286 }
287
288 pub fn with_table_filter(mut self, tables: Vec<String>) -> Self {
289 if !tables.is_empty() {
290 self.config.table_filter = Some(tables.into_iter().collect());
291 }
292 self
293 }
294
295 pub fn with_progress<F: Fn(u64) + 'static>(mut self, f: F) -> Self {
296 self.config.progress_fn = Some(Box::new(f));
297 self
298 }
299
300 pub fn with_content_filter(mut self, filter: ContentFilter) -> Self {
301 self.config.content_filter = filter;
302 self
303 }
304
305 pub fn with_output_compression(mut self, format: Compression) -> Self {
306 self.config.output_compression = format;
307 self
308 }
309
310 pub fn with_io_profile(mut self, profile: IoStrategy) -> Self {
314 self.config.io_strategy = profile;
315 self
316 }
317
318 #[doc(hidden)]
322 pub fn with_io_clock(mut self, clock: Arc<dyn Clock>) -> Self {
323 self.config.io_clock = Some(clock);
324 self
325 }
326
327 pub fn split(mut self) -> anyhow::Result<Stats> {
328 let file_size = std::fs::metadata(&self.input_file)
329 .with_context(|| format!("Failed to open input file: {:?}", self.input_file))?
330 .len();
331 let buffer_size = determine_buffer_size(file_size);
332 let dialect = self.config.dialect;
333 let content_filter = self.config.content_filter;
334
335 let reader: Box<dyn Read> =
338 open_input_opt_progress(&self.input_file, self.config.progress_fn.take())?;
339
340 let mut parser = Parser::with_dialect(reader, buffer_size, dialect);
341
342 let out_compression = self.config.output_compression;
347 let compressing = out_compression != Compression::None;
348 let cores = std::thread::available_parallelism()
349 .map(|n| n.get())
350 .unwrap_or(4);
351
352 let epoch_bytes = std::env::var("SQL_SPLITTER_EPOCH_BYTES")
356 .ok()
357 .and_then(|v| v.parse::<u64>().ok())
358 .filter(|&n| n > 0);
359 const DEFAULT_EPOCH_BYTES: u64 = 256 * 1024 * 1024;
368 const AUTO_MIN_FILE_SIZE: u64 = 64 * 1024 * 1024;
369 let input_size_estimate =
370 estimate_uncompressed_size(file_size, Compression::from_path(&self.input_file));
371 let adaptive = self.config.io_strategy == IoStrategy::Auto
372 && !self.config.dry_run
373 && (epoch_bytes.is_some() || input_size_estimate >= AUTO_MIN_FILE_SIZE);
374 let epoch_bytes = epoch_bytes
376 .unwrap_or_else(|| DEFAULT_EPOCH_BYTES.min((input_size_estimate / 4).max(1)));
377
378 let opening_kind = match self.config.io_strategy.pinned() {
379 Some(kind) => kind,
380 None if adaptive => probe_output_dir(&self.output_dir),
383 None => ProfileKind::Ssd,
384 };
385 let profile =
386 WriterProfile::for_kind(opening_kind, cores, compressing).with_env_overrides();
387
388 let initial_writers = if adaptive && !compressing {
400 env_writer_count().unwrap_or(1)
401 } else {
402 profile.writers
403 };
404 let fast_writers = if env_writer_count().is_some() {
405 initial_writers
406 } else {
407 WriterProfile::for_kind(ProfileKind::Ssd, cores, compressing).writers
408 };
409
410 let values = Arc::new(ProfileValues::new(&profile));
411 let mut writers = if self.config.dry_run {
412 None
413 } else {
414 let capacity = (profile.stage_cap / profile.flush_chunk.max(1)).clamp(4, 64);
418 Some(
419 ParallelWriters::new(
420 self.output_dir.clone(),
421 initial_writers,
422 capacity,
423 out_compression,
424 Arc::clone(&values),
425 )
426 .with_context(|| {
427 format!("Failed to create output directory: {:?}", self.output_dir)
428 })?,
429 )
430 };
431
432 let mut epoch_driver = adaptive.then(|| {
436 let ctrl = Controller::new(opening_kind, fast_writers);
437 let ctrl = if compressing {
438 ctrl.for_compressed_output()
439 } else {
440 ctrl
441 };
442 let clock: Arc<dyn Clock> = self
443 .config
444 .io_clock
445 .take()
446 .unwrap_or_else(|| Arc::new(RealClock::new()));
447 EpochDriver::new(
448 ctrl,
449 clock,
450 Arc::clone(&values),
451 epoch_bytes,
452 cores,
453 compressing,
454 )
455 });
456
457 let mut tables_seen: AHashSet<String> = AHashSet::new();
458 let mut stats = Stats {
459 statements_processed: 0,
460 tables_found: 0,
461 bytes_processed: 0,
462 table_names: Vec::new(),
463 writers_used: initial_writers,
464 io_transitions: Vec::new(),
465 };
466
467 let mut last_copy_table: Option<String> = None;
469
470 while let Some(stmt) = parser.read_statement()? {
471 let (stmt_type, mut table_name) =
472 Parser::<&[u8]>::parse_statement_with_dialect(&stmt, dialect);
473
474 if stmt_type == StatementType::Copy {
476 last_copy_table = Some(table_name.clone());
477 }
478
479 let is_copy_data = if stmt_type == StatementType::Unknown && last_copy_table.is_some() {
481 if stmt.ends_with(b"\\.\n") || stmt.ends_with(b"\\.\r\n") {
483 if let Some(copy_table) = last_copy_table.take() {
485 table_name = copy_table;
486 true
487 } else {
488 false
489 }
490 } else {
491 false
492 }
493 } else {
494 false
495 };
496
497 if !is_copy_data && (stmt_type == StatementType::Unknown || table_name.is_empty()) {
498 continue;
499 }
500
501 match content_filter {
503 ContentFilter::SchemaOnly => {
504 if !stmt_type.is_schema() {
505 continue;
506 }
507 }
508 ContentFilter::DataOnly => {
509 if !stmt_type.is_data() && !is_copy_data {
511 continue;
512 }
513 }
514 ContentFilter::All => {}
515 }
516
517 if let Some(ref filter) = self.config.table_filter {
518 if !filter.contains(&table_name) {
519 continue;
520 }
521 }
522
523 if !tables_seen.contains(&table_name) {
524 tables_seen.insert(table_name.clone());
525 stats.tables_found += 1;
526 stats.table_names.push(table_name.clone());
527 }
528
529 if let Some(w) = writers.as_mut() {
530 let suffix: &[u8] = if self.config.dialect == SqlDialect::Mssql {
534 let last = stmt
535 .iter()
536 .rev()
537 .find(|&&b| b != b'\n' && b != b'\r' && b != b' ' && b != b'\t');
538 if last != Some(&b';') {
539 b";"
540 } else {
541 b""
542 }
543 } else {
544 b""
545 };
546 w.write(&table_name, &stmt, suffix);
547
548 if w.errored() {
550 break;
551 }
552 }
553
554 stats.statements_processed += 1;
555 stats.bytes_processed += stmt.len() as u64;
556
557 if let (Some(driver), Some(w)) = (epoch_driver.as_mut(), writers.as_mut()) {
563 driver.on_bytes(w, &mut stats);
564 }
565 }
566
567 if let Some(w) = writers {
568 w.finish()
569 .with_context(|| format!("Failed writing output to {:?}", self.output_dir))?;
570 }
571
572 Ok(stats)
573 }
574}
575
576#[cfg(all(test, feature = "compression"))]
577mod multi_member_tests {
578 use super::Compression;
579 use std::io::{Read, Write};
580
581 fn gzip(data: &[u8]) -> Vec<u8> {
582 let mut e = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
583 e.write_all(data).unwrap();
584 e.finish().unwrap()
585 }
586
587 fn bzip2(data: &[u8]) -> Vec<u8> {
588 let mut e = bzip2::write::BzEncoder::new(Vec::new(), bzip2::Compression::default());
589 e.write_all(data).unwrap();
590 e.finish().unwrap()
591 }
592
593 fn xz(data: &[u8]) -> Vec<u8> {
594 let mut e = xz2::write::XzEncoder::new(Vec::new(), 6);
595 e.write_all(data).unwrap();
596 e.finish().unwrap()
597 }
598
599 fn decoded(compression: Compression, bytes: Vec<u8>) -> Vec<u8> {
600 let reader: Box<dyn Read> = Box::new(std::io::Cursor::new(bytes));
601 let mut out = Vec::new();
602 compression
603 .wrap_reader(reader)
604 .unwrap()
605 .read_to_end(&mut out)
606 .unwrap();
607 out
608 }
609
610 #[test]
611 fn gzip_reads_all_concatenated_members() {
612 let mut concat = gzip(b"CREATE TABLE a (id INT);\n");
613 concat.extend(gzip(b"CREATE TABLE b (id INT);\n"));
614 assert_eq!(
615 decoded(Compression::Gzip, concat),
616 b"CREATE TABLE a (id INT);\nCREATE TABLE b (id INT);\n",
617 "second gzip member was truncated"
618 );
619 }
620
621 #[test]
622 fn bzip2_reads_all_concatenated_streams() {
623 let mut concat = bzip2(b"CREATE TABLE a (id INT);\n");
624 concat.extend(bzip2(b"CREATE TABLE b (id INT);\n"));
625 assert_eq!(
626 decoded(Compression::Bzip2, concat),
627 b"CREATE TABLE a (id INT);\nCREATE TABLE b (id INT);\n",
628 "second bzip2 stream was truncated"
629 );
630 }
631
632 #[test]
633 fn xz_reads_all_concatenated_streams() {
634 let mut concat = xz(b"CREATE TABLE a (id INT);\n");
635 concat.extend(xz(b"CREATE TABLE b (id INT);\n"));
636 assert_eq!(
637 decoded(Compression::Xz, concat),
638 b"CREATE TABLE a (id INT);\nCREATE TABLE b (id INT);\n",
639 "second xz stream was truncated"
640 );
641 }
642}