1use crate::parser::{determine_buffer_size, ContentFilter, Parser, SqlDialect, StatementType};
2use crate::progress::ProgressReader;
3use crate::writer::ParallelWriters;
4use ahash::AHashSet;
5use anyhow::Context;
6use serde::Serialize;
7use std::fs::File;
8use std::io::Read;
9use std::path::{Path, PathBuf};
10
11#[derive(Serialize)]
13pub struct Stats {
14 pub statements_processed: u64,
16 pub tables_found: usize,
18 pub bytes_processed: u64,
20 pub table_names: Vec<String>,
22}
23
24#[derive(Default)]
26pub struct SplitterConfig {
27 pub dialect: SqlDialect,
29 pub dry_run: bool,
31 pub table_filter: Option<AHashSet<String>>,
33 pub progress_fn: Option<Box<dyn Fn(u64)>>,
35 pub content_filter: ContentFilter,
37 pub output_compression: Compression,
39}
40
41#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
43pub enum Compression {
44 #[default]
45 None,
46 Gzip,
47 Bzip2,
48 Xz,
49 Zstd,
50}
51
52impl Compression {
53 pub fn from_path(path: &Path) -> Self {
55 let ext = path
56 .extension()
57 .and_then(|e| e.to_str())
58 .map(|e| e.to_lowercase());
59
60 match ext.as_deref() {
61 Some("gz" | "gzip") => Compression::Gzip,
62 Some("bz2" | "bzip2") => Compression::Bzip2,
63 Some("xz" | "lzma") => Compression::Xz,
64 Some("zst" | "zstd") => Compression::Zstd,
65 _ => Compression::None,
66 }
67 }
68
69 pub fn parse_output(s: &str) -> Result<Self, String> {
71 match s.to_lowercase().as_str() {
72 "none" | "" => Ok(Compression::None),
73 "gzip" | "gz" => Ok(Compression::Gzip),
74 "bzip2" | "bz2" => Ok(Compression::Bzip2),
75 "xz" | "lzma" => Ok(Compression::Xz),
76 "zstd" | "zst" => Ok(Compression::Zstd),
77 other => Err(format!(
78 "Unknown compression '{other}'. Valid: none, gzip, bzip2, xz, zstd"
79 )),
80 }
81 }
82
83 pub fn output_extension(&self) -> &'static str {
85 match self {
86 Compression::None => "",
87 Compression::Gzip => ".gz",
88 Compression::Bzip2 => ".bz2",
89 Compression::Xz => ".xz",
90 Compression::Zstd => ".zst",
91 }
92 }
93
94 pub fn wrap_reader<'a>(
96 &self,
97 reader: Box<dyn Read + 'a>,
98 ) -> std::io::Result<Box<dyn Read + 'a>> {
99 Ok(match self {
100 Compression::None => reader,
101 #[cfg(feature = "compression")]
102 Compression::Gzip => Box::new(flate2::read::GzDecoder::new(reader)),
103 #[cfg(feature = "compression")]
104 Compression::Bzip2 => Box::new(bzip2::read::BzDecoder::new(reader)),
105 #[cfg(feature = "compression")]
106 Compression::Xz => Box::new(xz2::read::XzDecoder::new(reader)),
107 #[cfg(feature = "compression")]
108 Compression::Zstd => Box::new(zstd::stream::read::Decoder::new(reader)?),
109 #[cfg(not(feature = "compression"))]
110 _ => {
111 return Err(std::io::Error::new(
112 std::io::ErrorKind::Unsupported,
113 "compressed input requires the `compression` feature",
114 ))
115 }
116 })
117 }
118}
119
120impl std::fmt::Display for Compression {
121 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
122 match self {
123 Compression::None => write!(f, "none"),
124 Compression::Gzip => write!(f, "gzip"),
125 Compression::Bzip2 => write!(f, "bzip2"),
126 Compression::Xz => write!(f, "xz"),
127 Compression::Zstd => write!(f, "zstd"),
128 }
129 }
130}
131
132pub struct Splitter {
133 input_file: PathBuf,
134 output_dir: PathBuf,
135 config: SplitterConfig,
136}
137
138impl Splitter {
139 pub fn new(input_file: PathBuf, output_dir: PathBuf) -> Self {
140 Self {
141 input_file,
142 output_dir,
143 config: SplitterConfig::default(),
144 }
145 }
146
147 pub fn with_dialect(mut self, dialect: SqlDialect) -> Self {
148 self.config.dialect = dialect;
149 self
150 }
151
152 pub fn with_dry_run(mut self, dry_run: bool) -> Self {
153 self.config.dry_run = dry_run;
154 self
155 }
156
157 pub fn with_table_filter(mut self, tables: Vec<String>) -> Self {
158 if !tables.is_empty() {
159 self.config.table_filter = Some(tables.into_iter().collect());
160 }
161 self
162 }
163
164 pub fn with_progress<F: Fn(u64) + 'static>(mut self, f: F) -> Self {
165 self.config.progress_fn = Some(Box::new(f));
166 self
167 }
168
169 pub fn with_content_filter(mut self, filter: ContentFilter) -> Self {
170 self.config.content_filter = filter;
171 self
172 }
173
174 pub fn with_output_compression(mut self, format: Compression) -> Self {
175 self.config.output_compression = format;
176 self
177 }
178
179 pub fn split(mut self) -> anyhow::Result<Stats> {
180 let file = File::open(&self.input_file)
181 .with_context(|| format!("Failed to open input file: {:?}", self.input_file))?;
182 let file_size = file.metadata()?.len();
183 let buffer_size = determine_buffer_size(file_size);
184 let dialect = self.config.dialect;
185 let content_filter = self.config.content_filter;
186
187 let compression = Compression::from_path(&self.input_file);
189
190 let reader: Box<dyn Read> = if let Some(cb) = self.config.progress_fn.take() {
191 let progress_reader = ProgressReader::new(file, cb);
192 compression
193 .wrap_reader(Box::new(progress_reader))
194 .with_context(|| {
195 format!(
196 "Failed to initialize {} decompression for {:?}",
197 compression, self.input_file
198 )
199 })?
200 } else {
201 compression.wrap_reader(Box::new(file)).with_context(|| {
202 format!(
203 "Failed to initialize {} decompression for {:?}",
204 compression, self.input_file
205 )
206 })?
207 };
208
209 let mut parser = Parser::with_dialect(reader, buffer_size, dialect);
210
211 let out_compression = self.config.output_compression;
215 let mut writers = if self.config.dry_run {
216 None
217 } else {
218 let cores = std::thread::available_parallelism()
219 .map(|n| n.get())
220 .unwrap_or(4);
221 let num_writers = std::env::var("SQL_SPLITTER_WRITERS")
222 .ok()
223 .and_then(|v| v.parse::<usize>().ok())
224 .filter(|&n| n >= 1)
225 .unwrap_or_else(|| {
226 if out_compression == Compression::None {
227 cores.min(4)
228 } else {
229 cores
230 }
231 });
232 Some(
233 ParallelWriters::new(self.output_dir.clone(), num_writers, 64, out_compression)
234 .with_context(|| {
235 format!("Failed to create output directory: {:?}", self.output_dir)
236 })?,
237 )
238 };
239
240 let mut tables_seen: AHashSet<String> = AHashSet::new();
241 let mut stats = Stats {
242 statements_processed: 0,
243 tables_found: 0,
244 bytes_processed: 0,
245 table_names: Vec::new(),
246 };
247
248 let mut last_copy_table: Option<String> = None;
250
251 while let Some(stmt) = parser.read_statement()? {
252 let (stmt_type, mut table_name) =
253 Parser::<&[u8]>::parse_statement_with_dialect(&stmt, dialect);
254
255 if stmt_type == StatementType::Copy {
257 last_copy_table = Some(table_name.clone());
258 }
259
260 let is_copy_data = if stmt_type == StatementType::Unknown && last_copy_table.is_some() {
262 if stmt.ends_with(b"\\.\n") || stmt.ends_with(b"\\.\r\n") {
264 if let Some(copy_table) = last_copy_table.take() {
266 table_name = copy_table;
267 true
268 } else {
269 false
270 }
271 } else {
272 false
273 }
274 } else {
275 false
276 };
277
278 if !is_copy_data && (stmt_type == StatementType::Unknown || table_name.is_empty()) {
279 continue;
280 }
281
282 match content_filter {
284 ContentFilter::SchemaOnly => {
285 if !stmt_type.is_schema() {
286 continue;
287 }
288 }
289 ContentFilter::DataOnly => {
290 if !stmt_type.is_data() && !is_copy_data {
292 continue;
293 }
294 }
295 ContentFilter::All => {}
296 }
297
298 if let Some(ref filter) = self.config.table_filter {
299 if !filter.contains(&table_name) {
300 continue;
301 }
302 }
303
304 if !tables_seen.contains(&table_name) {
305 tables_seen.insert(table_name.clone());
306 stats.tables_found += 1;
307 stats.table_names.push(table_name.clone());
308 }
309
310 if let Some(w) = writers.as_mut() {
311 let suffix: &[u8] = if self.config.dialect == SqlDialect::Mssql {
315 let last = stmt
316 .iter()
317 .rev()
318 .find(|&&b| b != b'\n' && b != b'\r' && b != b' ' && b != b'\t');
319 if last != Some(&b';') {
320 b";"
321 } else {
322 b""
323 }
324 } else {
325 b""
326 };
327 w.write(&table_name, &stmt, suffix);
328
329 if w.errored() {
331 break;
332 }
333 }
334
335 stats.statements_processed += 1;
336 stats.bytes_processed += stmt.len() as u64;
337 }
338
339 if let Some(w) = writers {
340 w.finish()
341 .with_context(|| format!("Failed writing output to {:?}", self.output_dir))?;
342 }
343
344 Ok(stats)
345 }
346}