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            #[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            // Zip is an archive, not a stream decoder: it needs a seekable
142            // `File` to parse the central directory, so it can never be
143            // wrapped here. Callers must go through `open_input` instead.
144            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
174/// Open `path` as a streaming byte source, transparently handling any
175/// supported compression format — including zip archives, which need a
176/// different opening strategy than the stream decoders (see
177/// `crate::zip_input`). This is the entry point call sites should use
178/// instead of manually pairing `File::open` with [`Compression::wrap_reader`].
179///
180/// When `progress_fn` is `Some`, it receives cumulative bytes read from disk
181/// (raw/compressed bytes, for compressed/zip inputs) as they're read; size a
182/// progress bar over this with [`input_progress_len`]. The zero- and
183/// always-progress conveniences [`open_input`] / [`open_input_with_progress`]
184/// are thin wrappers over this.
185pub 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
212/// Convenience wrapper: [`open_input_opt_progress`] without progress reporting.
213pub fn open_input(path: &Path) -> anyhow::Result<Box<dyn Read>> {
214    open_input_opt_progress(path, None)
215}
216
217/// Convenience wrapper: [`open_input_opt_progress`] with progress reporting.
218pub 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
225/// Total number of bytes the progress callback installed by
226/// [`open_input_with_progress`] can report for `path` — i.e. the correct
227/// length for a progress bar over this input.
228///
229/// For most inputs this is simply the on-disk file size (progress counts
230/// raw/compressed bytes read from disk). Zip archives are the exception:
231/// only the sole `.sql` member's compressed bytes are ever streamed, so the
232/// total is that member's compressed size — sizing a bar with the archive's
233/// file size would leave it stuck below 100% by the archive overhead and any
234/// sibling members. Falls back to the file size when the member can't be
235/// located (the subsequent open reports the real error).
236pub 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/// Estimated decompressed size of an input file, for adaptive-I/O gating and
247/// epoch sizing. Exact for uncompressed input; for compressed/zip input a
248/// deliberately conservative 4× multiplier is applied (SQL text typically
249/// compresses 4–10×) so a small-but-dense archive doesn't silently pin the
250/// SSD profile for hundreds of MB of output.
251#[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    /// Choose the I/O strategy for output writing (`--io-strategy`). Explicit
307    /// profiles pin the writer configuration; `Auto` (the default) probes the
308    /// output device and adapts at runtime.
309    pub fn with_io_profile(mut self, profile: IoStrategy) -> Self {
310        self.config.io_strategy = profile;
311        self
312    }
313
314    /// Override the clock used for adaptive-I/O epoch measurements.
315    /// Deterministic-test seam; production code always uses the default
316    /// wall clock.
317    #[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        // Open the input, transparently handling any supported compression
332        // format (including zip archives, which need a two-phase open).
333        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        // Parallel, pipelined writers (skipped for dry runs), configured by
339        // the selected I/O strategy (see docs/features/ADAPTIVE_IO_PROFILES.md).
340        // Precedence: SQL_SPLITTER_WRITERS / SQL_SPLITTER_WRITE_BUF env vars >
341        // explicit --io-strategy > auto.
342        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        // Epoch length for the adaptive controller: byte-based so controller
349        // decisions are a pure function of (bytes, measured durations). The
350        // hidden env override is the deterministic-test seam.
351        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        // Adaptation only pays off at scale: below ~4 default epochs' worth of
356        // input the run is over before the controller could act, so `auto`
357        // just pins FAST (today's defaults) and skips the 8MB probe. An
358        // explicit epoch override (tests) engages the full machinery.
359        // Compressed inputs are gated (and epoch-sized) on an estimate of the
360        // *decompressed* volume: run length is governed by how much SQL comes
361        // out of the archive, not by its on-disk size, and `bytes_processed`
362        // (which epoch boundaries compare against) counts decompressed bytes.
363        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        // Aim for at least 4 epochs per file so short runs still measure.
371        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            // The fsync probe picks auto's *opening* state only; the feedback
377            // controller owns the truth once the pipeline runs.
378            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        // In auto mode, open at W=1 and let the controller spawn up to FAST's
385        // writer count once the device proves fast: on NVMe the W=1 opening
386        // costs ~15% for one epoch; on slow media it avoids ever thrashing.
387        // SQL_SPLITTER_WRITERS pins the count and disables growth entirely.
388        //
389        // Compressed output can never deliver that proof: throughput is
390        // measured in *compressed* bytes beneath the encoders (a lone gzip
391        // writer never shows 150 MB/s compressed) and a CPU-bound encoder
392        // stalls the producer exactly like a slow device. Such runs open
393        // with the probe-chosen profile's full writer count and freeze the
394        // controller (see `Controller::for_compressed_output`).
395        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            // Channel depth scales with chunk size so in-flight bytes stay in
411            // the same ballpark as the profile's stage cap: FAST keeps the
412            // historical 64 × 256KB; the slow profiles get fewer, bigger slots.
413            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        // The adaptive feedback loop, evaluated at every epoch boundary
429        // (measurement + controller decision + writer retuning) — see
430        // `epoch::EpochDriver`.
431        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        // Track the last COPY table for PostgreSQL COPY data blocks
464        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            // Track COPY statements for data association
471            if stmt_type == StatementType::Copy {
472                last_copy_table = Some(table_name.clone());
473            }
474
475            // Handle PostgreSQL COPY data blocks - associate with last COPY table
476            let is_copy_data = if stmt_type == StatementType::Unknown && last_copy_table.is_some() {
477                // Check if this looks like COPY data (ends with \.\n)
478                if stmt.ends_with(b"\\.\n") || stmt.ends_with(b"\\.\r\n") {
479                    // Safe: we just checked is_some() above
480                    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            // Apply content filter (schema-only or data-only)
498            match content_filter {
499                ContentFilter::SchemaOnly => {
500                    if !stmt_type.is_schema() {
501                        continue;
502                    }
503                }
504                ContentFilter::DataOnly => {
505                    // For data-only, include INSERT, COPY, and COPY data blocks
506                    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                // For MSSQL, add a semicolon when the statement doesn't already
527                // end with one (GO is the batch separator, but we need `;` for
528                // re-parsing). Other dialects add no suffix.
529                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                // A writer thread hit an I/O error; stop parsing and surface it.
545                if w.errored() {
546                    break;
547                }
548            }
549
550            stats.statements_processed += 1;
551            stats.bytes_processed += stmt.len() as u64;
552
553            // Adaptive-I/O epoch boundary: byte-based (see epoch module
554            // docs), so the controller's decisions are a pure function of
555            // measured data, not wall-clock scheduling. `writers` is always
556            // `Some` when the driver is `Some` (adaptive requires
557            // `!dry_run`, see above).
558            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}