Skip to main content

sql_splitter/
transform_common.rs

1//! Shared plumbing for the row-level transform commands (`sample`, `shard`).
2//!
3//! Both commands follow the same pipeline: split the dump into per-table temp
4//! files, build a schema graph, walk each table's data rows, spill selected
5//! rows to disk, then synthesize a single SQL output file. This module owns
6//! the pieces that were previously duplicated between the two commands:
7//!
8//! - [`UnifiedRow`] / [`RowFormat`]: dialect-agnostic row representation
9//! - [`for_each_data_row`]: the INSERT/COPY statement walker
10//! - [`RowSpillWriter`] / [`RowSpillReader`]: bounded-memory row spilling
11//! - [`split_to_temp_tables`] / [`build_schema_graph`]: pipeline phases 0-1
12//! - [`write_dialect_header`] / [`write_dialect_footer`] / [`quote_ident`]:
13//!   session preamble and identifier quoting
14//! - [`convert_copy_to_insert_values`]: COPY-row to INSERT-VALUES conversion
15
16use crate::parser::mysql_insert::{
17    parse_insert_tuple, FkRef, InsertRowContext, ParsedRow, PkTuple, PkValue, RowExtraction,
18};
19use crate::parser::postgres_copy::{parse_copy_columns, CopyParser, ParsedCopyRow};
20use crate::parser::{ContentFilter, Parser, ParserEvent, SqlDialect};
21use crate::schema::{SchemaBuilder, SchemaGraph, TableSchema};
22use crate::splitter::{Splitter, Stats as SplitStats};
23use indicatif::{ProgressBar, ProgressStyle};
24use std::fs::{self, File};
25use std::io::{self, BufReader, BufWriter, Read, Write};
26use std::path::{Path, PathBuf};
27use tempfile::TempDir;
28
29/// Row format indicator for spilled/converted rows.
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub enum RowFormat {
32    /// MySQL-style `(v1, v2, ...)` value list from an INSERT statement.
33    Insert,
34    /// PostgreSQL COPY tab-separated row.
35    Copy,
36}
37
38impl RowFormat {
39    fn tag(self) -> u8 {
40        match self {
41            RowFormat::Insert => 0,
42            RowFormat::Copy => 1,
43        }
44    }
45
46    fn from_tag(tag: u8) -> Self {
47        if tag == 0 {
48            RowFormat::Insert
49        } else {
50            RowFormat::Copy
51        }
52    }
53}
54
55/// Combined row representation for both MySQL INSERT and PostgreSQL COPY.
56pub enum UnifiedRow {
57    Insert(ParsedRow),
58    Copy(ParsedCopyRow),
59}
60
61impl UnifiedRow {
62    pub fn pk(&self) -> Option<&PkTuple> {
63        match self {
64            UnifiedRow::Insert(r) => r.pk.as_ref(),
65            UnifiedRow::Copy(r) => r.pk.as_ref(),
66        }
67    }
68
69    pub fn fk_values(&self) -> &[(FkRef, PkTuple)] {
70        match self {
71            UnifiedRow::Insert(r) => &r.fk_values,
72            UnifiedRow::Copy(r) => &r.fk_values,
73        }
74    }
75
76    /// Get the value for a specific schema column index (requires
77    /// [`RowExtraction::Full`] parsing).
78    pub fn get_column_value(&self, idx: usize) -> Option<&PkValue> {
79        match self {
80            UnifiedRow::Insert(r) => r.get_column_value(idx),
81            UnifiedRow::Copy(r) => r.get_column_value(idx),
82        }
83    }
84
85    pub fn format(&self) -> RowFormat {
86        match self {
87            UnifiedRow::Insert(_) => RowFormat::Insert,
88            UnifiedRow::Copy(_) => RowFormat::Copy,
89        }
90    }
91
92    pub fn raw(&self) -> &[u8] {
93        match self {
94            UnifiedRow::Insert(r) => &r.raw,
95            UnifiedRow::Copy(r) => &r.raw,
96        }
97    }
98}
99
100// The row/event control-flow signal now lives in the parser layer so the
101// streaming row visitors and `Parser::visit_events` can share it; re-exported
102// here so the sample/shard consumers keep their existing import path.
103pub use crate::parser::RowFlow;
104
105/// Returns true if `stmt` is a PostgreSQL COPY data block (ends with the
106/// `\.` terminator).
107pub fn is_copy_data_block(stmt: &[u8]) -> bool {
108    stmt.ends_with(b"\\.\n") || stmt.ends_with(b"\\.\r\n")
109}
110
111/// Walk every data row of a per-table SQL file, invoking `f` for each row.
112///
113/// Handles the INSERT/COPY-header/COPY-data statement dispatch (including
114/// tracking the COPY column order across statements) that was previously
115/// hand-rolled in every sampling/sharding loop.
116pub fn for_each_data_row<F>(
117    table_file: &Path,
118    table_schema: &TableSchema,
119    dialect: SqlDialect,
120    extraction: RowExtraction,
121    mut f: F,
122) -> anyhow::Result<()>
123where
124    F: FnMut(UnifiedRow) -> anyhow::Result<RowFlow>,
125{
126    let file = File::open(table_file)?;
127    let mut parser = Parser::with_dialect(file, 64 * 1024, dialect);
128
129    // Per-statement/block context, rebuilt lazily as headers arrive so each
130    // streamed row is parsed with the same column mapping the collecting parser
131    // would have used — but only the current row is ever materialized.
132    let mut insert_ctx: Option<InsertRowContext> = None;
133    let mut copy_ctx: Option<(CopyParser<'_>, bool)> = None;
134
135    parser.visit_events(|event| match event {
136        // DDL/control statements carry no data rows here.
137        ParserEvent::Statement(_) => Ok(RowFlow::Continue),
138        ParserEvent::InsertRow {
139            header,
140            row,
141            first_in_statement,
142        } => {
143            if first_in_statement || insert_ctx.is_none() {
144                insert_ctx = Some(InsertRowContext::from_header(header, table_schema));
145            }
146            let ctx = insert_ctx.as_ref().expect("insert_ctx set above");
147            match parse_insert_tuple(row, table_schema, ctx, dialect, extraction) {
148                Some(parsed) => f(UnifiedRow::Insert(parsed)),
149                None => Ok(RowFlow::Continue),
150            }
151        }
152        ParserEvent::CopyStart(header) => {
153            let columns = parse_copy_columns(&String::from_utf8_lossy(header));
154            let (parser, empty_line_is_row) = CopyParser::new(&[])
155                .with_schema(table_schema)
156                .with_column_order(columns)
157                .with_extraction(extraction)
158                .prepared();
159            copy_ctx = Some((parser, empty_line_is_row));
160            Ok(RowFlow::Continue)
161        }
162        ParserEvent::CopyRow(line) => match copy_ctx.as_ref() {
163            Some((cp, empty_line_is_row)) => match cp.parse_line(line, *empty_line_is_row) {
164                Some(parsed) => f(UnifiedRow::Copy(parsed)),
165                None => Ok(RowFlow::Continue),
166            },
167            None => Ok(RowFlow::Continue),
168        },
169        ParserEvent::CopyEnd => Ok(RowFlow::Continue),
170    })
171}
172
173/// Writer for spilling selected rows to a temp file with bounded memory.
174///
175/// Record format: 1-byte format tag, 4-byte little-endian length, raw row
176/// bytes. Length-prefixed so rows containing newlines or non-UTF-8 bytes
177/// round-trip exactly.
178pub struct RowSpillWriter {
179    writer: BufWriter<File>,
180}
181
182impl RowSpillWriter {
183    pub fn create(path: &Path) -> io::Result<Self> {
184        Ok(Self {
185            writer: BufWriter::new(File::create(path)?),
186        })
187    }
188
189    pub fn write_row(&mut self, format: RowFormat, raw: &[u8]) -> io::Result<()> {
190        self.writer.write_all(&[format.tag()])?;
191        self.writer.write_all(&(raw.len() as u32).to_le_bytes())?;
192        self.writer.write_all(raw)
193    }
194
195    pub fn finish(mut self) -> io::Result<()> {
196        self.writer.flush()
197    }
198}
199
200/// Reader for row spill files written by [`RowSpillWriter`].
201pub struct RowSpillReader {
202    reader: BufReader<File>,
203}
204
205impl RowSpillReader {
206    pub fn open(path: &Path) -> io::Result<Self> {
207        Ok(Self {
208            reader: BufReader::new(File::open(path)?),
209        })
210    }
211
212    /// Read the next spilled row, or `None` at end of file.
213    pub fn next_row(&mut self) -> io::Result<Option<(RowFormat, Vec<u8>)>> {
214        let mut tag = [0u8; 1];
215        match self.reader.read_exact(&mut tag) {
216            Ok(()) => {}
217            Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => return Ok(None),
218            Err(e) => return Err(e),
219        }
220        let mut len_buf = [0u8; 4];
221        self.reader.read_exact(&mut len_buf)?;
222        let len = u32::from_le_bytes(len_buf) as usize;
223        let mut raw = vec![0u8; len];
224        self.reader.read_exact(&mut raw)?;
225        Ok(Some((RowFormat::from_tag(tag[0]), raw)))
226    }
227}
228
229/// Result of the phase-0 split into per-table temp files.
230pub struct SplitPhase {
231    /// Owns the temp directory; dropped when the pipeline finishes.
232    pub temp_dir: TempDir,
233    /// Directory containing the per-table `.sql` files.
234    pub tables_dir: PathBuf,
235    /// Statistics from the split.
236    pub stats: SplitStats,
237}
238
239/// Phase 0 shared by sample/shard: split the input dump into per-table temp
240/// files, with an optional byte-based progress bar.
241pub fn split_to_temp_tables(
242    input: &Path,
243    dialect: SqlDialect,
244    progress: bool,
245) -> anyhow::Result<SplitPhase> {
246    // Get file size for progress tracking
247    let file_size = std::fs::metadata(input)?.len();
248
249    // Progress bar setup - byte-based for the split phase
250    let progress_bar = if progress {
251        let pb = ProgressBar::new(file_size);
252        pb.set_style(
253            ProgressStyle::with_template(
254                "{spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] {bytes}/{total_bytes} ({percent}%) {msg}",
255            )
256            .unwrap()
257            .progress_chars("█▓▒░  ")
258            .tick_chars("⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"),
259        );
260        pb.enable_steady_tick(std::time::Duration::from_millis(100));
261        pb.set_message("Splitting dump...");
262        Some(pb)
263    } else {
264        None
265    };
266
267    let temp_dir = TempDir::new()?;
268    let tables_dir = temp_dir.path().join("tables");
269
270    let mut splitter = Splitter::new(input.to_path_buf(), tables_dir.clone())
271        .with_dialect(dialect)
272        .with_content_filter(ContentFilter::All);
273
274    if let Some(ref pb) = progress_bar {
275        let pb_clone = pb.clone();
276        splitter = splitter.with_progress(move |bytes| {
277            pb_clone.set_position(bytes);
278        });
279    }
280
281    let stats = splitter.split()?;
282
283    // Finish byte-based progress, switch to milestone messages
284    if let Some(ref pb) = progress_bar {
285        pb.finish_and_clear();
286    }
287
288    if progress {
289        eprintln!(
290            "Split complete: {} tables, {} statements",
291            stats.tables_found, stats.statements_processed
292        );
293    }
294
295    Ok(SplitPhase {
296        temp_dir,
297        tables_dir,
298        stats,
299    })
300}
301
302/// Build a schema graph from a directory of split per-table files.
303pub fn build_schema_graph(tables_dir: &Path, dialect: SqlDialect) -> anyhow::Result<SchemaGraph> {
304    let mut builder = SchemaBuilder::new();
305
306    for entry in fs::read_dir(tables_dir)? {
307        let entry = entry?;
308        let path = entry.path();
309
310        if path.extension().is_some_and(|e| e == "sql") {
311            let file = File::open(&path)?;
312            let mut parser = Parser::with_dialect(file, 64 * 1024, dialect);
313
314            while let Some(stmt) = parser.read_statement()? {
315                builder.ingest_statement(&stmt, dialect);
316            }
317        }
318    }
319
320    Ok(SchemaGraph::from_schema(builder.build()))
321}
322
323/// Quote an identifier for the given dialect.
324pub fn quote_ident(dialect: SqlDialect, name: &str) -> String {
325    // Double any occurrence of the closing delimiter so an identifier can never
326    // terminate its own quoting early (malformed / injectable SQL otherwise).
327    match dialect {
328        SqlDialect::MySql => format!("`{}`", name.replace('`', "``")),
329        SqlDialect::Postgres | SqlDialect::Sqlite => format!("\"{}\"", name.replace('"', "\"\"")),
330        SqlDialect::Mssql => format!("[{}]", name.replace(']', "]]")),
331    }
332}
333
334/// Write the dialect-specific session header (FK checks off, encoding, etc.).
335pub fn write_dialect_header<W: Write>(writer: &mut W, dialect: SqlDialect) -> io::Result<()> {
336    match dialect {
337        SqlDialect::MySql => {
338            writeln!(writer, "SET NAMES utf8mb4;")?;
339            writeln!(writer, "SET FOREIGN_KEY_CHECKS = 0;")?;
340        }
341        SqlDialect::Postgres => {
342            writeln!(writer, "SET client_encoding = 'UTF8';")?;
343            writeln!(writer, "SET session_replication_role = replica;")?;
344        }
345        SqlDialect::Sqlite => {
346            writeln!(writer, "PRAGMA foreign_keys = OFF;")?;
347        }
348        SqlDialect::Mssql => {
349            writeln!(writer, "SET ANSI_NULLS ON;")?;
350            writeln!(writer, "SET QUOTED_IDENTIFIER ON;")?;
351            writeln!(writer, "SET NOCOUNT ON;")?;
352        }
353    }
354    writeln!(writer)?;
355    Ok(())
356}
357
358/// Write the dialect-specific session footer (restores header settings).
359pub fn write_dialect_footer<W: Write>(writer: &mut W, dialect: SqlDialect) -> io::Result<()> {
360    writeln!(writer)?;
361    match dialect {
362        SqlDialect::MySql => {
363            writeln!(writer, "SET FOREIGN_KEY_CHECKS = 1;")?;
364        }
365        SqlDialect::Postgres => {
366            writeln!(writer, "SET session_replication_role = DEFAULT;")?;
367        }
368        SqlDialect::Sqlite => {
369            writeln!(writer, "PRAGMA foreign_keys = ON;")?;
370        }
371        SqlDialect::Mssql => {
372            // No footer needed
373        }
374    }
375    Ok(())
376}
377
378/// Write a chunk of spilled rows as a single multi-row INSERT statement.
379pub fn write_insert_chunk<W: Write>(
380    writer: &mut W,
381    quoted_name: &str,
382    chunk: &[(RowFormat, Vec<u8>)],
383    dialect: SqlDialect,
384) -> io::Result<()> {
385    writeln!(writer, "INSERT INTO {} VALUES", quoted_name)?;
386
387    for (i, (format, row_bytes)) in chunk.iter().enumerate() {
388        if i > 0 {
389            writer.write_all(b",\n")?;
390        }
391
392        let values = match format {
393            // A RowFormat::Insert row was captured verbatim from an input
394            // INSERT in this same dialect (sample/shard never cross-convert
395            // dialects), so it is re-emitted as-is. Rewriting escapes here — e.g.
396            // \' -> '' — corrupts native literals such as a value ending in a
397            // backslash.
398            RowFormat::Insert => row_bytes.clone(),
399            RowFormat::Copy => convert_copy_to_insert_values(row_bytes, dialect),
400        };
401        writer.write_all(&values)?;
402    }
403
404    writer.write_all(b";\n")?;
405    Ok(())
406}
407
408/// Convert PostgreSQL COPY format (tab-separated) to INSERT VALUES format.
409pub fn convert_copy_to_insert_values(row: &[u8], dialect: SqlDialect) -> Vec<u8> {
410    let mut result = Vec::with_capacity(row.len() + 20);
411    result.push(b'(');
412
413    let fields: Vec<&[u8]> = row.split(|&b| b == b'\t').collect();
414
415    for (i, field) in fields.iter().enumerate() {
416        if i > 0 {
417            result.extend_from_slice(b", ");
418        }
419
420        // Check for NULL marker
421        if *field == b"\\N" {
422            result.extend_from_slice(b"NULL");
423        } else if field.is_empty() {
424            result.extend_from_slice(b"''");
425        } else if is_numeric(field) {
426            // Numeric value - no quotes needed
427            result.extend_from_slice(field);
428        } else {
429            // Decode the COPY text-format escapes (\n \t \\ …) to the real
430            // bytes first, then re-escape for the target dialect's string
431            // literal. Emitting the raw COPY bytes here would leave `\n` as the
432            // two characters backslash+n (and MySQL would double the backslash
433            // into `\\n`), corrupting embedded newlines/tabs/backslashes.
434            let decoded = decode_copy_escapes(field);
435            result.push(b'\'');
436            for &b in &decoded {
437                match b {
438                    b'\'' => {
439                        // Escape single quote
440                        match dialect {
441                            SqlDialect::MySql => result.extend_from_slice(b"\\'"),
442                            SqlDialect::Postgres | SqlDialect::Sqlite | SqlDialect::Mssql => {
443                                result.extend_from_slice(b"''")
444                            }
445                        }
446                    }
447                    b'\\' if dialect == SqlDialect::MySql => {
448                        // Escape backslash in MySQL
449                        result.extend_from_slice(b"\\\\");
450                    }
451                    _ => result.push(b),
452                }
453            }
454            result.push(b'\'');
455        }
456    }
457
458    result.push(b')');
459    result
460}
461
462/// Decode PostgreSQL COPY text-format escape sequences in one field to the
463/// bytes they represent. Mirrors the decoder in `convert::copy_to_insert` but
464/// stays byte-oriented so binary/`bytea` data survives the round-trip.
465fn decode_copy_escapes(field: &[u8]) -> Vec<u8> {
466    // Fast path: no escapes at all -> the field is already the raw bytes.
467    if !field.contains(&b'\\') {
468        return field.to_vec();
469    }
470
471    let mut out = Vec::with_capacity(field.len());
472    let mut i = 0;
473    while i < field.len() {
474        if field[i] == b'\\' && i + 1 < field.len() {
475            let next = field[i + 1];
476            match next {
477                b'n' => out.push(b'\n'),
478                b'r' => out.push(b'\r'),
479                b't' => out.push(b'\t'),
480                b'\\' => out.push(b'\\'),
481                b'b' => out.push(0x08),
482                b'f' => out.push(0x0C),
483                b'v' => out.push(0x0B),
484                _ if next.is_ascii_digit() => {
485                    // Octal escape (\NNN, up to 3 digits).
486                    let mut val = 0u8;
487                    let mut consumed = 0;
488                    for j in 0..3 {
489                        match field.get(i + 1 + j) {
490                            Some(&d @ b'0'..=b'7') => {
491                                val = val.wrapping_mul(8).wrapping_add(d - b'0');
492                                consumed += 1;
493                            }
494                            _ => break,
495                        }
496                    }
497                    if consumed > 0 {
498                        out.push(val);
499                        i += 1 + consumed;
500                        continue;
501                    }
502                    // Not actually octal: keep the backslash and the byte.
503                    out.push(b'\\');
504                    out.push(next);
505                }
506                // Unknown escape: keep the backslash and the following byte.
507                _ => {
508                    out.push(b'\\');
509                    out.push(next);
510                }
511            }
512            i += 2;
513        } else {
514            out.push(field[i]);
515            i += 1;
516        }
517    }
518    out
519}
520
521/// Check if a byte slice represents a numeric value.
522pub fn is_numeric(s: &[u8]) -> bool {
523    if s.is_empty() {
524        return false;
525    }
526
527    let mut has_digit = false;
528    let mut has_dot = false;
529    let mut start = 0;
530
531    // Handle leading sign
532    if s[0] == b'-' || s[0] == b'+' {
533        start = 1;
534    }
535
536    for &b in &s[start..] {
537        match b {
538            b'0'..=b'9' => has_digit = true,
539            b'.' if !has_dot => has_dot = true,
540            b'e' | b'E' => {
541                // Scientific notation - just check rest is digits
542                continue;
543            }
544            _ => return false,
545        }
546    }
547
548    has_digit
549}
550
551#[cfg(test)]
552mod tests {
553    use super::*;
554
555    #[test]
556    fn spill_roundtrip_preserves_newlines_and_binary() {
557        let dir = tempfile::tempdir().unwrap();
558        let path = dir.path().join("t.rows");
559
560        let rows: Vec<(RowFormat, Vec<u8>)> = vec![
561            (RowFormat::Insert, b"(1, 'a\nb')".to_vec()),
562            (RowFormat::Copy, vec![0xFF, 0xFE, b'\t', b'x', b'\n']),
563            (RowFormat::Insert, Vec::new()),
564        ];
565
566        let mut w = RowSpillWriter::create(&path).unwrap();
567        for (f, raw) in &rows {
568            w.write_row(*f, raw).unwrap();
569        }
570        w.finish().unwrap();
571
572        let mut r = RowSpillReader::open(&path).unwrap();
573        for (f, raw) in &rows {
574            let (rf, rraw) = r.next_row().unwrap().unwrap();
575            assert_eq!(rf, *f);
576            assert_eq!(&rraw, raw);
577        }
578        assert!(r.next_row().unwrap().is_none());
579    }
580
581    #[test]
582    fn quote_ident_per_dialect() {
583        assert_eq!(quote_ident(SqlDialect::MySql, "t"), "`t`");
584        assert_eq!(quote_ident(SqlDialect::Postgres, "t"), "\"t\"");
585        assert_eq!(quote_ident(SqlDialect::Sqlite, "t"), "\"t\"");
586        assert_eq!(quote_ident(SqlDialect::Mssql, "t"), "[t]");
587    }
588
589    #[test]
590    fn quote_ident_escapes_the_closing_delimiter() {
591        // A delimiter character inside an identifier must be doubled so it cannot
592        // terminate the quoted identifier early (malformed / injectable SQL).
593        assert_eq!(quote_ident(SqlDialect::MySql, "a`b"), "`a``b`");
594        assert_eq!(quote_ident(SqlDialect::Postgres, "a\"b"), "\"a\"\"b\"");
595        assert_eq!(quote_ident(SqlDialect::Sqlite, "a\"b"), "\"a\"\"b\"");
596        assert_eq!(quote_ident(SqlDialect::Mssql, "a]b"), "[a]]b]");
597    }
598
599    #[test]
600    fn is_numeric_basics() {
601        assert!(is_numeric(b"123"));
602        assert!(is_numeric(b"-1.5"));
603        assert!(is_numeric(b"1e10"));
604        assert!(!is_numeric(b""));
605        assert!(!is_numeric(b"abc"));
606        assert!(!is_numeric(b"1.2.3"));
607    }
608}