1use crate::parser::mysql_insert::{
18 parse_insert_tuple, FkRef, InsertRowContext, ParsedRow, PkTuple, PkValue, RowExtraction,
19};
20use crate::parser::postgres_copy::{parse_copy_columns, CopyParser, ParsedCopyRow};
21use crate::parser::{ContentFilter, Parser, ParserEvent, SqlDialect};
22use crate::schema::{SchemaBuilder, SchemaGraph, TableSchema};
23use crate::splitter::{Splitter, Stats as SplitStats};
24use indicatif::{ProgressBar, ProgressStyle};
25use std::fs::{self, File};
26use std::io::{self, BufReader, BufWriter, Read, Write};
27use std::path::{Path, PathBuf};
28use tempfile::TempDir;
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub enum RowFormat {
33 Insert,
35 Copy,
37}
38
39impl RowFormat {
40 fn tag(self) -> u8 {
41 match self {
42 RowFormat::Insert => 0,
43 RowFormat::Copy => 1,
44 }
45 }
46
47 fn from_tag(tag: u8) -> Self {
48 if tag == 0 {
49 RowFormat::Insert
50 } else {
51 RowFormat::Copy
52 }
53 }
54}
55
56pub enum UnifiedRow {
58 Insert(ParsedRow),
59 Copy(ParsedCopyRow),
60}
61
62impl UnifiedRow {
63 pub fn pk(&self) -> Option<&PkTuple> {
64 match self {
65 UnifiedRow::Insert(r) => r.pk.as_ref(),
66 UnifiedRow::Copy(r) => r.pk.as_ref(),
67 }
68 }
69
70 pub fn fk_values(&self) -> &[(FkRef, PkTuple)] {
71 match self {
72 UnifiedRow::Insert(r) => &r.fk_values,
73 UnifiedRow::Copy(r) => &r.fk_values,
74 }
75 }
76
77 pub fn get_column_value(&self, idx: usize) -> Option<&PkValue> {
80 match self {
81 UnifiedRow::Insert(r) => r.get_column_value(idx),
82 UnifiedRow::Copy(r) => r.get_column_value(idx),
83 }
84 }
85
86 pub fn format(&self) -> RowFormat {
87 match self {
88 UnifiedRow::Insert(_) => RowFormat::Insert,
89 UnifiedRow::Copy(_) => RowFormat::Copy,
90 }
91 }
92
93 pub fn raw(&self) -> &[u8] {
94 match self {
95 UnifiedRow::Insert(r) => &r.raw,
96 UnifiedRow::Copy(r) => &r.raw,
97 }
98 }
99}
100
101pub use crate::parser::RowFlow;
105
106pub fn is_copy_data_block(stmt: &[u8]) -> bool {
109 stmt.ends_with(b"\\.\n") || stmt.ends_with(b"\\.\r\n")
110}
111
112pub fn for_each_data_row<F>(
118 table_file: &Path,
119 table_schema: &TableSchema,
120 dialect: SqlDialect,
121 extraction: RowExtraction,
122 mut f: F,
123) -> anyhow::Result<()>
124where
125 F: FnMut(UnifiedRow) -> anyhow::Result<RowFlow>,
126{
127 let file = File::open(table_file)?;
128 let mut parser = Parser::with_dialect(file, 64 * 1024, dialect);
129
130 let mut insert_ctx: Option<InsertRowContext> = None;
134 let mut copy_ctx: Option<(CopyParser<'_>, bool)> = None;
135
136 parser.visit_events(|event| match event {
137 ParserEvent::Statement(_) => Ok(RowFlow::Continue),
139 ParserEvent::InsertRow {
140 header,
141 row,
142 first_in_statement,
143 } => {
144 if first_in_statement || insert_ctx.is_none() {
145 insert_ctx = Some(InsertRowContext::from_header(header, table_schema));
146 }
147 let ctx = insert_ctx.as_ref().expect("insert_ctx set above");
148 match parse_insert_tuple(row, table_schema, ctx, dialect, extraction) {
149 Some(parsed) => f(UnifiedRow::Insert(parsed)),
150 None => Ok(RowFlow::Continue),
151 }
152 }
153 ParserEvent::CopyStart(header) => {
154 let columns = parse_copy_columns(&String::from_utf8_lossy(header));
155 let (parser, empty_line_is_row) = CopyParser::new(&[])
156 .with_schema(table_schema)
157 .with_column_order(columns)
158 .with_extraction(extraction)
159 .prepared();
160 copy_ctx = Some((parser, empty_line_is_row));
161 Ok(RowFlow::Continue)
162 }
163 ParserEvent::CopyRow(line) => match copy_ctx.as_ref() {
164 Some((cp, empty_line_is_row)) => match cp.parse_line(line, *empty_line_is_row) {
165 Some(parsed) => f(UnifiedRow::Copy(parsed)),
166 None => Ok(RowFlow::Continue),
167 },
168 None => Ok(RowFlow::Continue),
169 },
170 ParserEvent::CopyEnd => Ok(RowFlow::Continue),
171 })
172}
173
174pub struct RowSpillWriter {
180 writer: BufWriter<File>,
181}
182
183impl RowSpillWriter {
184 pub fn create(path: &Path) -> io::Result<Self> {
185 Ok(Self {
186 writer: BufWriter::new(File::create(path)?),
187 })
188 }
189
190 pub fn write_row(&mut self, format: RowFormat, raw: &[u8]) -> io::Result<()> {
191 self.writer.write_all(&[format.tag()])?;
192 self.writer.write_all(&(raw.len() as u32).to_le_bytes())?;
193 self.writer.write_all(raw)
194 }
195
196 pub fn finish(mut self) -> io::Result<()> {
197 self.writer.flush()
198 }
199}
200
201pub struct RowSpillReader {
203 reader: BufReader<File>,
204}
205
206impl RowSpillReader {
207 pub fn open(path: &Path) -> io::Result<Self> {
208 Ok(Self {
209 reader: BufReader::new(File::open(path)?),
210 })
211 }
212
213 pub fn next_row(&mut self) -> io::Result<Option<(RowFormat, Vec<u8>)>> {
215 let mut tag = [0u8; 1];
216 match self.reader.read_exact(&mut tag) {
217 Ok(()) => {}
218 Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => return Ok(None),
219 Err(e) => return Err(e),
220 }
221 let mut len_buf = [0u8; 4];
222 self.reader.read_exact(&mut len_buf)?;
223 let len = u32::from_le_bytes(len_buf) as usize;
224 let mut raw = vec![0u8; len];
225 self.reader.read_exact(&mut raw)?;
226 Ok(Some((RowFormat::from_tag(tag[0]), raw)))
227 }
228}
229
230pub struct SplitPhase {
232 pub temp_dir: TempDir,
234 pub tables_dir: PathBuf,
236 pub stats: SplitStats,
238}
239
240pub fn split_to_temp_tables(
243 input: &Path,
244 dialect: SqlDialect,
245 progress: bool,
246) -> anyhow::Result<SplitPhase> {
247 let file_size = std::fs::metadata(input)?.len();
249
250 let progress_bar = if progress {
252 let pb = ProgressBar::new(file_size);
253 pb.set_style(
254 ProgressStyle::with_template(
255 "{spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] {bytes}/{total_bytes} ({percent}%) {msg}",
256 )
257 .unwrap()
258 .progress_chars("█▓▒░ ")
259 .tick_chars("⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"),
260 );
261 pb.enable_steady_tick(std::time::Duration::from_millis(100));
262 pb.set_message("Splitting dump...");
263 Some(pb)
264 } else {
265 None
266 };
267
268 let temp_dir = TempDir::new()?;
269 let tables_dir = temp_dir.path().join("tables");
270
271 let mut splitter = Splitter::new(input.to_path_buf(), tables_dir.clone())
272 .with_dialect(dialect)
273 .with_content_filter(ContentFilter::All);
274
275 if let Some(ref pb) = progress_bar {
276 let pb_clone = pb.clone();
277 splitter = splitter.with_progress(move |bytes| {
278 pb_clone.set_position(bytes);
279 });
280 }
281
282 let stats = splitter.split()?;
283
284 if let Some(ref pb) = progress_bar {
286 pb.finish_and_clear();
287 }
288
289 if progress {
290 eprintln!(
291 "Split complete: {} tables, {} statements",
292 stats.tables_found, stats.statements_processed
293 );
294 }
295
296 Ok(SplitPhase {
297 temp_dir,
298 tables_dir,
299 stats,
300 })
301}
302
303pub fn build_schema_graph(tables_dir: &Path, dialect: SqlDialect) -> anyhow::Result<SchemaGraph> {
305 let mut builder = SchemaBuilder::new();
306
307 for entry in fs::read_dir(tables_dir)? {
308 let entry = entry?;
309 let path = entry.path();
310
311 if path.extension().is_some_and(|e| e == "sql") {
312 let file = File::open(&path)?;
313 let mut parser = Parser::with_dialect(file, 64 * 1024, dialect);
314
315 while let Some(stmt) = parser.read_statement()? {
316 builder.ingest_statement(&stmt, dialect);
317 }
318 }
319 }
320
321 Ok(SchemaGraph::from_schema(builder.build()))
322}
323
324pub fn quote_ident(dialect: SqlDialect, name: &str) -> String {
326 match dialect {
329 SqlDialect::MySql => format!("`{}`", name.replace('`', "``")),
330 SqlDialect::Postgres | SqlDialect::Sqlite => format!("\"{}\"", name.replace('"', "\"\"")),
331 SqlDialect::Mssql => format!("[{}]", name.replace(']', "]]")),
332 }
333}
334
335pub fn write_dialect_header<W: Write>(writer: &mut W, dialect: SqlDialect) -> io::Result<()> {
337 match dialect {
338 SqlDialect::MySql => {
339 writeln!(writer, "SET NAMES utf8mb4;")?;
340 writeln!(writer, "SET FOREIGN_KEY_CHECKS = 0;")?;
341 }
342 SqlDialect::Postgres => {
343 writeln!(writer, "SET client_encoding = 'UTF8';")?;
344 writeln!(writer, "SET session_replication_role = replica;")?;
345 }
346 SqlDialect::Sqlite => {
347 writeln!(writer, "PRAGMA foreign_keys = OFF;")?;
348 }
349 SqlDialect::Mssql => {
350 writeln!(writer, "SET ANSI_NULLS ON;")?;
351 writeln!(writer, "SET QUOTED_IDENTIFIER ON;")?;
352 writeln!(writer, "SET NOCOUNT ON;")?;
353 }
354 }
355 writeln!(writer)?;
356 Ok(())
357}
358
359pub fn write_dialect_footer<W: Write>(writer: &mut W, dialect: SqlDialect) -> io::Result<()> {
361 writeln!(writer)?;
362 match dialect {
363 SqlDialect::MySql => {
364 writeln!(writer, "SET FOREIGN_KEY_CHECKS = 1;")?;
365 }
366 SqlDialect::Postgres => {
367 writeln!(writer, "SET session_replication_role = DEFAULT;")?;
368 }
369 SqlDialect::Sqlite => {
370 writeln!(writer, "PRAGMA foreign_keys = ON;")?;
371 }
372 SqlDialect::Mssql => {
373 }
375 }
376 Ok(())
377}
378
379pub fn write_insert_chunk<W: Write>(
381 writer: &mut W,
382 quoted_name: &str,
383 chunk: &[(RowFormat, Vec<u8>)],
384 dialect: SqlDialect,
385) -> io::Result<()> {
386 writeln!(writer, "INSERT INTO {} VALUES", quoted_name)?;
387
388 for (i, (format, row_bytes)) in chunk.iter().enumerate() {
389 if i > 0 {
390 writer.write_all(b",\n")?;
391 }
392
393 let values = match format {
394 RowFormat::Insert => match dialect {
395 SqlDialect::Postgres => convert_row_to_postgres(row_bytes),
396 _ => row_bytes.clone(),
397 },
398 RowFormat::Copy => convert_copy_to_insert_values(row_bytes, dialect),
399 };
400 writer.write_all(&values)?;
401 }
402
403 writer.write_all(b";\n")?;
404 Ok(())
405}
406
407pub fn convert_row_to_postgres(row: &[u8]) -> Vec<u8> {
409 let mut result = Vec::with_capacity(row.len());
412 let mut i = 0;
413
414 while i < row.len() {
415 if row[i] == b'\\' && i + 1 < row.len() && row[i + 1] == b'\'' {
416 result.push(b'\'');
418 result.push(b'\'');
419 i += 2;
420 } else {
421 result.push(row[i]);
422 i += 1;
423 }
424 }
425
426 result
427}
428
429pub fn convert_copy_to_insert_values(row: &[u8], dialect: SqlDialect) -> Vec<u8> {
431 let mut result = Vec::with_capacity(row.len() + 20);
432 result.push(b'(');
433
434 let fields: Vec<&[u8]> = row.split(|&b| b == b'\t').collect();
435
436 for (i, field) in fields.iter().enumerate() {
437 if i > 0 {
438 result.extend_from_slice(b", ");
439 }
440
441 if *field == b"\\N" {
443 result.extend_from_slice(b"NULL");
444 } else if field.is_empty() {
445 result.extend_from_slice(b"''");
446 } else if is_numeric(field) {
447 result.extend_from_slice(field);
449 } else {
450 result.push(b'\'');
452 for &b in *field {
453 match b {
454 b'\'' => {
455 match dialect {
457 SqlDialect::MySql => result.extend_from_slice(b"\\'"),
458 SqlDialect::Postgres | SqlDialect::Sqlite | SqlDialect::Mssql => {
459 result.extend_from_slice(b"''")
460 }
461 }
462 }
463 b'\\' if dialect == SqlDialect::MySql => {
464 result.extend_from_slice(b"\\\\");
466 }
467 _ => result.push(b),
468 }
469 }
470 result.push(b'\'');
471 }
472 }
473
474 result.push(b')');
475 result
476}
477
478pub fn is_numeric(s: &[u8]) -> bool {
480 if s.is_empty() {
481 return false;
482 }
483
484 let mut has_digit = false;
485 let mut has_dot = false;
486 let mut start = 0;
487
488 if s[0] == b'-' || s[0] == b'+' {
490 start = 1;
491 }
492
493 for &b in &s[start..] {
494 match b {
495 b'0'..=b'9' => has_digit = true,
496 b'.' if !has_dot => has_dot = true,
497 b'e' | b'E' => {
498 continue;
500 }
501 _ => return false,
502 }
503 }
504
505 has_digit
506}
507
508#[cfg(test)]
509mod tests {
510 use super::*;
511
512 #[test]
513 fn spill_roundtrip_preserves_newlines_and_binary() {
514 let dir = tempfile::tempdir().unwrap();
515 let path = dir.path().join("t.rows");
516
517 let rows: Vec<(RowFormat, Vec<u8>)> = vec![
518 (RowFormat::Insert, b"(1, 'a\nb')".to_vec()),
519 (RowFormat::Copy, vec![0xFF, 0xFE, b'\t', b'x', b'\n']),
520 (RowFormat::Insert, Vec::new()),
521 ];
522
523 let mut w = RowSpillWriter::create(&path).unwrap();
524 for (f, raw) in &rows {
525 w.write_row(*f, raw).unwrap();
526 }
527 w.finish().unwrap();
528
529 let mut r = RowSpillReader::open(&path).unwrap();
530 for (f, raw) in &rows {
531 let (rf, rraw) = r.next_row().unwrap().unwrap();
532 assert_eq!(rf, *f);
533 assert_eq!(&rraw, raw);
534 }
535 assert!(r.next_row().unwrap().is_none());
536 }
537
538 #[test]
539 fn quote_ident_per_dialect() {
540 assert_eq!(quote_ident(SqlDialect::MySql, "t"), "`t`");
541 assert_eq!(quote_ident(SqlDialect::Postgres, "t"), "\"t\"");
542 assert_eq!(quote_ident(SqlDialect::Sqlite, "t"), "\"t\"");
543 assert_eq!(quote_ident(SqlDialect::Mssql, "t"), "[t]");
544 }
545
546 #[test]
547 fn quote_ident_escapes_the_closing_delimiter() {
548 assert_eq!(quote_ident(SqlDialect::MySql, "a`b"), "`a``b`");
551 assert_eq!(quote_ident(SqlDialect::Postgres, "a\"b"), "\"a\"\"b\"");
552 assert_eq!(quote_ident(SqlDialect::Sqlite, "a\"b"), "\"a\"\"b\"");
553 assert_eq!(quote_ident(SqlDialect::Mssql, "a]b"), "[a]]b]");
554 }
555
556 #[test]
557 fn is_numeric_basics() {
558 assert!(is_numeric(b"123"));
559 assert!(is_numeric(b"-1.5"));
560 assert!(is_numeric(b"1e10"));
561 assert!(!is_numeric(b""));
562 assert!(!is_numeric(b"abc"));
563 assert!(!is_numeric(b"1.2.3"));
564 }
565}