1use super::batch::{flush_batch, BatchManager, MAX_ROWS_PER_BATCH};
4use super::types::TypeConverter;
5use super::{ImportStats, QueryConfig};
6use crate::convert::copy_to_insert::{copy_to_inserts, parse_copy_header, CopyHeader};
7use crate::parser::{
8 detect_dialect_from_file, parse_insert_for_bulk, Parser, SqlDialect, StatementType,
9};
10use anyhow::{Context, Result};
11use duckdb::Connection;
12use indicatif::{ProgressBar, ProgressStyle};
13use once_cell::sync::Lazy;
14use regex::Regex;
15use std::io::{BufRead, BufReader, Read};
16use std::path::Path;
17
18const MAX_COPY_ROWS_PER_BATCH: usize = 10_000;
21
22pub struct DumpLoader<'a> {
24 conn: &'a Connection,
25 config: &'a QueryConfig,
26}
27
28impl<'a> DumpLoader<'a> {
29 pub fn new(conn: &'a Connection, config: &'a QueryConfig) -> Self {
31 Self { conn, config }
32 }
33
34 pub fn load(&self, dump_path: &Path) -> Result<ImportStats> {
36 let start = std::time::Instant::now();
37 let mut stats = ImportStats::default();
38
39 let dialect = if let Some(d) = self.config.dialect {
41 d
42 } else {
43 let result = detect_dialect_from_file(dump_path)?;
44 result.dialect
45 };
46
47 let file_size = std::fs::metadata(dump_path)?.len();
49
50 let progress_bar = if self.config.progress {
52 let pb = ProgressBar::new(file_size);
53 pb.set_style(
54 ProgressStyle::default_bar()
55 .template("{spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] {bytes}/{total_bytes} ({percent}%)")
56 .unwrap()
57 .progress_chars("=>-"),
58 );
59 Some(pb)
60 } else {
61 None
62 };
63
64 let reader: Box<dyn Read> = match &progress_bar {
72 Some(pb) => {
73 let pb = pb.clone();
74 crate::splitter::open_input_with_progress(
75 dump_path,
76 Box::new(move |bytes| pb.set_position(bytes)),
77 )
78 .context("Failed to open dump file")?
79 }
80 None => crate::splitter::open_input(dump_path).context("Failed to open dump file")?,
81 };
82
83 let buf_reader = BufReader::with_capacity(256 * 1024, reader);
84
85 self.load_statements(buf_reader, dialect, &mut stats)?;
87
88 if let Some(pb) = progress_bar {
89 pb.finish_with_message("Import complete");
90 }
91
92 stats.duration_secs = start.elapsed().as_secs_f64();
93 Ok(stats)
94 }
95
96 fn load_statements<R: Read>(
98 &self,
99 reader: BufReader<R>,
100 dialect: SqlDialect,
101 stats: &mut ImportStats,
102 ) -> Result<()> {
103 let mut parser = StatementReader::new(reader, dialect);
104 let mut pending_copy: Option<CopyHeader> = None;
105
106 let mut copy_batch_data: Vec<u8> = Vec::new();
108 let mut copy_batch_rows: usize = 0;
109
110 let mut failed_tables: std::collections::HashSet<String> = std::collections::HashSet::new();
112
113 let mut batch_mgr = BatchManager::new(MAX_ROWS_PER_BATCH);
115
116 while let Some(stmt_result) = parser.next_statement() {
117 let stmt = stmt_result?;
118
119 if let Some(ref header) = pending_copy {
121 let trimmed = stmt.trim();
122
123 if trimmed == "\\." {
125 if !copy_batch_data.is_empty() {
127 self.process_copy_batch(
128 header,
129 ©_batch_data,
130 stats,
131 &mut failed_tables,
132 );
133 copy_batch_data.clear();
134 copy_batch_rows = 0;
135 }
136 pending_copy = None;
137 parser.set_copy_mode(false);
138 continue;
139 }
140
141 if trimmed.is_empty() {
143 continue;
144 }
145
146 if Self::looks_like_copy_data(&stmt) {
148 if failed_tables.contains(&header.table) {
150 continue;
151 }
152
153 copy_batch_data.extend_from_slice(stmt.as_bytes());
154 copy_batch_data.push(b'\n');
155 copy_batch_rows += 1;
156
157 if copy_batch_rows >= MAX_COPY_ROWS_PER_BATCH {
159 self.process_copy_batch(
160 header,
161 ©_batch_data,
162 stats,
163 &mut failed_tables,
164 );
165 copy_batch_data.clear();
166 copy_batch_rows = 0;
167 }
168 continue;
169 }
170
171 if !copy_batch_data.is_empty() {
173 self.process_copy_batch(header, ©_batch_data, stats, &mut failed_tables);
174 copy_batch_data.clear();
175 copy_batch_rows = 0;
176 }
177 pending_copy = None;
178 parser.set_copy_mode(false);
179 }
181
182 let (mut stmt_type, table_name) =
183 Parser::<&[u8]>::parse_statement_with_dialect(stmt.as_bytes(), dialect);
184
185 if dialect == SqlDialect::Postgres && stmt_type == StatementType::Unknown {
187 let upper = stmt.to_uppercase();
188 if let Some(copy_pos) = upper.find("COPY ") {
189 let after_copy = &upper[copy_pos..];
190 if after_copy.contains("FROM STDIN") {
191 stmt_type = StatementType::Copy;
192 }
193 }
194 }
195
196 if let Some(ref tables) = self.config.tables {
198 if !table_name.is_empty()
199 && !tables.iter().any(|t| t.eq_ignore_ascii_case(&table_name))
200 {
201 continue;
202 }
203 }
204
205 match stmt_type {
206 StatementType::CreateTable => {
207 let duckdb_sql = self.convert_create_table(&stmt, dialect)?;
208 match self.conn.execute(&duckdb_sql, []) {
209 Ok(_) => stats.tables_created += 1,
210 Err(e) => {
211 stats
212 .warnings
213 .push(format!("Failed to create table {}: {}", table_name, e));
214 stats.statements_skipped += 1;
215 }
216 }
217 }
218 StatementType::Insert => {
219 if !self.try_queue_for_bulk(
221 &stmt,
222 dialect,
223 &mut batch_mgr,
224 stats,
225 &mut failed_tables,
226 ) {
227 let duckdb_sql = self.convert_insert(&stmt, dialect)?;
229 match self.conn.execute(&duckdb_sql, []) {
230 Ok(_) => {
231 stats.insert_statements += 1;
232 stats.rows_inserted += Self::count_insert_rows(&duckdb_sql);
233 }
234 Err(e) => {
235 stats
236 .warnings
237 .push(format!("Failed INSERT for {}: {}", table_name, e));
238 stats.statements_skipped += 1;
239 }
240 }
241 }
242
243 for mut batch in batch_mgr.get_ready_batches() {
245 flush_batch(self.conn, &mut batch, stats, &mut failed_tables)?;
246 }
247 }
248 StatementType::Copy => {
249 if let Some(header) = parse_copy_header(&stmt) {
251 if failed_tables.contains(&header.table) {
253 parser.set_copy_mode(true);
255 Self::skip_copy_block(&mut parser);
256 parser.set_copy_mode(false);
257 continue;
258 }
259
260 if !self.table_exists(&header.table) {
262 failed_tables.insert(header.table.clone());
263 if stats.warnings.len() < 100 {
264 stats.warnings.push(format!(
265 "Skipping COPY for non-existent table {}",
266 header.table
267 ));
268 }
269 parser.set_copy_mode(true);
271 Self::skip_copy_block(&mut parser);
272 parser.set_copy_mode(false);
273 continue;
274 }
275
276 copy_batch_data.clear();
277 copy_batch_rows = 0;
278 pending_copy = Some(header);
279 parser.set_copy_mode(true);
280 }
281 }
282 StatementType::CreateIndex => {
283 stats.statements_skipped += 1;
285 }
286 _ => {
287 stats.statements_skipped += 1;
289 }
290 }
291 }
292
293 if let Some(ref header) = pending_copy {
295 if !copy_batch_data.is_empty() {
296 self.process_copy_batch(header, ©_batch_data, stats, &mut failed_tables);
297 }
298 }
299
300 for mut batch in batch_mgr.drain_all() {
302 flush_batch(self.conn, &mut batch, stats, &mut failed_tables)?;
303 }
304
305 Ok(())
306 }
307
308 fn process_copy_batch(
310 &self,
311 header: &CopyHeader,
312 batch_data: &[u8],
313 stats: &mut ImportStats,
314 failed_tables: &mut std::collections::HashSet<String>,
315 ) {
316 if batch_data.is_empty() {
317 return;
318 }
319
320 if failed_tables.contains(&header.table) {
322 return;
323 }
324
325 let inserts = copy_to_inserts(header, batch_data, SqlDialect::Postgres);
326 for insert in inserts {
327 let insert_sql = String::from_utf8_lossy(&insert);
328 match self.conn.execute(&insert_sql, []) {
329 Ok(_) => {
330 stats.rows_inserted += Self::count_insert_rows(&insert_sql);
331 }
332 Err(e) => {
333 let err_str = e.to_string();
334 if err_str.contains("does not exist") {
336 failed_tables.insert(header.table.clone());
337 if stats.warnings.len() < 100 {
338 stats.warnings.push(format!(
339 "Table {} does not exist, skipping COPY data",
340 header.table
341 ));
342 }
343 return; }
345 if stats.warnings.len() < 100 {
347 stats.warnings.push(format!(
348 "Failed to insert COPY data for {}: {}",
349 header.table, e
350 ));
351 }
352 stats.statements_skipped += 1;
353 }
354 }
355 }
356 }
357
358 fn table_exists(&self, table: &str) -> bool {
360 let query = "SELECT 1 FROM information_schema.tables WHERE table_name = ? LIMIT 1";
361 match self.conn.prepare(query) {
362 Ok(mut stmt) => stmt.exists([table]).unwrap_or(false),
363 Err(_) => false,
364 }
365 }
366
367 fn try_queue_for_bulk(
370 &self,
371 stmt: &str,
372 dialect: SqlDialect,
373 batch_mgr: &mut BatchManager,
374 stats: &mut ImportStats,
375 failed_tables: &mut std::collections::HashSet<String>,
376 ) -> bool {
377 let upper = stmt.to_uppercase();
379 if upper.contains("ON DUPLICATE KEY")
380 || upper.contains("ON CONFLICT")
381 || upper.contains("REPLACE")
382 || upper.contains("IGNORE")
383 || upper.contains("RETURNING")
384 || upper.contains("SELECT")
385 {
386 return false;
387 }
388
389 let parsed = match parse_insert_for_bulk(stmt.as_bytes(), dialect) {
391 Ok(p) => p,
392 Err(_) => return false, };
394
395 if failed_tables.contains(&parsed.table) {
397 return true; }
399
400 if parsed.rows.is_empty() {
402 return false;
403 }
404
405 let duckdb_sql = match self.convert_insert(stmt, dialect) {
407 Ok(sql) => sql,
408 Err(_) => return false,
409 };
410
411 if let Some(mut batch) =
413 batch_mgr.queue_insert(&parsed.table, parsed.columns, parsed.rows, duckdb_sql)
414 {
415 if let Err(e) = flush_batch(self.conn, &mut batch, stats, failed_tables) {
417 if stats.warnings.len() < 100 {
418 stats.warnings.push(format!("Batch flush error: {}", e));
419 }
420 }
421 }
422
423 true
424 }
425
426 fn skip_copy_block<R: Read>(parser: &mut StatementReader<R>) {
428 while let Some(Ok(line)) = parser.next_statement() {
429 if line.trim() == "\\." {
430 break;
431 }
432 }
433 }
434
435 fn looks_like_copy_data(line: &str) -> bool {
437 let trimmed = line.trim();
438
439 if trimmed.is_empty() {
441 return false;
442 }
443
444 if trimmed == "\\." {
446 return false;
447 }
448
449 let first_char = trimmed.chars().next().unwrap_or(' ');
452
453 if matches!(
455 first_char,
456 'S' | 's'
457 | 'I'
458 | 'i'
459 | 'C'
460 | 'c'
461 | 'D'
462 | 'd'
463 | 'A'
464 | 'a'
465 | 'U'
466 | 'u'
467 | 'G'
468 | 'g'
469 | '-'
470 | '/'
471 ) {
472 let upper_prefix: String = trimmed.chars().take(7).collect::<String>().to_uppercase();
473 if upper_prefix.starts_with("SELECT")
474 || upper_prefix.starts_with("INSERT")
475 || upper_prefix.starts_with("CREATE")
476 || upper_prefix.starts_with("DROP")
477 || upper_prefix.starts_with("ALTER")
478 || upper_prefix.starts_with("UPDATE")
479 || upper_prefix.starts_with("GRANT")
480 || upper_prefix.starts_with("--")
481 || upper_prefix.starts_with("/*")
482 {
483 return false;
484 }
485 }
486
487 true
490 }
491
492 fn convert_create_table(&self, stmt: &str, dialect: SqlDialect) -> Result<String> {
494 let mut result = stmt.to_string();
495
496 result = Self::convert_identifiers(&result, dialect);
498
499 result = Self::strip_mysql_clauses(&result);
502
503 result = Self::convert_types_in_statement(&result);
505
506 if dialect == SqlDialect::Postgres {
508 result = Self::strip_postgres_syntax(&result);
509 }
510
511 if dialect == SqlDialect::Mssql {
513 result = Self::strip_mssql_syntax(&result);
514 }
515
516 if dialect == SqlDialect::Sqlite {
518 result = Self::strip_sqlite_syntax(&result);
519 }
520
521 Ok(result)
522 }
523
524 fn convert_insert(&self, stmt: &str, dialect: SqlDialect) -> Result<String> {
526 let mut result = stmt.to_string();
527
528 result = Self::convert_identifiers(&result, dialect);
530
531 if dialect == SqlDialect::MySql {
533 result = Self::convert_mysql_escapes(&result);
534 }
535
536 if dialect == SqlDialect::Postgres {
538 result = Self::strip_schema_prefix(&result);
539 }
540
541 if dialect == SqlDialect::Mssql {
543 result = Self::strip_mssql_schema_prefix(&result);
544 }
545
546 Ok(result)
547 }
548
549 fn convert_mysql_escapes(stmt: &str) -> String {
551 let mut result = String::with_capacity(stmt.len() + 100);
552 let mut chars = stmt.chars().peekable();
553 let mut in_string = false;
554
555 while let Some(c) = chars.next() {
556 if c == '\'' {
557 in_string = !in_string;
558 result.push(c);
559 } else if c == '\\' && in_string {
560 match chars.peek() {
562 Some('\'') => {
563 chars.next();
565 result.push_str("''");
566 }
567 Some('\\') => {
568 chars.next();
570 result.push('\\');
571 }
572 Some('n') => {
573 chars.next();
575 result.push('\n');
576 }
577 Some('r') => {
578 chars.next();
580 result.push('\r');
581 }
582 Some('t') => {
583 chars.next();
585 result.push('\t');
586 }
587 Some('0') => {
588 chars.next();
590 }
591 Some('"') => {
592 chars.next();
594 result.push('"');
595 }
596 _ => {
597 result.push(c);
599 }
600 }
601 } else {
602 result.push(c);
603 }
604 }
605 result
606 }
607
608 fn convert_identifiers(stmt: &str, dialect: SqlDialect) -> String {
610 match dialect {
611 SqlDialect::MySql => {
612 let mut result = String::with_capacity(stmt.len());
614 let mut in_string = false;
615 let mut in_backtick = false;
616
617 for c in stmt.chars() {
618 if c == '\'' && !in_backtick {
619 in_string = !in_string;
620 result.push(c);
621 } else if c == '`' && !in_string {
622 in_backtick = !in_backtick;
623 result.push('"');
624 } else {
625 result.push(c);
626 }
627 }
628 result
629 }
630 SqlDialect::Mssql => {
631 let mut result = String::with_capacity(stmt.len());
633 let mut in_string = false;
634 let mut in_bracket = false;
635 let mut chars = stmt.chars().peekable();
636
637 while let Some(c) = chars.next() {
638 if c == '\'' && !in_bracket {
639 in_string = !in_string;
640 result.push(c);
641 } else if c == '[' && !in_string {
642 in_bracket = true;
643 result.push('"');
644 } else if c == ']' && !in_string {
645 if chars.peek() == Some(&']') {
647 chars.next();
648 result.push(']');
649 } else {
650 in_bracket = false;
651 result.push('"');
652 }
653 } else if c == 'N' && !in_string && !in_bracket && chars.peek() == Some(&'\'') {
654 } else {
657 result.push(c);
658 }
659 }
660 result
661 }
662 _ => stmt.to_string(),
663 }
664 }
665
666 fn convert_types_in_statement(stmt: &str) -> String {
668 static RE_COLUMN_TYPE: Lazy<Regex> = Lazy::new(|| {
675 Regex::new(r#"(?i)(["'`\]\s])\s*(BIGSERIAL|SMALLSERIAL|SERIAL|BIGINT|SMALLINT|MEDIUMINT|TINYINT|INTEGER|INT|DOUBLE\s+PRECISION|DOUBLE|FLOAT|DECIMAL|NUMERIC|CHARACTER\s+VARYING|NVARCHAR|NCHAR|VARCHAR|CHAR|VARBINARY|BINARY|LONGTEXT|MEDIUMTEXT|TINYTEXT|NTEXT|TEXT|LONGBLOB|MEDIUMBLOB|TINYBLOB|IMAGE|BLOB|DATETIME2|DATETIMEOFFSET|SMALLDATETIME|DATETIME|TIMESTAMPTZ|TIMESTAMP|TIMETZ|TIME|DATE|YEAR|ENUM|SET|JSONB|JSON|UUID|UNIQUEIDENTIFIER|BYTEA|BOOLEAN|BOOL|BIT|REAL|MONEY|SMALLMONEY|INTERVAL|ROWVERSION|XML|SQL_VARIANT)\b(\s*\([^)]+\))?(\s+(?:UNSIGNED|WITH(?:OUT)?\s+TIME\s+ZONE))?"#).unwrap()
676 });
677
678 RE_COLUMN_TYPE
679 .replace_all(stmt, |caps: ®ex::Captures| {
680 let full_match = caps.get(0).unwrap().as_str();
681 let leading_char = caps.get(1).unwrap().as_str();
682 let type_part = caps.get(2).unwrap().as_str();
683 let size_part = caps.get(3).map(|m| m.as_str()).unwrap_or("");
684 let suffix = caps.get(4).map(|m| m.as_str()).unwrap_or("");
685
686 let end_pos = caps.get(0).unwrap().end();
689 let stmt_bytes = stmt.as_bytes();
690 if end_pos < stmt_bytes.len() {
691 let next_char = stmt_bytes[end_pos] as char;
692 if next_char == '"' || next_char == '\'' || next_char == '`' {
694 return full_match.to_string();
695 }
696 }
697
698 let ws_len = full_match.len()
700 - leading_char.len()
701 - type_part.len()
702 - size_part.len()
703 - suffix.len();
704 let ws = &full_match[leading_char.len()..leading_char.len() + ws_len];
705
706 let converted =
707 TypeConverter::convert(&format!("{}{}{}", type_part, size_part, suffix));
708 format!("{}{}{}", leading_char, ws, converted)
709 })
710 .to_string()
711 }
712
713 fn strip_mysql_clauses(stmt: &str) -> String {
715 let mut result = stmt.to_string();
716
717 static RE_ENGINE: Lazy<Regex> =
719 Lazy::new(|| Regex::new(r"(?i)\s*ENGINE\s*=\s*\w+").unwrap());
720 result = RE_ENGINE.replace_all(&result, "").to_string();
721
722 static RE_AUTO_INC: Lazy<Regex> =
724 Lazy::new(|| Regex::new(r"(?i)\s*AUTO_INCREMENT\s*=\s*\d+").unwrap());
725 result = RE_AUTO_INC.replace_all(&result, "").to_string();
726
727 result = result.replace(" AUTO_INCREMENT", "");
729 result = result.replace(" auto_increment", "");
730
731 static RE_CHAR_SET: Lazy<Regex> =
733 Lazy::new(|| Regex::new(r"(?i)\s*CHARACTER\s+SET\s+\w+").unwrap());
734 result = RE_CHAR_SET.replace_all(&result, "").to_string();
735
736 static RE_CHARSET: Lazy<Regex> =
738 Lazy::new(|| Regex::new(r"(?i)\s*(DEFAULT\s+)?CHARSET\s*=\s*\w+").unwrap());
739 result = RE_CHARSET.replace_all(&result, "").to_string();
740
741 static RE_COLLATE: Lazy<Regex> =
743 Lazy::new(|| Regex::new(r"(?i)\s*COLLATE\s*=?\s*\w+").unwrap());
744 result = RE_COLLATE.replace_all(&result, "").to_string();
745
746 static RE_ROW_FORMAT: Lazy<Regex> =
748 Lazy::new(|| Regex::new(r"(?i)\s*ROW_FORMAT\s*=\s*\w+").unwrap());
749 result = RE_ROW_FORMAT.replace_all(&result, "").to_string();
750
751 static RE_KEY_BLOCK: Lazy<Regex> =
753 Lazy::new(|| Regex::new(r"(?i)\s*KEY_BLOCK_SIZE\s*=\s*\d+").unwrap());
754 result = RE_KEY_BLOCK.replace_all(&result, "").to_string();
755
756 static RE_COMMENT: Lazy<Regex> =
758 Lazy::new(|| Regex::new(r"(?i)\s*COMMENT\s*=?\s*'[^']*'").unwrap());
759 result = RE_COMMENT.replace_all(&result, "").to_string();
760
761 static RE_COND_COMMENT: Lazy<Regex> = Lazy::new(|| Regex::new(r"/\*!\d+\s*|\*/").unwrap());
763 result = RE_COND_COMMENT.replace_all(&result, "").to_string();
764
765 static RE_ON_UPDATE: Lazy<Regex> =
767 Lazy::new(|| Regex::new(r"(?i)\s*ON\s+UPDATE\s+CURRENT_TIMESTAMP").unwrap());
768 result = RE_ON_UPDATE.replace_all(&result, "").to_string();
769
770 static RE_UNIQUE_KEY: Lazy<Regex> = Lazy::new(|| {
773 Regex::new(r#"(?i),?\s*UNIQUE\s+KEY\s+[`"']?\w+[`"']?\s*\([^)]+\)"#).unwrap()
774 });
775 result = RE_UNIQUE_KEY.replace_all(&result, "").to_string();
776
777 static RE_KEY_INDEX: Lazy<Regex> = Lazy::new(|| {
781 Regex::new(
782 r#"(?i)(?:,\s*|\n\s*)(?:FULLTEXT\s+|SPATIAL\s+)?KEY\s+[`"']?\w+[`"']?\s*\([^)]+\)"#,
783 )
784 .unwrap()
785 });
786 result = RE_KEY_INDEX.replace_all(&result, "").to_string();
787
788 static RE_GENERATED_COL: Lazy<Regex> = Lazy::new(|| {
792 Regex::new(r#"(?i),?\s*[`"']?\w+[`"']?\s+\w+\s+GENERATED\s+ALWAYS\s+AS\s*\((?:[^()]+|\([^()]*\))+\)\s*(?:STORED|VIRTUAL)?"#).unwrap()
793 });
794 result = RE_GENERATED_COL.replace_all(&result, "").to_string();
795
796 static RE_FK_CONSTRAINT: Lazy<Regex> = Lazy::new(|| {
800 Regex::new(r#"(?i),?\s*(?:CONSTRAINT\s+[`"']?\w+[`"']?\s+)?FOREIGN\s+KEY\s*\([^)]+\)\s*REFERENCES\s+[`"']?\w+[`"']?\s*\([^)]+\)(?:\s+ON\s+(?:DELETE|UPDATE)\s+(?:CASCADE|SET\s+NULL|SET\s+DEFAULT|NO\s+ACTION|RESTRICT))*"#).unwrap()
801 });
802 result = RE_FK_CONSTRAINT.replace_all(&result, "").to_string();
803
804 result
805 }
806
807 fn strip_postgres_syntax(stmt: &str) -> String {
809 let mut result = stmt.to_string();
810
811 result = Self::strip_schema_prefix(&result);
813
814 static RE_CAST: Lazy<Regex> = Lazy::new(|| {
816 Regex::new(r"::[a-zA-Z_][a-zA-Z0-9_]*(?:\s+[a-zA-Z_][a-zA-Z0-9_]*)*").unwrap()
817 });
818 result = RE_CAST.replace_all(&result, "").to_string();
819
820 static RE_NEXTVAL: Lazy<Regex> =
822 Lazy::new(|| Regex::new(r"(?i)\s*DEFAULT\s+nextval\s*\([^)]+\)").unwrap());
823 result = RE_NEXTVAL.replace_all(&result, "").to_string();
824
825 static RE_NOW: Lazy<Regex> =
827 Lazy::new(|| Regex::new(r"(?i)\bDEFAULT\s+now\s*\(\s*\)").unwrap());
828 result = RE_NOW
829 .replace_all(&result, "DEFAULT CURRENT_TIMESTAMP")
830 .to_string();
831
832 static RE_INHERITS: Lazy<Regex> =
834 Lazy::new(|| Regex::new(r"(?i)\s*INHERITS\s*\([^)]+\)").unwrap());
835 result = RE_INHERITS.replace_all(&result, "").to_string();
836
837 static RE_WITH: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\s*WITH\s*\([^)]+\)").unwrap());
839 result = RE_WITH.replace_all(&result, "").to_string();
840
841 result
842 }
843
844 fn strip_schema_prefix(stmt: &str) -> String {
846 static RE_SCHEMA: Lazy<Regex> =
847 Lazy::new(|| Regex::new(r#"(?i)\b(public|pg_catalog|pg_temp)\s*\.\s*"#).unwrap());
848 RE_SCHEMA.replace_all(stmt, "").to_string()
849 }
850
851 fn strip_mssql_schema_prefix(stmt: &str) -> String {
853 static RE_SCHEMA: Lazy<Regex> =
855 Lazy::new(|| Regex::new(r#"(?i)"?(dbo|master|tempdb|model|msdb)"?\s*\.\s*"#).unwrap());
856 RE_SCHEMA.replace_all(stmt, "").to_string()
857 }
858
859 fn strip_mssql_syntax(stmt: &str) -> String {
861 let mut result = Self::strip_mssql_schema_prefix(stmt);
862
863 static RE_IDENTITY_NOT_NULL: Lazy<Regex> = Lazy::new(|| {
866 Regex::new(r"(?i)\s*IDENTITY\s*\(\s*\d+\s*,\s*\d+\s*\)\s*NOT\s+NULL").unwrap()
867 });
868 result = RE_IDENTITY_NOT_NULL.replace_all(&result, "").to_string();
869
870 static RE_IDENTITY: Lazy<Regex> =
872 Lazy::new(|| Regex::new(r"(?i)\s*IDENTITY\s*\(\s*\d+\s*,\s*\d+\s*\)").unwrap());
873 result = RE_IDENTITY.replace_all(&result, "").to_string();
874
875 static RE_CLUSTERED: Lazy<Regex> =
877 Lazy::new(|| Regex::new(r"(?i)\s*(?:NON)?CLUSTERED\s*").unwrap());
878 result = RE_CLUSTERED.replace_all(&result, " ").to_string();
879
880 static RE_FILEGROUP: Lazy<Regex> =
882 Lazy::new(|| Regex::new(r#"(?i)\s*ON\s*"?PRIMARY"?"#).unwrap());
883 result = RE_FILEGROUP.replace_all(&result, "").to_string();
884
885 static RE_PK_CONSTRAINT: Lazy<Regex> = Lazy::new(|| {
887 Regex::new(r#"(?i),?\s*CONSTRAINT\s+"?\w+"?\s+PRIMARY\s+KEY\s+\([^)]+\)"#).unwrap()
888 });
889 result = RE_PK_CONSTRAINT.replace_all(&result, "").to_string();
890
891 static RE_FK_CONSTRAINT: Lazy<Regex> = Lazy::new(|| {
893 Regex::new(r#"(?i),?\s*CONSTRAINT\s+"?\w+"?\s+FOREIGN\s+KEY\s*\([^)]+\)\s*REFERENCES\s+[^\s(]+\s*\([^)]+\)"#).unwrap()
894 });
895 result = RE_FK_CONSTRAINT.replace_all(&result, "").to_string();
896
897 static RE_WITH: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\s*WITH\s*\([^)]+\)").unwrap());
899 result = RE_WITH.replace_all(&result, "").to_string();
900
901 static RE_TEXTIMAGE: Lazy<Regex> =
903 Lazy::new(|| Regex::new(r#"(?i)\s*TEXTIMAGE_ON\s*"?\w+"?"#).unwrap());
904 result = RE_TEXTIMAGE.replace_all(&result, "").to_string();
905
906 static RE_GETDATE: Lazy<Regex> =
908 Lazy::new(|| Regex::new(r"(?i)\bGETDATE\s*\(\s*\)").unwrap());
909 result = RE_GETDATE
910 .replace_all(&result, "CURRENT_TIMESTAMP")
911 .to_string();
912
913 static RE_NEWID: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bNEWID\s*\(\s*\)").unwrap());
915 result = RE_NEWID
916 .replace_all(&result, "gen_random_uuid()")
917 .to_string();
918
919 result
920 }
921
922 fn strip_sqlite_syntax(stmt: &str) -> String {
924 let mut result = stmt.to_string();
925
926 result = result.replace(" AUTOINCREMENT", "");
929 result = result.replace(" autoincrement", "");
930
931 static RE_STRICT: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\)\s*STRICT\s*;").unwrap());
936 result = RE_STRICT.replace_all(&result, ");").to_string();
937
938 static RE_WITHOUT_ROWID: Lazy<Regex> =
940 Lazy::new(|| Regex::new(r"(?i)\)\s*WITHOUT\s+ROWID\s*;").unwrap());
941 result = RE_WITHOUT_ROWID.replace_all(&result, ");").to_string();
942
943 result
944 }
945
946 fn count_insert_rows(sql: &str) -> u64 {
948 if let Some(values_pos) = sql.to_uppercase().find("VALUES") {
950 let after_values = &sql[values_pos + 6..];
951 let mut count = 0u64;
953 let mut depth = 0;
954 let mut in_string = false;
955 let mut prev_char = ' ';
956
957 for c in after_values.chars() {
958 if c == '\'' && prev_char != '\\' {
959 in_string = !in_string;
960 }
961 if !in_string {
962 if c == '(' {
963 if depth == 0 {
964 count += 1;
965 }
966 depth += 1;
967 } else if c == ')' {
968 depth -= 1;
969 }
970 }
971 prev_char = c;
972 }
973 count
974 } else {
975 1
976 }
977 }
978}
979
980struct StatementReader<R> {
982 reader: BufReader<R>,
983 dialect: SqlDialect,
984 buffer: String,
985 buffer_pos: usize,
987 eof: bool,
988 in_copy_mode: bool,
990}
991
992impl<R: Read> StatementReader<R> {
993 fn new(reader: BufReader<R>, dialect: SqlDialect) -> Self {
994 Self {
995 reader,
996 dialect,
997 buffer: String::new(),
998 buffer_pos: 0,
999 eof: false,
1000 in_copy_mode: false,
1001 }
1002 }
1003
1004 fn compact_buffer(&mut self) {
1007 if self.buffer_pos > 0 {
1008 self.buffer.drain(..self.buffer_pos);
1009 self.buffer_pos = 0;
1010 }
1011 }
1012
1013 fn remaining_buffer(&self) -> &str {
1015 &self.buffer[self.buffer_pos..]
1016 }
1017
1018 fn set_copy_mode(&mut self, enabled: bool) {
1020 self.in_copy_mode = enabled;
1021 }
1022
1023 fn strip_leading_sql_comments(s: &str) -> &str {
1025 let mut result = s.trim();
1026 loop {
1027 if result.starts_with("--") {
1029 if let Some(pos) = result.find('\n') {
1030 result = result[pos + 1..].trim();
1031 continue;
1032 } else {
1033 return ""; }
1035 }
1036 if result.starts_with("/*") {
1038 if let Some(pos) = result.find("*/") {
1039 result = result[pos + 2..].trim();
1040 continue;
1041 } else {
1042 return ""; }
1044 }
1045 break;
1046 }
1047 result
1048 }
1049
1050 fn next_statement(&mut self) -> Option<Result<String>> {
1051 if self.eof && self.remaining_buffer().is_empty() {
1052 return None;
1053 }
1054
1055 loop {
1056 if self.in_copy_mode {
1058 if let Some(line) = self.extract_copy_line() {
1059 return Some(Ok(line));
1060 }
1061 } else {
1062 if let Some(stmt) = self.extract_statement() {
1064 return Some(Ok(stmt));
1066 }
1067 }
1068
1069 if self.buffer_pos > 64 * 1024 {
1072 self.compact_buffer();
1073 }
1074
1075 let mut line = String::new();
1077 match self.reader.read_line(&mut line) {
1078 Ok(0) => {
1079 self.eof = true;
1080 self.in_copy_mode = false; let remaining = self.remaining_buffer().trim();
1082 if !remaining.is_empty() {
1083 let stmt = remaining.to_string();
1084 self.buffer.clear();
1085 self.buffer_pos = 0;
1086 return Some(Ok(stmt));
1087 }
1088 return None;
1089 }
1090 Ok(_) => {
1091 self.buffer.push_str(&line);
1092 }
1093 Err(e) => return Some(Err(e.into())),
1094 }
1095 }
1096 }
1097
1098 fn extract_copy_line(&mut self) -> Option<String> {
1100 let remaining = self.remaining_buffer();
1101 if let Some(newline_pos) = remaining.find('\n') {
1102 let line = remaining[..newline_pos].to_string();
1103 self.buffer_pos += newline_pos + 1;
1104 Some(line)
1106 } else {
1107 None
1108 }
1109 }
1110
1111 fn extract_statement(&mut self) -> Option<String> {
1112 let remaining = self.remaining_buffer();
1113 let mut in_string = false;
1114 let mut in_dollar_quote = false;
1115 let mut in_bracket = false;
1116 let mut in_line_comment = false;
1117 let mut in_block_comment = false;
1118 let mut escape_next = false;
1119 let mut chars = remaining.char_indices().peekable();
1120 let mut end_pos = None;
1121
1122 if self.dialect == SqlDialect::Mssql {
1124 if let Some(go_pos) = self.find_go_separator() {
1125 let stmt = remaining[..go_pos].to_string();
1126 let after_go = &remaining[go_pos..];
1128 if let Some(line_end) = after_go.find('\n') {
1129 self.buffer_pos += go_pos + line_end + 1;
1130 } else {
1131 self.buffer_pos = self.buffer.len();
1132 }
1133
1134 let trimmed = stmt.trim();
1135 if trimmed.is_empty()
1136 || trimmed.starts_with("--")
1137 || (trimmed.starts_with("/*") && !trimmed.contains("/*!"))
1138 {
1139 return self.extract_statement();
1140 }
1141 return Some(stmt);
1142 }
1143 }
1144
1145 while let Some((i, c)) = chars.next() {
1146 if escape_next {
1147 escape_next = false;
1148 continue;
1149 }
1150
1151 if in_line_comment {
1153 if c == '\n' {
1154 in_line_comment = false;
1155 }
1156 continue;
1157 }
1158
1159 if in_block_comment {
1161 if c == '*' && chars.peek().map(|(_, c)| *c == '/').unwrap_or(false) {
1162 chars.next();
1163 in_block_comment = false;
1164 }
1165 continue;
1166 }
1167
1168 match c {
1169 '\\' if self.dialect == SqlDialect::MySql && in_string => {
1170 escape_next = true;
1171 }
1172 '\'' if !in_dollar_quote && !in_bracket => {
1173 in_string = !in_string;
1174 }
1175 '[' if self.dialect == SqlDialect::Mssql && !in_string => {
1176 in_bracket = true;
1177 }
1178 ']' if self.dialect == SqlDialect::Mssql && !in_string => {
1179 if chars.peek().map(|(_, c)| *c == ']').unwrap_or(false) {
1181 chars.next();
1182 } else {
1183 in_bracket = false;
1184 }
1185 }
1186 '$' if self.dialect == SqlDialect::Postgres && !in_string => {
1187 if chars.peek().map(|(_, c)| *c == '$').unwrap_or(false) {
1189 in_dollar_quote = !in_dollar_quote;
1190 chars.next();
1191 }
1192 }
1193 '-' if !in_string && !in_dollar_quote && !in_bracket => {
1194 if chars.peek().map(|(_, c)| *c == '-').unwrap_or(false) {
1196 chars.next();
1197 in_line_comment = true;
1198 }
1199 }
1200 '/' if !in_string && !in_dollar_quote && !in_bracket => {
1201 if chars.peek().map(|(_, c)| *c == '*').unwrap_or(false) {
1203 chars.next();
1204 in_block_comment = true;
1205 }
1206 }
1207 ';' if !in_string && !in_dollar_quote && !in_bracket => {
1208 end_pos = Some(i + 1);
1209 break;
1210 }
1211 _ => {}
1212 }
1213 }
1214
1215 if let Some(pos) = end_pos {
1216 let stmt = remaining[..pos].to_string();
1217 let after_stmt = &remaining[pos..];
1219 let trimmed_len = after_stmt.len() - after_stmt.trim_start().len();
1220 self.buffer_pos += pos + trimmed_len;
1221
1222 let trimmed = stmt.trim();
1224
1225 let stripped = Self::strip_leading_sql_comments(trimmed);
1227 if stripped.is_empty() {
1228 return self.extract_statement();
1229 }
1230
1231 let trimmed = stripped;
1233
1234 if self.dialect == SqlDialect::Postgres {
1237 let upper = trimmed.to_uppercase();
1238 if upper.ends_with("FROM STDIN;") && upper.contains("COPY ") {
1239 self.in_copy_mode = true;
1240 }
1241 }
1242
1243 Some(stmt)
1244 } else {
1245 None
1246 }
1247 }
1248
1249 fn find_go_separator(&self) -> Option<usize> {
1251 let remaining = self.remaining_buffer();
1252 let mut in_string = false;
1253 let mut in_bracket = false;
1254 let mut line_start = 0;
1255
1256 for (i, c) in remaining.char_indices() {
1257 if c == '\'' && !in_bracket {
1258 in_string = !in_string;
1259 } else if c == '[' && !in_string {
1260 in_bracket = true;
1261 } else if c == ']' && !in_string {
1262 in_bracket = false;
1263 } else if c == '\n' {
1264 line_start = i + 1;
1265 } else if !in_string && !in_bracket && i == line_start {
1266 let rest = &remaining[i..];
1268 if rest.len() >= 2 {
1269 let word = &rest[..2.min(rest.len())];
1270 if word.eq_ignore_ascii_case("GO") {
1271 let after_go = if rest.len() > 2 {
1273 rest.chars().nth(2)
1274 } else {
1275 None
1276 };
1277 if after_go.is_none()
1278 || after_go == Some('\n')
1279 || after_go == Some('\r')
1280 || after_go == Some(' ')
1281 || after_go.unwrap().is_ascii_digit()
1282 {
1283 return Some(i);
1284 }
1285 }
1286 }
1287 }
1288 }
1289 None
1290 }
1291}
1292
1293#[cfg(test)]
1294mod tests {
1295 use super::*;
1296
1297 #[test]
1298 fn test_count_insert_rows() {
1299 assert_eq!(
1300 DumpLoader::count_insert_rows("INSERT INTO t VALUES (1, 'a')"),
1301 1
1302 );
1303 assert_eq!(
1304 DumpLoader::count_insert_rows("INSERT INTO t VALUES (1, 'a'), (2, 'b'), (3, 'c')"),
1305 3
1306 );
1307 assert_eq!(
1308 DumpLoader::count_insert_rows("INSERT INTO t VALUES (1, '(test)')"),
1309 1
1310 );
1311 }
1312
1313 #[test]
1314 fn test_strip_mysql_clauses() {
1315 let sql = "CREATE TABLE t (id INT) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";
1316 let result = DumpLoader::strip_mysql_clauses(sql);
1317 assert!(!result.contains("ENGINE"));
1318 assert!(!result.contains("CHARSET"));
1319 }
1320
1321 #[test]
1322 fn test_convert_identifiers() {
1323 let sql = "INSERT INTO `users` (`id`, `name`) VALUES (1, 'test')";
1324 let result = DumpLoader::convert_identifiers(sql, SqlDialect::MySql);
1325 assert_eq!(
1326 result,
1327 "INSERT INTO \"users\" (\"id\", \"name\") VALUES (1, 'test')"
1328 );
1329 }
1330
1331 #[test]
1332 fn test_looks_like_copy_data() {
1333 assert!(DumpLoader::looks_like_copy_data("1\tAlice\t2024-01-01"));
1334 assert!(!DumpLoader::looks_like_copy_data("SELECT * FROM users"));
1335 assert!(!DumpLoader::looks_like_copy_data("INSERT INTO t VALUES"));
1336 }
1337
1338 #[test]
1339 fn test_strip_mssql_syntax() {
1340 let sql = r#"CREATE TABLE "users" (
1341 "id" INTEGER NOT NULL,
1342 "email" VARCHAR(255) NOT NULL
1343)"#;
1344 let result = DumpLoader::strip_mssql_syntax(sql);
1346 assert!(!result.contains("IDENTITY"), "IDENTITY should be stripped");
1347
1348 let sql_with_identity = r#"CREATE TABLE "users" (
1350 "id" INTEGER IDENTITY(1,1) NOT NULL,
1351 "email" VARCHAR(255) NOT NULL
1352)"#;
1353 let result2 = DumpLoader::strip_mssql_syntax(sql_with_identity);
1354 assert!(
1355 !result2.contains("IDENTITY"),
1356 "IDENTITY should be stripped: {}",
1357 result2
1358 );
1359 assert!(
1361 !result2.contains("IDENTITY(1,1) NOT NULL"),
1362 "Should strip full IDENTITY NOT NULL"
1363 );
1364 }
1365
1366 #[test]
1367 fn test_convert_mssql_identifiers() {
1368 let sql = "INSERT INTO [dbo].[users] ([id], [name]) VALUES (1, N'test')";
1369 let result = DumpLoader::convert_identifiers(sql, SqlDialect::Mssql);
1370 assert_eq!(
1371 result,
1372 "INSERT INTO \"dbo\".\"users\" (\"id\", \"name\") VALUES (1, 'test')"
1373 );
1374 }
1375}