Skip to main content

sql_splitter/splitter/
mod.rs

1mod epoch;
2
3#[allow(unused_imports)] // Public API re-export used by integration tests
4pub 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/// Statistics from a split operation.
22#[derive(Serialize)]
23pub struct Stats {
24    /// Total statements processed.
25    pub statements_processed: u64,
26    /// Number of unique tables found.
27    pub tables_found: usize,
28    /// Total bytes processed from input.
29    pub bytes_processed: u64,
30    /// Names of all tables found.
31    pub table_names: Vec<String>,
32    /// Number of writer threads at the end of the run (observability for the
33    /// adaptive controller's deferred writer spawn; not part of JSON output).
34    #[serde(skip)]
35    pub writers_used: usize,
36    /// Adaptive I/O transition log lines emitted during the run, in order
37    /// (observability for tests and debugging; not part of JSON output).
38    #[serde(skip)]
39    pub io_transitions: Vec<String>,
40}
41
42/// Configuration for the splitter.
43#[derive(Default)]
44pub struct SplitterConfig {
45    /// SQL dialect for parsing.
46    pub dialect: SqlDialect,
47    /// If true, parse without writing output files.
48    pub dry_run: bool,
49    /// If set, only process tables in this set.
50    pub table_filter: Option<AHashSet<String>>,
51    /// Optional callback for progress reporting.
52    pub progress_fn: Option<Box<dyn Fn(u64)>>,
53    /// Filter for which statement types to include.
54    pub content_filter: ContentFilter,
55    /// Per-table output compression (default `None` → plain `.sql`).
56    pub output_compression: Compression,
57    /// I/O strategy for output writing (default `Auto`).
58    pub io_strategy: IoStrategy,
59    /// Clock driving epoch measurements (None → wall clock). Test seam: a
60    /// stepping mock clock makes the adaptive controller fully deterministic.
61    pub io_clock: Option<Arc<dyn Clock>>,
62}
63
64/// Compression format detected from file extension
65#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
66pub enum Compression {
67    #[default]
68    None,
69    Gzip,
70    Bzip2,
71    Xz,
72    Zstd,
73    /// A zip *archive* (not a stream compressor) containing exactly one
74    /// `.sql` member. Detected here so callers can branch on it, but it
75    /// never goes through [`Compression::wrap_reader`] — see [`open_input`]
76    /// and `crate::zip_input`.
77    Zip,
78}
79
80impl Compression {
81    /// Detect compression format from file extension
82    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    /// Parse an output-compression format name (for the `--compress` flag).
99    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    /// File-name extension for compressed output (empty for `None`).
113    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            // Never selected as an output compression: `parse_output` has no
121            // "zip" case, so per-table output stays rejected as documented.
122            Compression::Zip => "",
123        }
124    }
125
126    /// Wrap a reader with the appropriate decompressor
127    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            // Use the multi-member/multi-stream decoders: dumps are commonly
134            // stored as concatenated members (e.g. `cat a.gz b.gz`, or tools
135            // that flush a new stream per table). The single-member decoders
136            // stop at the first member and silently truncate the rest.
137            #[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            // Zip is an archive, not a stream decoder: it needs a seekable
146            // `File` to parse the central directory, so it can never be
147            // wrapped here. Callers must go through `open_input` instead.
148            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
178/// Open `path` as a streaming byte source, transparently handling any
179/// supported compression format — including zip archives, which need a
180/// different opening strategy than the stream decoders (see
181/// `crate::zip_input`). This is the entry point call sites should use
182/// instead of manually pairing `File::open` with [`Compression::wrap_reader`].
183///
184/// When `progress_fn` is `Some`, it receives cumulative bytes read from disk
185/// (raw/compressed bytes, for compressed/zip inputs) as they're read; size a
186/// progress bar over this with [`input_progress_len`]. The zero- and
187/// always-progress conveniences [`open_input`] / [`open_input_with_progress`]
188/// are thin wrappers over this.
189pub 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
216/// Convenience wrapper: [`open_input_opt_progress`] without progress reporting.
217pub fn open_input(path: &Path) -> anyhow::Result<Box<dyn Read>> {
218    open_input_opt_progress(path, None)
219}
220
221/// Convenience wrapper: [`open_input_opt_progress`] with progress reporting.
222pub 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
229/// Total number of bytes the progress callback installed by
230/// [`open_input_with_progress`] can report for `path` — i.e. the correct
231/// length for a progress bar over this input.
232///
233/// For most inputs this is simply the on-disk file size (progress counts
234/// raw/compressed bytes read from disk). Zip archives are the exception:
235/// only the sole `.sql` member's compressed bytes are ever streamed, so the
236/// total is that member's compressed size — sizing a bar with the archive's
237/// file size would leave it stuck below 100% by the archive overhead and any
238/// sibling members. Falls back to the file size when the member can't be
239/// located (the subsequent open reports the real error).
240pub 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/// Estimated decompressed size of an input file, for adaptive-I/O gating and
251/// epoch sizing. Exact for uncompressed input; for compressed/zip input a
252/// deliberately conservative 4× multiplier is applied (SQL text typically
253/// compresses 4–10×) so a small-but-dense archive doesn't silently pin the
254/// SSD profile for hundreds of MB of output.
255#[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    /// Choose the I/O strategy for output writing (`--io-strategy`). Explicit
311    /// profiles pin the writer configuration; `Auto` (the default) probes the
312    /// output device and adapts at runtime.
313    pub fn with_io_profile(mut self, profile: IoStrategy) -> Self {
314        self.config.io_strategy = profile;
315        self
316    }
317
318    /// Override the clock used for adaptive-I/O epoch measurements.
319    /// Deterministic-test seam; production code always uses the default
320    /// wall clock.
321    #[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        // Open the input, transparently handling any supported compression
336        // format (including zip archives, which need a two-phase open).
337        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        // Parallel, pipelined writers (skipped for dry runs), configured by
343        // the selected I/O strategy (see docs/features/ADAPTIVE_IO_PROFILES.md).
344        // Precedence: SQL_SPLITTER_WRITERS / SQL_SPLITTER_WRITE_BUF env vars >
345        // explicit --io-strategy > auto.
346        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        // Epoch length for the adaptive controller: byte-based so controller
353        // decisions are a pure function of (bytes, measured durations). The
354        // hidden env override is the deterministic-test seam.
355        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        // Adaptation only pays off at scale: below ~4 default epochs' worth of
360        // input the run is over before the controller could act, so `auto`
361        // just pins FAST (today's defaults) and skips the 8MB probe. An
362        // explicit epoch override (tests) engages the full machinery.
363        // Compressed inputs are gated (and epoch-sized) on an estimate of the
364        // *decompressed* volume: run length is governed by how much SQL comes
365        // out of the archive, not by its on-disk size, and `bytes_processed`
366        // (which epoch boundaries compare against) counts decompressed bytes.
367        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        // Aim for at least 4 epochs per file so short runs still measure.
375        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            // The fsync probe picks auto's *opening* state only; the feedback
381            // controller owns the truth once the pipeline runs.
382            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        // In auto mode, open at W=1 and let the controller spawn up to FAST's
389        // writer count once the device proves fast: on NVMe the W=1 opening
390        // costs ~15% for one epoch; on slow media it avoids ever thrashing.
391        // SQL_SPLITTER_WRITERS pins the count and disables growth entirely.
392        //
393        // Compressed output can never deliver that proof: throughput is
394        // measured in *compressed* bytes beneath the encoders (a lone gzip
395        // writer never shows 150 MB/s compressed) and a CPU-bound encoder
396        // stalls the producer exactly like a slow device. Such runs open
397        // with the probe-chosen profile's full writer count and freeze the
398        // controller (see `Controller::for_compressed_output`).
399        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            // Channel depth scales with chunk size so in-flight bytes stay in
415            // the same ballpark as the profile's stage cap: FAST keeps the
416            // historical 64 × 256KB; the slow profiles get fewer, bigger slots.
417            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        // The adaptive feedback loop, evaluated at every epoch boundary
433        // (measurement + controller decision + writer retuning) — see
434        // `epoch::EpochDriver`.
435        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        // Track the last COPY table for PostgreSQL COPY data blocks
468        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            // Track COPY statements for data association
475            if stmt_type == StatementType::Copy {
476                last_copy_table = Some(table_name.clone());
477            }
478
479            // Handle PostgreSQL COPY data blocks - associate with last COPY table
480            let is_copy_data = if stmt_type == StatementType::Unknown && last_copy_table.is_some() {
481                // Check if this looks like COPY data (ends with \.\n)
482                if stmt.ends_with(b"\\.\n") || stmt.ends_with(b"\\.\r\n") {
483                    // Safe: we just checked is_some() above
484                    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            // Apply content filter (schema-only or data-only)
502            match content_filter {
503                ContentFilter::SchemaOnly => {
504                    if !stmt_type.is_schema() {
505                        continue;
506                    }
507                }
508                ContentFilter::DataOnly => {
509                    // For data-only, include INSERT, COPY, and COPY data blocks
510                    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                // For MSSQL, add a semicolon when the statement doesn't already
531                // end with one (GO is the batch separator, but we need `;` for
532                // re-parsing). Other dialects add no suffix.
533                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                // A writer thread hit an I/O error; stop parsing and surface it.
549                if w.errored() {
550                    break;
551                }
552            }
553
554            stats.statements_processed += 1;
555            stats.bytes_processed += stmt.len() as u64;
556
557            // Adaptive-I/O epoch boundary: byte-based (see epoch module
558            // docs), so the controller's decisions are a pure function of
559            // measured data, not wall-clock scheduling. `writers` is always
560            // `Some` when the driver is `Some` (adaptive requires
561            // `!dry_run`, see above).
562            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}