1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub enum RowFormat {
32 Insert,
34 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
55pub 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 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
100pub use crate::parser::RowFlow;
104
105pub fn is_copy_data_block(stmt: &[u8]) -> bool {
108 stmt.ends_with(b"\\.\n") || stmt.ends_with(b"\\.\r\n")
109}
110
111pub 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 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 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, dialect));
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
173pub 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
200pub 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 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
229pub struct SplitPhase {
231 pub temp_dir: TempDir,
233 pub tables_dir: PathBuf,
235 pub stats: SplitStats,
237}
238
239pub fn split_to_temp_tables(
242 input: &Path,
243 dialect: SqlDialect,
244 progress: bool,
245) -> anyhow::Result<SplitPhase> {
246 let file_size = std::fs::metadata(input)?.len();
248
249 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 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
302pub 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
323pub fn quote_ident(dialect: SqlDialect, name: &str) -> String {
325 split_qualified_identifier(name)
330 .unwrap_or_else(|| vec![name.to_string()])
331 .iter()
332 .map(|part| quote_identifier_part(dialect, part))
333 .collect::<Vec<_>>()
334 .join(".")
335}
336
337pub fn quote_identifier(dialect: SqlDialect, name: &str) -> String {
343 quote_identifier_part(dialect, name)
344}
345
346fn split_qualified_identifier(name: &str) -> Option<Vec<String>> {
349 let bytes = name.as_bytes();
350 let mut i = 0;
351 let mut parts = Vec::new();
352
353 while i < bytes.len() {
354 let mut part = Vec::new();
355 if bytes[i] == b'"' {
356 i += 1;
357 let mut terminated = false;
358 while i < bytes.len() {
359 if bytes[i] == b'"' {
360 if bytes.get(i + 1) == Some(&b'"') {
361 part.push(b'"');
362 i += 2;
363 continue;
364 }
365 i += 1;
366 terminated = true;
367 break;
368 }
369 part.push(bytes[i]);
370 i += 1;
371 }
372 if !terminated {
373 return None;
374 }
375 } else {
376 while i < bytes.len() && bytes[i] != b'.' {
377 part.push(bytes[i]);
378 i += 1;
379 }
380 }
381
382 if part.is_empty() {
383 return None;
384 }
385 parts.push(String::from_utf8_lossy(&part).into_owned());
386
387 if i == bytes.len() {
388 return Some(parts);
389 }
390 if bytes[i] != b'.' {
391 return None;
392 }
393 i += 1;
394 }
395
396 None
397}
398
399fn quote_identifier_part(dialect: SqlDialect, name: &str) -> String {
400 match dialect {
403 SqlDialect::MySql => format!("`{}`", name.replace('`', "``")),
404 SqlDialect::Postgres | SqlDialect::Sqlite => {
405 format!("\"{}\"", name.replace('"', "\"\""))
406 }
407 SqlDialect::Mssql => format!("[{}]", name.replace(']', "]]")),
408 }
409}
410
411pub fn write_dialect_header<W: Write>(writer: &mut W, dialect: SqlDialect) -> io::Result<()> {
413 match dialect {
414 SqlDialect::MySql => {
415 writeln!(writer, "SET NAMES utf8mb4;")?;
416 writeln!(writer, "SET FOREIGN_KEY_CHECKS = 0;")?;
417 }
418 SqlDialect::Postgres => {
419 writeln!(writer, "SET client_encoding = 'UTF8';")?;
420 writeln!(writer, "SET session_replication_role = replica;")?;
421 }
422 SqlDialect::Sqlite => {
423 writeln!(writer, "PRAGMA foreign_keys = OFF;")?;
424 }
425 SqlDialect::Mssql => {
426 writeln!(writer, "SET ANSI_NULLS ON;")?;
427 writeln!(writer, "SET QUOTED_IDENTIFIER ON;")?;
428 writeln!(writer, "SET NOCOUNT ON;")?;
429 }
430 }
431 writeln!(writer)?;
432 Ok(())
433}
434
435pub fn write_dialect_footer<W: Write>(writer: &mut W, dialect: SqlDialect) -> io::Result<()> {
437 writeln!(writer)?;
438 match dialect {
439 SqlDialect::MySql => {
440 writeln!(writer, "SET FOREIGN_KEY_CHECKS = 1;")?;
441 }
442 SqlDialect::Postgres => {
443 writeln!(writer, "SET session_replication_role = DEFAULT;")?;
444 }
445 SqlDialect::Sqlite => {
446 writeln!(writer, "PRAGMA foreign_keys = ON;")?;
447 }
448 SqlDialect::Mssql => {
449 }
451 }
452 Ok(())
453}
454
455pub fn write_insert_chunk<W: Write>(
457 writer: &mut W,
458 quoted_name: &str,
459 chunk: &[(RowFormat, Vec<u8>)],
460 dialect: SqlDialect,
461) -> io::Result<()> {
462 writeln!(writer, "INSERT INTO {} VALUES", quoted_name)?;
463
464 for (i, (format, row_bytes)) in chunk.iter().enumerate() {
465 if i > 0 {
466 writer.write_all(b",\n")?;
467 }
468
469 let values = match format {
470 RowFormat::Insert => row_bytes.clone(),
476 RowFormat::Copy => convert_copy_to_insert_values(row_bytes, dialect),
477 };
478 writer.write_all(&values)?;
479 }
480
481 writer.write_all(b";\n")?;
482 Ok(())
483}
484
485pub fn convert_copy_to_insert_values(row: &[u8], dialect: SqlDialect) -> Vec<u8> {
487 let mut result = Vec::with_capacity(row.len() + 20);
488 result.push(b'(');
489
490 let fields: Vec<&[u8]> = row.split(|&b| b == b'\t').collect();
491
492 for (i, field) in fields.iter().enumerate() {
493 if i > 0 {
494 result.extend_from_slice(b", ");
495 }
496
497 if *field == b"\\N" {
499 result.extend_from_slice(b"NULL");
500 } else if field.is_empty() {
501 result.extend_from_slice(b"''");
502 } else if is_numeric(field) {
503 result.extend_from_slice(field);
505 } else {
506 let decoded = decode_copy_escapes(field);
512 result.push(b'\'');
513 for &b in &decoded {
514 match b {
515 b'\'' => {
516 match dialect {
518 SqlDialect::MySql => result.extend_from_slice(b"\\'"),
519 SqlDialect::Postgres | SqlDialect::Sqlite | SqlDialect::Mssql => {
520 result.extend_from_slice(b"''")
521 }
522 }
523 }
524 b'\\' if dialect == SqlDialect::MySql => {
525 result.extend_from_slice(b"\\\\");
527 }
528 _ => result.push(b),
529 }
530 }
531 result.push(b'\'');
532 }
533 }
534
535 result.push(b')');
536 result
537}
538
539fn decode_copy_escapes(field: &[u8]) -> Vec<u8> {
543 if !field.contains(&b'\\') {
545 return field.to_vec();
546 }
547
548 let mut out = Vec::with_capacity(field.len());
549 let mut i = 0;
550 while i < field.len() {
551 if field[i] == b'\\' && i + 1 < field.len() {
552 let next = field[i + 1];
553 match next {
554 b'n' => out.push(b'\n'),
555 b'r' => out.push(b'\r'),
556 b't' => out.push(b'\t'),
557 b'\\' => out.push(b'\\'),
558 b'b' => out.push(0x08),
559 b'f' => out.push(0x0C),
560 b'v' => out.push(0x0B),
561 _ if next.is_ascii_digit() => {
562 let mut val = 0u8;
564 let mut consumed = 0;
565 for j in 0..3 {
566 match field.get(i + 1 + j) {
567 Some(&d @ b'0'..=b'7') => {
568 val = val.wrapping_mul(8).wrapping_add(d - b'0');
569 consumed += 1;
570 }
571 _ => break,
572 }
573 }
574 if consumed > 0 {
575 out.push(val);
576 i += 1 + consumed;
577 continue;
578 }
579 out.push(b'\\');
581 out.push(next);
582 }
583 _ => {
585 out.push(b'\\');
586 out.push(next);
587 }
588 }
589 i += 2;
590 } else {
591 out.push(field[i]);
592 i += 1;
593 }
594 }
595 out
596}
597
598pub fn is_numeric(s: &[u8]) -> bool {
600 if s.is_empty() {
601 return false;
602 }
603
604 let mut has_digit = false;
605 let mut has_dot = false;
606 let mut start = 0;
607
608 if s[0] == b'-' || s[0] == b'+' {
610 start = 1;
611 }
612
613 for &b in &s[start..] {
614 match b {
615 b'0'..=b'9' => has_digit = true,
616 b'.' if !has_dot => has_dot = true,
617 b'e' | b'E' => {
618 continue;
620 }
621 _ => return false,
622 }
623 }
624
625 has_digit
626}
627
628#[cfg(test)]
629mod tests {
630 use super::*;
631
632 #[test]
633 fn spill_roundtrip_preserves_newlines_and_binary() {
634 let dir = tempfile::tempdir().unwrap();
635 let path = dir.path().join("t.rows");
636
637 let rows: Vec<(RowFormat, Vec<u8>)> = vec![
638 (RowFormat::Insert, b"(1, 'a\nb')".to_vec()),
639 (RowFormat::Copy, vec![0xFF, 0xFE, b'\t', b'x', b'\n']),
640 (RowFormat::Insert, Vec::new()),
641 ];
642
643 let mut w = RowSpillWriter::create(&path).unwrap();
644 for (f, raw) in &rows {
645 w.write_row(*f, raw).unwrap();
646 }
647 w.finish().unwrap();
648
649 let mut r = RowSpillReader::open(&path).unwrap();
650 for (f, raw) in &rows {
651 let (rf, rraw) = r.next_row().unwrap().unwrap();
652 assert_eq!(rf, *f);
653 assert_eq!(&rraw, raw);
654 }
655 assert!(r.next_row().unwrap().is_none());
656 }
657
658 #[test]
659 fn quote_ident_per_dialect() {
660 assert_eq!(quote_ident(SqlDialect::MySql, "t"), "`t`");
661 assert_eq!(quote_ident(SqlDialect::Postgres, "t"), "\"t\"");
662 assert_eq!(quote_ident(SqlDialect::Sqlite, "t"), "\"t\"");
663 assert_eq!(quote_ident(SqlDialect::Mssql, "t"), "[t]");
664 }
665
666 #[test]
667 fn quote_ident_keeps_qualified_table_parts_separate() {
668 assert_eq!(
669 quote_ident(SqlDialect::Postgres, "tenant_a.users"),
670 "\"tenant_a\".\"users\""
671 );
672 assert_eq!(
673 quote_ident(SqlDialect::MySql, "tenant_a.users"),
674 "`tenant_a`.`users`"
675 );
676 assert_eq!(quote_ident(SqlDialect::Mssql, "dbo.users"), "[dbo].[users]");
677 assert_eq!(
678 quote_ident(SqlDialect::Postgres, "public.\"user.log\""),
679 "\"public\".\"user.log\""
680 );
681 }
682
683 #[test]
684 fn quote_ident_escapes_the_closing_delimiter() {
685 assert_eq!(quote_ident(SqlDialect::MySql, "a`b"), "`a``b`");
688 assert_eq!(quote_ident(SqlDialect::Postgres, "a\"b"), "\"a\"\"b\"");
689 assert_eq!(quote_ident(SqlDialect::Sqlite, "a\"b"), "\"a\"\"b\"");
690 assert_eq!(quote_ident(SqlDialect::Mssql, "a]b"), "[a]]b]");
691 }
692
693 #[test]
694 fn quote_identifier_keeps_literal_dots_in_one_component() {
695 assert_eq!(
696 quote_identifier(SqlDialect::Postgres, "settings.theme"),
697 "\"settings.theme\""
698 );
699 }
700
701 #[test]
702 fn is_numeric_basics() {
703 assert!(is_numeric(b"123"));
704 assert!(is_numeric(b"-1.5"));
705 assert!(is_numeric(b"1e10"));
706 assert!(!is_numeric(b""));
707 assert!(!is_numeric(b"abc"));
708 assert!(!is_numeric(b"1.2.3"));
709 }
710}