mod epoch;
#[allow(unused_imports)] pub use epoch::advance_epoch_boundary;
use epoch::EpochDriver;
use crate::parser::{determine_buffer_size, ContentFilter, Parser, SqlDialect, StatementType};
use crate::progress::ProgressReader;
use crate::writer::{
env_writer_count, probe_output_dir, Clock, Controller, IoStrategy, ParallelWriters,
ProfileKind, ProfileValues, RealClock, WriterProfile,
};
use ahash::AHashSet;
use anyhow::Context;
use serde::Serialize;
use std::fs::File;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::sync::Arc;
#[derive(Serialize)]
pub struct Stats {
pub statements_processed: u64,
pub tables_found: usize,
pub bytes_processed: u64,
pub table_names: Vec<String>,
#[serde(skip)]
pub writers_used: usize,
#[serde(skip)]
pub io_transitions: Vec<String>,
}
#[derive(Default)]
pub struct SplitterConfig {
pub dialect: SqlDialect,
pub dry_run: bool,
pub table_filter: Option<AHashSet<String>>,
pub progress_fn: Option<Box<dyn Fn(u64)>>,
pub content_filter: ContentFilter,
pub output_compression: Compression,
pub io_strategy: IoStrategy,
pub io_clock: Option<Arc<dyn Clock>>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Compression {
#[default]
None,
Gzip,
Bzip2,
Xz,
Zstd,
Zip,
}
impl Compression {
pub fn from_path(path: &Path) -> Self {
let ext = path
.extension()
.and_then(|e| e.to_str())
.map(|e| e.to_lowercase());
match ext.as_deref() {
Some("gz" | "gzip") => Compression::Gzip,
Some("bz2" | "bzip2") => Compression::Bzip2,
Some("xz" | "lzma") => Compression::Xz,
Some("zst" | "zstd") => Compression::Zstd,
Some("zip") => Compression::Zip,
_ => Compression::None,
}
}
pub fn parse_output(s: &str) -> Result<Self, String> {
match s.to_lowercase().as_str() {
"none" | "" => Ok(Compression::None),
"gzip" | "gz" => Ok(Compression::Gzip),
"bzip2" | "bz2" => Ok(Compression::Bzip2),
"xz" | "lzma" => Ok(Compression::Xz),
"zstd" | "zst" => Ok(Compression::Zstd),
other => Err(format!(
"Unknown compression '{other}'. Valid: none, gzip, bzip2, xz, zstd"
)),
}
}
pub fn output_extension(&self) -> &'static str {
match self {
Compression::None => "",
Compression::Gzip => ".gz",
Compression::Bzip2 => ".bz2",
Compression::Xz => ".xz",
Compression::Zstd => ".zst",
Compression::Zip => "",
}
}
pub fn wrap_reader<'a>(
&self,
reader: Box<dyn Read + 'a>,
) -> std::io::Result<Box<dyn Read + 'a>> {
Ok(match self {
Compression::None => reader,
#[cfg(feature = "compression")]
Compression::Gzip => Box::new(flate2::read::GzDecoder::new(reader)),
#[cfg(feature = "compression")]
Compression::Bzip2 => Box::new(bzip2::read::BzDecoder::new(reader)),
#[cfg(feature = "compression")]
Compression::Xz => Box::new(xz2::read::XzDecoder::new(reader)),
#[cfg(feature = "compression")]
Compression::Zstd => Box::new(zstd::stream::read::Decoder::new(reader)?),
Compression::Zip => {
return Err(std::io::Error::new(
std::io::ErrorKind::Unsupported,
"zip input must be opened via open_input(), not wrap_reader() (needs a seekable File)",
))
}
#[cfg(not(feature = "compression"))]
_ => {
return Err(std::io::Error::new(
std::io::ErrorKind::Unsupported,
"compressed input requires the `compression` feature",
))
}
})
}
}
impl std::fmt::Display for Compression {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Compression::None => write!(f, "none"),
Compression::Gzip => write!(f, "gzip"),
Compression::Bzip2 => write!(f, "bzip2"),
Compression::Xz => write!(f, "xz"),
Compression::Zstd => write!(f, "zstd"),
Compression::Zip => write!(f, "zip"),
}
}
}
pub fn open_input_opt_progress(
path: &Path,
progress_fn: Option<Box<dyn Fn(u64)>>,
) -> anyhow::Result<Box<dyn Read>> {
let compression = Compression::from_path(path);
if compression == Compression::Zip {
#[cfg(feature = "archive")]
{
return crate::zip_input::open_zip_member(path, progress_fn);
}
#[cfg(not(feature = "archive"))]
{
anyhow::bail!("zip input requires the `archive` feature");
}
}
let file = File::open(path).with_context(|| format!("Failed to open input file: {path:?}"))?;
let reader: Box<dyn Read> = match progress_fn {
Some(cb) => Box::new(ProgressReader::new(file, cb)),
None => Box::new(file),
};
compression
.wrap_reader(reader)
.with_context(|| format!("Failed to initialize {compression} decompression for {path:?}"))
}
pub fn open_input(path: &Path) -> anyhow::Result<Box<dyn Read>> {
open_input_opt_progress(path, None)
}
pub fn open_input_with_progress(
path: &Path,
progress_fn: Box<dyn Fn(u64)>,
) -> anyhow::Result<Box<dyn Read>> {
open_input_opt_progress(path, Some(progress_fn))
}
pub fn input_progress_len(path: &Path) -> u64 {
#[cfg(feature = "archive")]
if Compression::from_path(path) == Compression::Zip {
if let Ok(size) = crate::zip_input::sql_member_compressed_size(path) {
return size;
}
}
std::fs::metadata(path).map(|m| m.len()).unwrap_or(0)
}
#[doc(hidden)]
pub fn estimate_uncompressed_size(file_size: u64, compression: Compression) -> u64 {
match compression {
Compression::None => file_size,
_ => file_size.saturating_mul(4),
}
}
pub struct Splitter {
input_file: PathBuf,
output_dir: PathBuf,
config: SplitterConfig,
}
impl Splitter {
pub fn new(input_file: PathBuf, output_dir: PathBuf) -> Self {
Self {
input_file,
output_dir,
config: SplitterConfig::default(),
}
}
pub fn with_dialect(mut self, dialect: SqlDialect) -> Self {
self.config.dialect = dialect;
self
}
pub fn with_dry_run(mut self, dry_run: bool) -> Self {
self.config.dry_run = dry_run;
self
}
pub fn with_table_filter(mut self, tables: Vec<String>) -> Self {
if !tables.is_empty() {
self.config.table_filter = Some(tables.into_iter().collect());
}
self
}
pub fn with_progress<F: Fn(u64) + 'static>(mut self, f: F) -> Self {
self.config.progress_fn = Some(Box::new(f));
self
}
pub fn with_content_filter(mut self, filter: ContentFilter) -> Self {
self.config.content_filter = filter;
self
}
pub fn with_output_compression(mut self, format: Compression) -> Self {
self.config.output_compression = format;
self
}
pub fn with_io_profile(mut self, profile: IoStrategy) -> Self {
self.config.io_strategy = profile;
self
}
#[doc(hidden)]
pub fn with_io_clock(mut self, clock: Arc<dyn Clock>) -> Self {
self.config.io_clock = Some(clock);
self
}
pub fn split(mut self) -> anyhow::Result<Stats> {
let file_size = std::fs::metadata(&self.input_file)
.with_context(|| format!("Failed to open input file: {:?}", self.input_file))?
.len();
let buffer_size = determine_buffer_size(file_size);
let dialect = self.config.dialect;
let content_filter = self.config.content_filter;
let reader: Box<dyn Read> =
open_input_opt_progress(&self.input_file, self.config.progress_fn.take())?;
let mut parser = Parser::with_dialect(reader, buffer_size, dialect);
let out_compression = self.config.output_compression;
let compressing = out_compression != Compression::None;
let cores = std::thread::available_parallelism()
.map(|n| n.get())
.unwrap_or(4);
let epoch_bytes = std::env::var("SQL_SPLITTER_EPOCH_BYTES")
.ok()
.and_then(|v| v.parse::<u64>().ok())
.filter(|&n| n > 0);
const DEFAULT_EPOCH_BYTES: u64 = 256 * 1024 * 1024;
const AUTO_MIN_FILE_SIZE: u64 = 64 * 1024 * 1024;
let input_size_estimate =
estimate_uncompressed_size(file_size, Compression::from_path(&self.input_file));
let adaptive = self.config.io_strategy == IoStrategy::Auto
&& !self.config.dry_run
&& (epoch_bytes.is_some() || input_size_estimate >= AUTO_MIN_FILE_SIZE);
let epoch_bytes = epoch_bytes
.unwrap_or_else(|| DEFAULT_EPOCH_BYTES.min((input_size_estimate / 4).max(1)));
let opening_kind = match self.config.io_strategy.pinned() {
Some(kind) => kind,
None if adaptive => probe_output_dir(&self.output_dir),
None => ProfileKind::Ssd,
};
let profile =
WriterProfile::for_kind(opening_kind, cores, compressing).with_env_overrides();
let initial_writers = if adaptive && !compressing {
env_writer_count().unwrap_or(1)
} else {
profile.writers
};
let fast_writers = if env_writer_count().is_some() {
initial_writers
} else {
WriterProfile::for_kind(ProfileKind::Ssd, cores, compressing).writers
};
let values = Arc::new(ProfileValues::new(&profile));
let mut writers = if self.config.dry_run {
None
} else {
let capacity = (profile.stage_cap / profile.flush_chunk.max(1)).clamp(4, 64);
Some(
ParallelWriters::new(
self.output_dir.clone(),
initial_writers,
capacity,
out_compression,
Arc::clone(&values),
)
.with_context(|| {
format!("Failed to create output directory: {:?}", self.output_dir)
})?,
)
};
let mut epoch_driver = adaptive.then(|| {
let ctrl = Controller::new(opening_kind, fast_writers);
let ctrl = if compressing {
ctrl.for_compressed_output()
} else {
ctrl
};
let clock: Arc<dyn Clock> = self
.config
.io_clock
.take()
.unwrap_or_else(|| Arc::new(RealClock::new()));
EpochDriver::new(
ctrl,
clock,
Arc::clone(&values),
epoch_bytes,
cores,
compressing,
)
});
let mut tables_seen: AHashSet<String> = AHashSet::new();
let mut stats = Stats {
statements_processed: 0,
tables_found: 0,
bytes_processed: 0,
table_names: Vec::new(),
writers_used: initial_writers,
io_transitions: Vec::new(),
};
let mut last_copy_table: Option<String> = None;
while let Some(stmt) = parser.read_statement()? {
let (stmt_type, mut table_name) =
Parser::<&[u8]>::parse_statement_with_dialect(&stmt, dialect);
if stmt_type == StatementType::Copy {
last_copy_table = Some(table_name.clone());
}
let is_copy_data = if stmt_type == StatementType::Unknown && last_copy_table.is_some() {
if stmt.ends_with(b"\\.\n") || stmt.ends_with(b"\\.\r\n") {
if let Some(copy_table) = last_copy_table.take() {
table_name = copy_table;
true
} else {
false
}
} else {
false
}
} else {
false
};
if !is_copy_data && (stmt_type == StatementType::Unknown || table_name.is_empty()) {
continue;
}
match content_filter {
ContentFilter::SchemaOnly => {
if !stmt_type.is_schema() {
continue;
}
}
ContentFilter::DataOnly => {
if !stmt_type.is_data() && !is_copy_data {
continue;
}
}
ContentFilter::All => {}
}
if let Some(ref filter) = self.config.table_filter {
if !filter.contains(&table_name) {
continue;
}
}
if !tables_seen.contains(&table_name) {
tables_seen.insert(table_name.clone());
stats.tables_found += 1;
stats.table_names.push(table_name.clone());
}
if let Some(w) = writers.as_mut() {
let suffix: &[u8] = if self.config.dialect == SqlDialect::Mssql {
let last = stmt
.iter()
.rev()
.find(|&&b| b != b'\n' && b != b'\r' && b != b' ' && b != b'\t');
if last != Some(&b';') {
b";"
} else {
b""
}
} else {
b""
};
w.write(&table_name, &stmt, suffix);
if w.errored() {
break;
}
}
stats.statements_processed += 1;
stats.bytes_processed += stmt.len() as u64;
if let (Some(driver), Some(w)) = (epoch_driver.as_mut(), writers.as_mut()) {
driver.on_bytes(w, &mut stats);
}
}
if let Some(w) = writers {
w.finish()
.with_context(|| format!("Failed writing output to {:?}", self.output_dir))?;
}
Ok(stats)
}
}