Skip to main content

sql_splitter/writer/
mod.rs

1//! Buffered file writers for splitting SQL statements into per-table files.
2
3use ahash::AHashMap;
4use std::collections::hash_map::Entry;
5use std::fs::{self, File};
6use std::io::{BufWriter, Write};
7use std::path::{Path, PathBuf};
8use std::sync::atomic::{AtomicBool, Ordering};
9use std::sync::mpsc::{sync_channel, Receiver, SyncSender};
10use std::sync::Arc;
11use std::thread::JoinHandle;
12
13/// Size of the BufWriter buffer per table file. Sits at the top of the
14/// sequential-write plateau (64KB–256KB); overridable via
15/// `SQL_SPLITTER_WRITE_BUF` (bytes) for tuning.
16pub const WRITER_BUFFER_SIZE: usize = 256 * 1024;
17
18/// Resolve the per-file write buffer size, honoring the env override.
19pub fn write_buffer_size() -> usize {
20    std::env::var("SQL_SPLITTER_WRITE_BUF")
21        .ok()
22        .and_then(|v| v.parse::<usize>().ok())
23        .filter(|&n| n >= 4096)
24        .unwrap_or(WRITER_BUFFER_SIZE)
25}
26
27/// Buffered writer for a single table's SQL file.
28pub struct TableWriter {
29    writer: BufWriter<File>,
30}
31
32impl TableWriter {
33    /// Create a new table writer for the given file path.
34    pub fn new(filename: &Path) -> std::io::Result<Self> {
35        let file = File::create(filename)?;
36        let writer = BufWriter::with_capacity(write_buffer_size(), file);
37        Ok(Self { writer })
38    }
39
40    /// Write a SQL statement followed by a newline. The `BufWriter` flushes
41    /// itself only when its buffer fills (and on close), so writes coalesce
42    /// into large syscalls instead of one per ~100 statements.
43    pub fn write_statement(&mut self, stmt: &[u8]) -> std::io::Result<()> {
44        self.writer.write_all(stmt)?;
45        self.writer.write_all(b"\n")
46    }
47
48    /// Write a SQL statement with a custom suffix and newline.
49    pub fn write_statement_with_suffix(
50        &mut self,
51        stmt: &[u8],
52        suffix: &[u8],
53    ) -> std::io::Result<()> {
54        self.writer.write_all(stmt)?;
55        self.writer.write_all(suffix)?;
56        self.writer.write_all(b"\n")
57    }
58
59    /// Flush the internal buffer to the OS.
60    pub fn flush(&mut self) -> std::io::Result<()> {
61        self.writer.flush()
62    }
63}
64
65/// Pool of per-table writers, creating files on demand.
66pub struct WriterPool {
67    output_dir: PathBuf,
68    writers: AHashMap<String, TableWriter>,
69}
70
71impl WriterPool {
72    /// Create a new writer pool targeting the given output directory.
73    pub fn new(output_dir: PathBuf) -> Self {
74        Self {
75            output_dir,
76            writers: AHashMap::new(),
77        }
78    }
79
80    /// Create the output directory if it does not exist.
81    pub fn ensure_output_dir(&self) -> std::io::Result<()> {
82        fs::create_dir_all(&self.output_dir)
83    }
84
85    /// Get or create a writer for the given table name.
86    pub fn get_writer(&mut self, table_name: &str) -> std::io::Result<&mut TableWriter> {
87        use std::collections::hash_map::Entry;
88
89        // Use entry API to avoid separate contains_key + get_mut (eliminates unwrap)
90        match self.writers.entry(table_name.to_string()) {
91            Entry::Occupied(entry) => Ok(entry.into_mut()),
92            Entry::Vacant(entry) => {
93                let filename = self.output_dir.join(format!("{}.sql", table_name));
94                let writer = TableWriter::new(&filename)?;
95                Ok(entry.insert(writer))
96            }
97        }
98    }
99
100    /// Write a statement to the file for the given table.
101    pub fn write_statement(&mut self, table_name: &str, stmt: &[u8]) -> std::io::Result<()> {
102        let writer = self.get_writer(table_name)?;
103        writer.write_statement(stmt)
104    }
105
106    /// Write a statement with suffix to the file for the given table.
107    pub fn write_statement_with_suffix(
108        &mut self,
109        table_name: &str,
110        stmt: &[u8],
111        suffix: &[u8],
112    ) -> std::io::Result<()> {
113        let writer = self.get_writer(table_name)?;
114        writer.write_statement_with_suffix(stmt, suffix)
115    }
116
117    /// Flush and close all writers.
118    pub fn close_all(&mut self) -> std::io::Result<()> {
119        for writer in self.writers.values_mut() {
120            writer.flush()?;
121        }
122        Ok(())
123    }
124}
125
126use crate::splitter::Compression;
127
128/// Threshold at which a table's staging buffer is shipped to its writer thread.
129const STAGE_FLUSH: usize = 256 * 1024;
130
131/// Cap on the *total* bytes staged across all tables. Individual buffers ship
132/// at [`STAGE_FLUSH`], but a dump with thousands of tables could otherwise
133/// stage up to `tables × STAGE_FLUSH`; crossing this cap flushes every staged
134/// buffer so producer-side memory stays bounded regardless of table count.
135const STAGE_TOTAL_CAP: usize = 32 * 1024 * 1024;
136
137/// A batched write job: pre-assembled bytes for one table.
138struct Chunk {
139    table: Arc<str>,
140    data: Vec<u8>,
141}
142
143/// A per-table output stream: a plain file, or a streaming compressor over one.
144/// Compressing per file keeps every output independent, so the writer pool
145/// still runs fully in parallel — and the compression work parallelizes with it.
146enum TableSink {
147    Raw(File),
148    #[cfg(feature = "compression")]
149    Gzip(flate2::write::GzEncoder<File>),
150    #[cfg(feature = "compression")]
151    Bzip2(bzip2::write::BzEncoder<File>),
152    #[cfg(feature = "compression")]
153    Xz(xz2::write::XzEncoder<File>),
154    #[cfg(feature = "compression")]
155    Zstd(zstd::stream::write::Encoder<'static, File>),
156}
157
158impl TableSink {
159    /// Create the `<table>.sql[.ext]` file and wrap it in the chosen encoder.
160    fn create(dir: &Path, table: &str, format: Compression) -> std::io::Result<Self> {
161        let path = dir.join(format!("{}.sql{}", table, format.output_extension()));
162        let file = File::create(&path)?;
163        Ok(match format {
164            Compression::None => TableSink::Raw(file),
165            #[cfg(feature = "compression")]
166            Compression::Gzip => TableSink::Gzip(flate2::write::GzEncoder::new(
167                file,
168                flate2::Compression::default(),
169            )),
170            #[cfg(feature = "compression")]
171            Compression::Bzip2 => TableSink::Bzip2(bzip2::write::BzEncoder::new(
172                file,
173                bzip2::Compression::default(),
174            )),
175            #[cfg(feature = "compression")]
176            Compression::Xz => TableSink::Xz(xz2::write::XzEncoder::new(file, 6)),
177            #[cfg(feature = "compression")]
178            Compression::Zstd => TableSink::Zstd(zstd::stream::write::Encoder::new(file, 3)?),
179            #[cfg(not(feature = "compression"))]
180            _ => {
181                return Err(std::io::Error::new(
182                    std::io::ErrorKind::Unsupported,
183                    "compressed output requires the `compression` feature",
184                ))
185            }
186        })
187    }
188
189    fn write_all(&mut self, data: &[u8]) -> std::io::Result<()> {
190        match self {
191            TableSink::Raw(f) => f.write_all(data),
192            #[cfg(feature = "compression")]
193            TableSink::Gzip(e) => e.write_all(data),
194            #[cfg(feature = "compression")]
195            TableSink::Bzip2(e) => e.write_all(data),
196            #[cfg(feature = "compression")]
197            TableSink::Xz(e) => e.write_all(data),
198            #[cfg(feature = "compression")]
199            TableSink::Zstd(e) => e.write_all(data),
200        }
201    }
202
203    /// Finalize the stream, flushing the compressor's epilogue (required for a
204    /// valid archive — especially zstd, which writes a frame footer).
205    fn finish(self) -> std::io::Result<()> {
206        match self {
207            TableSink::Raw(mut f) => f.flush(),
208            #[cfg(feature = "compression")]
209            TableSink::Gzip(e) => e.finish().map(|_| ()),
210            #[cfg(feature = "compression")]
211            TableSink::Bzip2(e) => e.finish().map(|_| ()),
212            #[cfg(feature = "compression")]
213            TableSink::Xz(e) => e.finish().map(|_| ()),
214            #[cfg(feature = "compression")]
215            TableSink::Zstd(e) => e.finish().map(|_| ()),
216        }
217    }
218}
219
220/// Parallel, pipelined writer pool.
221///
222/// The producer (parser thread) stages per-table bytes and ships ~256KB chunks
223/// over bounded channels to `N` writer threads, each owning a disjoint shard of
224/// tables (sharded by name hash). This overlaps parsing with writing (a
225/// pipeline / double-buffer) and keeps several writes in flight so a single
226/// synchronous thread doesn't bottleneck a fast SSD (queue depth > 1). Batching
227/// into large chunks keeps per-statement channel overhead negligible.
228///
229/// Output is byte-identical to the single-threaded [`WriterPool`]: each table's
230/// file is written by exactly one thread, in input order.
231pub struct ParallelWriters {
232    senders: Vec<SyncSender<Chunk>>,
233    handles: Vec<JoinHandle<std::io::Result<()>>>,
234    error_flag: Arc<AtomicBool>,
235    intern: AHashMap<String, Arc<str>>,
236    stage: AHashMap<Arc<str>, Vec<u8>>,
237    /// Total bytes currently staged across all tables (see [`STAGE_TOTAL_CAP`]).
238    staged_bytes: usize,
239}
240
241impl ParallelWriters {
242    /// Spawn `num_writers` writer threads targeting `output_dir`, compressing
243    /// each per-table file with `format`. `capacity` is the per-shard channel
244    /// depth (chunks in flight).
245    pub fn new(
246        output_dir: PathBuf,
247        num_writers: usize,
248        capacity: usize,
249        format: Compression,
250    ) -> std::io::Result<Self> {
251        fs::create_dir_all(&output_dir)?;
252        let n = num_writers.max(1);
253        let error_flag = Arc::new(AtomicBool::new(false));
254        let mut senders = Vec::with_capacity(n);
255        let mut handles = Vec::with_capacity(n);
256        for _ in 0..n {
257            let (tx, rx) = sync_channel::<Chunk>(capacity.max(1));
258            senders.push(tx);
259            let dir = output_dir.clone();
260            let ef = Arc::clone(&error_flag);
261            handles.push(std::thread::spawn(move || writer_loop(rx, dir, ef, format)));
262        }
263        Ok(Self {
264            senders,
265            handles,
266            error_flag,
267            intern: AHashMap::new(),
268            stage: AHashMap::new(),
269            staged_bytes: 0,
270        })
271    }
272
273    /// True once any writer thread has hit an I/O error, so the producer can
274    /// stop early; the actual error surfaces from [`finish`](Self::finish).
275    #[inline]
276    pub fn errored(&self) -> bool {
277        self.error_flag.load(Ordering::Relaxed)
278    }
279
280    /// Stage a statement for its table, appending `suffix` (e.g. `b";"`) and a
281    /// newline, shipping a chunk once the table's buffer crosses the threshold.
282    pub fn write(&mut self, table_name: &str, stmt: &[u8], suffix: &[u8]) {
283        let arc = match self.intern.get(table_name) {
284            Some(a) => Arc::clone(a),
285            None => {
286                let a: Arc<str> = Arc::from(table_name);
287                self.intern.insert(table_name.to_string(), Arc::clone(&a));
288                a
289            }
290        };
291        let buf = self.stage.entry(Arc::clone(&arc)).or_default();
292        buf.extend_from_slice(stmt);
293        buf.extend_from_slice(suffix);
294        buf.push(b'\n');
295        self.staged_bytes += stmt.len() + suffix.len() + 1;
296        if buf.len() >= STAGE_FLUSH {
297            let data = std::mem::take(buf);
298            self.staged_bytes -= data.len();
299            self.ship(&arc, data);
300        } else if self.staged_bytes >= STAGE_TOTAL_CAP {
301            // Many tables, each under the per-table threshold: flush everything
302            // so total staging memory stays bounded by the cap.
303            let stage = std::mem::take(&mut self.stage);
304            for (table, data) in stage {
305                if !data.is_empty() {
306                    self.ship(&table, data);
307                }
308            }
309            self.staged_bytes = 0;
310        }
311    }
312
313    fn ship(&self, table: &Arc<str>, data: Vec<u8>) {
314        let shard = shard_index(table, self.senders.len());
315        // A dead writer's receiver is dropped, so `send` errors; the real error
316        // is surfaced by `finish`, so ignore send failures here.
317        let _ = self.senders[shard].send(Chunk {
318            table: Arc::clone(table),
319            data,
320        });
321    }
322
323    /// Flush all staged data, join the writer threads, and return the first
324    /// I/O error encountered (if any).
325    pub fn finish(mut self) -> std::io::Result<()> {
326        let stage = std::mem::take(&mut self.stage);
327        for (table, data) in stage {
328            if !data.is_empty() {
329                self.ship(&table, data);
330            }
331        }
332        drop(self.senders);
333
334        let mut first_err: Option<std::io::Error> = None;
335        for handle in self.handles {
336            match handle.join() {
337                Ok(Ok(())) => {}
338                Ok(Err(e)) => {
339                    first_err.get_or_insert(e);
340                }
341                Err(_) => {
342                    first_err
343                        .get_or_insert_with(|| std::io::Error::other("writer thread panicked"));
344                }
345            }
346        }
347        match first_err {
348            Some(e) => Err(e),
349            None => Ok(()),
350        }
351    }
352}
353
354/// FNV-1a hash of the table name → shard index. Deterministic within a run so a
355/// table always maps to the same writer (preserving per-file order).
356#[inline]
357fn shard_index(table: &str, n: usize) -> usize {
358    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
359    for &b in table.as_bytes() {
360        h ^= b as u64;
361        h = h.wrapping_mul(0x0000_0100_0000_01b3);
362    }
363    (h % n as u64) as usize
364}
365
366fn writer_loop(
367    rx: Receiver<Chunk>,
368    output_dir: PathBuf,
369    error_flag: Arc<AtomicBool>,
370    format: Compression,
371) -> std::io::Result<()> {
372    // Chunks are already ~256KB, so write straight to the sink (each write is a
373    // large syscall / compressor input) with no extra buffering layer.
374    let mut sinks: AHashMap<Arc<str>, TableSink> = AHashMap::new();
375    let mut first_err: Option<std::io::Error> = None;
376
377    for chunk in rx {
378        if first_err.is_some() {
379            continue; // keep draining so the producer never blocks
380        }
381        let sink = match sinks.entry(Arc::clone(&chunk.table)) {
382            Entry::Occupied(e) => e.into_mut(),
383            Entry::Vacant(e) => match TableSink::create(&output_dir, &chunk.table, format) {
384                Ok(s) => e.insert(s),
385                Err(err) => {
386                    error_flag.store(true, Ordering::Relaxed);
387                    first_err = Some(err);
388                    continue;
389                }
390            },
391        };
392        if let Err(err) = sink.write_all(&chunk.data) {
393            error_flag.store(true, Ordering::Relaxed);
394            first_err = Some(err);
395        }
396    }
397
398    // Finalize every sink so compressor epilogues are flushed (best effort even
399    // after an error, so files close cleanly).
400    for (_, sink) in sinks.drain() {
401        if let Err(err) = sink.finish() {
402            error_flag.store(true, Ordering::Relaxed);
403            if first_err.is_none() {
404                first_err = Some(err);
405            }
406        }
407    }
408
409    match first_err {
410        Some(e) => Err(e),
411        None => Ok(()),
412    }
413}