1use super::batch::{flush_batch, BatchManager, MAX_ROWS_PER_BATCH};
4use super::types::TypeConverter;
5use super::{ImportStats, QueryConfig};
6use crate::convert::copy_to_insert::{
7 copy_rows_to_insert, parse_copy_data, parse_copy_header, CopyHeader, CopyValue,
8 MAX_ROWS_PER_INSERT,
9};
10use crate::parser::{
11 detect_dialect_from_file, determine_buffer_size, parse_insert_for_bulk, Parser, SqlDialect,
12 StatementType,
13};
14use anyhow::{Context, Result};
15use duckdb::Connection;
16use indicatif::{ProgressBar, ProgressStyle};
17use once_cell::sync::Lazy;
18use regex::Regex;
19use std::io::Read;
20use std::path::Path;
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 self.load_statements(
86 reader,
87 determine_buffer_size(file_size),
88 dialect,
89 &mut stats,
90 )?;
91
92 if let Some(pb) = progress_bar {
93 pb.finish_with_message("Import complete");
94 }
95
96 stats.duration_secs = start.elapsed().as_secs_f64();
97 Ok(stats)
98 }
99
100 fn load_statements<R: Read>(
102 &self,
103 reader: R,
104 buffer_size: usize,
105 dialect: SqlDialect,
106 stats: &mut ImportStats,
107 ) -> Result<()> {
108 let mut parser = Parser::with_dialect(reader, buffer_size, dialect);
109
110 let mut pending_copy: Option<CopyHeader> = None;
116 let mut skipping_copy_data = false;
117
118 let mut failed_tables: std::collections::HashSet<String> = std::collections::HashSet::new();
120
121 let mut batch_mgr = BatchManager::new(MAX_ROWS_PER_BATCH);
123
124 while let Some(raw) = parser.read_statement()? {
125 if let Some(header) = pending_copy.take() {
129 self.process_copy_batch(&header, &raw, stats, &mut failed_tables);
136 continue;
137 }
138 if skipping_copy_data {
139 skipping_copy_data = false;
140 stats.statements_skipped += 1;
141 continue;
142 }
143
144 let (stmt_type, table_name) =
145 Parser::<&[u8]>::parse_statement_with_dialect(&raw, dialect);
146
147 if let Some(ref tables) = self.config.tables {
151 if !table_name.is_empty()
152 && !tables.iter().any(|t| t.eq_ignore_ascii_case(&table_name))
153 {
154 skipping_copy_data = parser.in_copy_data();
155 continue;
156 }
157 }
158
159 let stmt = String::from_utf8_lossy(&raw);
160
161 match stmt_type {
162 StatementType::CreateTable => {
163 let duckdb_sql = self.convert_create_table(&stmt, dialect)?;
164 match self.conn.execute(&duckdb_sql, []) {
165 Ok(_) => stats.tables_created += 1,
166 Err(e) => {
167 stats
168 .warnings
169 .push(format!("Failed to create table {}: {}", table_name, e));
170 stats.statements_skipped += 1;
171 }
172 }
173 }
174 StatementType::Insert => {
175 if !self.try_queue_for_bulk(
177 &stmt,
178 dialect,
179 &mut batch_mgr,
180 stats,
181 &mut failed_tables,
182 ) {
183 let duckdb_sql = self.convert_insert(&stmt, dialect)?;
185 match self.conn.execute(&duckdb_sql, []) {
186 Ok(_) => {
187 stats.insert_statements += 1;
188 stats.rows_inserted += Self::count_insert_rows(&duckdb_sql);
189 }
190 Err(e) => {
191 stats
192 .warnings
193 .push(format!("Failed INSERT for {}: {}", table_name, e));
194 stats.statements_skipped += 1;
195 }
196 }
197 }
198
199 for mut batch in batch_mgr.get_ready_batches() {
201 flush_batch(self.conn, &mut batch, stats, &mut failed_tables)?;
202 }
203 }
204 StatementType::Copy => {
205 let has_data_block = parser.in_copy_data();
209 match parse_copy_header(&stmt) {
210 Some(header) if has_data_block => {
211 if !failed_tables.contains(&header.table)
215 && !self.table_exists(&header.table)
216 {
217 failed_tables.insert(header.table.clone());
218 if stats.warnings.len() < 100 {
219 stats.warnings.push(format!(
220 "Skipping COPY for non-existent table {}",
221 header.table
222 ));
223 }
224 }
225
226 if failed_tables.contains(&header.table) {
227 skipping_copy_data = true;
228 } else {
229 pending_copy = Some(header);
230 }
231 }
232 _ => skipping_copy_data = has_data_block,
235 }
236 }
237 StatementType::CreateIndex => {
238 stats.statements_skipped += 1;
240 }
241 _ => {
242 stats.statements_skipped += 1;
244 }
245 }
246 }
247
248 for mut batch in batch_mgr.drain_all() {
250 flush_batch(self.conn, &mut batch, stats, &mut failed_tables)?;
251 }
252
253 Ok(())
254 }
255
256 fn process_copy_batch(
258 &self,
259 header: &CopyHeader,
260 batch_data: &[u8],
261 stats: &mut ImportStats,
262 failed_tables: &mut std::collections::HashSet<String>,
263 ) {
264 if batch_data.is_empty() {
265 return;
266 }
267
268 if failed_tables.contains(&header.table) {
270 return;
271 }
272
273 let rows = parse_copy_data(batch_data);
274 for chunk in rows.chunks(MAX_ROWS_PER_INSERT) {
275 let insert = copy_rows_to_insert(header, chunk, SqlDialect::Postgres);
276 let insert_sql = String::from_utf8_lossy(&insert);
277 match self.conn.execute(&insert_sql, []) {
278 Ok(_) => {
279 stats.rows_inserted += chunk.len() as u64;
280 }
281 Err(e) => {
282 if Self::is_missing_table_error(&e) {
284 Self::mark_missing_copy_table(header, stats, failed_tables);
285 return; }
287
288 if chunk.len() > 1 {
292 self.process_copy_rows(header, chunk, stats, failed_tables);
293 } else {
294 Self::record_copy_insert_error(header, &e, stats);
295 }
296 }
297 }
298 }
299 }
300
301 fn process_copy_rows(
302 &self,
303 header: &CopyHeader,
304 rows: &[Vec<CopyValue>],
305 stats: &mut ImportStats,
306 failed_tables: &mut std::collections::HashSet<String>,
307 ) {
308 for row in rows {
309 let insert =
310 copy_rows_to_insert(header, std::slice::from_ref(row), SqlDialect::Postgres);
311 let insert_sql = String::from_utf8_lossy(&insert);
312
313 match self.conn.execute(&insert_sql, []) {
314 Ok(_) => stats.rows_inserted += 1,
315 Err(e) if Self::is_missing_table_error(&e) => {
316 Self::mark_missing_copy_table(header, stats, failed_tables);
317 return;
318 }
319 Err(e) => Self::record_copy_insert_error(header, &e, stats),
320 }
321 }
322 }
323
324 fn is_missing_table_error(error: &duckdb::Error) -> bool {
327 matches!(
328 error,
329 duckdb::Error::DuckDBFailure(_, Some(message))
330 if message.starts_with("Catalog Error: Table with name ")
331 )
332 }
333
334 fn mark_missing_copy_table(
335 header: &CopyHeader,
336 stats: &mut ImportStats,
337 failed_tables: &mut std::collections::HashSet<String>,
338 ) {
339 failed_tables.insert(header.table.clone());
340 if stats.warnings.len() < 100 {
341 stats.warnings.push(format!(
342 "Table {} does not exist, skipping COPY data",
343 header.table
344 ));
345 }
346 }
347
348 fn record_copy_insert_error(
349 header: &CopyHeader,
350 error: &duckdb::Error,
351 stats: &mut ImportStats,
352 ) {
353 if stats.warnings.len() < 100 {
354 stats.warnings.push(format!(
355 "Failed to insert COPY data for {}: {}",
356 header.table, error
357 ));
358 }
359 stats.statements_skipped += 1;
360 }
361
362 fn table_exists(&self, table: &str) -> bool {
364 let query = "SELECT 1 FROM information_schema.tables WHERE table_name = ? LIMIT 1";
365 match self.conn.prepare(query) {
366 Ok(mut stmt) => stmt.exists([table]).unwrap_or(false),
367 Err(_) => false,
368 }
369 }
370
371 fn has_unsupported_insert_clause(stmt: &str) -> bool {
383 const HEAD_SCAN_LIMIT: usize = 64 * 1024;
384 const TAIL_SCAN: usize = 8 * 1024;
387
388 let bytes = stmt.as_bytes();
389 let head_window = &bytes[..bytes.len().min(HEAD_SCAN_LIMIT)];
390
391 let values_end = match memchr::memmem::find_iter(head_window, b"VALUES")
392 .chain(memchr::memmem::find_iter(head_window, b"values"))
393 .min()
394 {
395 Some(p) => p + b"VALUES".len(),
396 None => {
397 let up = head_window.to_ascii_uppercase();
400 match memchr::memmem::find(&up, b"VALUES") {
401 Some(p) => p + b"VALUES".len(),
402 None => return true,
403 }
404 }
405 };
406
407 let head = bytes[..values_end].to_ascii_uppercase();
408 if [&b"REPLACE"[..], b"IGNORE", b"SELECT"]
409 .iter()
410 .any(|kw| memchr::memmem::find(&head, kw).is_some())
411 {
412 return true;
413 }
414
415 let tail_start = bytes.len().saturating_sub(TAIL_SCAN).max(values_end);
416 let tail = bytes[tail_start..].to_ascii_uppercase();
417 [&b"ON DUPLICATE KEY"[..], b"ON CONFLICT", b"RETURNING"]
418 .iter()
419 .any(|kw| memchr::memmem::find(&tail, kw).is_some())
420 }
421
422 fn try_queue_for_bulk(
425 &self,
426 stmt: &str,
427 dialect: SqlDialect,
428 batch_mgr: &mut BatchManager,
429 stats: &mut ImportStats,
430 failed_tables: &mut std::collections::HashSet<String>,
431 ) -> bool {
432 if Self::has_unsupported_insert_clause(stmt) {
434 return false;
435 }
436
437 let parsed = match parse_insert_for_bulk(stmt.as_bytes(), dialect) {
439 Ok(p) => p,
440 Err(_) => return false, };
442
443 if failed_tables.contains(&parsed.table) {
445 return true; }
447
448 if parsed.rows.is_empty() {
450 return false;
451 }
452
453 let duckdb_sql = match self.convert_insert(stmt, dialect) {
455 Ok(sql) => sql,
456 Err(_) => return false,
457 };
458
459 if let Some(mut batch) = batch_mgr.queue_insert(
461 &parsed.table,
462 parsed.columns,
463 parsed.rows,
464 duckdb_sql,
465 dialect,
466 ) {
467 if let Err(e) = flush_batch(self.conn, &mut batch, stats, failed_tables) {
469 if stats.warnings.len() < 100 {
470 stats.warnings.push(format!("Batch flush error: {}", e));
471 }
472 }
473 }
474
475 true
476 }
477
478 fn convert_create_table(&self, stmt: &str, dialect: SqlDialect) -> Result<String> {
480 let mut result = stmt.to_string();
481
482 result = Self::convert_identifiers(&result, dialect);
484
485 result = Self::strip_mysql_clauses(&result);
488
489 result = Self::convert_types_in_statement(&result);
491
492 if dialect == SqlDialect::Postgres {
494 result = Self::strip_postgres_syntax(&result);
495 }
496
497 if dialect == SqlDialect::Mssql {
499 result = Self::strip_mssql_syntax(&result);
500 }
501
502 if dialect == SqlDialect::Sqlite {
504 result = Self::strip_sqlite_syntax(&result);
505 }
506
507 Ok(result)
508 }
509
510 fn convert_insert(&self, stmt: &str, dialect: SqlDialect) -> Result<String> {
512 let mut result = stmt.to_string();
513
514 result = Self::convert_identifiers(&result, dialect);
516
517 if dialect == SqlDialect::MySql {
519 result = Self::convert_mysql_escapes(&result);
520 }
521
522 if dialect == SqlDialect::Postgres {
524 result = Self::strip_schema_prefix(&result);
525 }
526
527 if dialect == SqlDialect::Mssql {
529 result = Self::strip_mssql_schema_prefix(&result);
530 }
531
532 Ok(result)
533 }
534
535 fn convert_mysql_escapes(stmt: &str) -> String {
537 let mut result = String::with_capacity(stmt.len() + 100);
538 let mut chars = stmt.chars().peekable();
539 let mut in_string = false;
540
541 while let Some(c) = chars.next() {
542 if c == '\'' {
543 in_string = !in_string;
544 result.push(c);
545 } else if c == '\\' && in_string {
546 match chars.peek() {
548 Some('\'') => {
549 chars.next();
551 result.push_str("''");
552 }
553 Some('\\') => {
554 chars.next();
556 result.push('\\');
557 }
558 Some('n') => {
559 chars.next();
561 result.push('\n');
562 }
563 Some('r') => {
564 chars.next();
566 result.push('\r');
567 }
568 Some('t') => {
569 chars.next();
571 result.push('\t');
572 }
573 Some('0') => {
574 chars.next();
576 }
577 Some('"') => {
578 chars.next();
580 result.push('"');
581 }
582 _ => {
583 result.push(c);
585 }
586 }
587 } else {
588 result.push(c);
589 }
590 }
591 result
592 }
593
594 fn convert_identifiers(stmt: &str, dialect: SqlDialect) -> String {
596 match dialect {
597 SqlDialect::MySql => {
598 let mut result = String::with_capacity(stmt.len());
600 let mut in_string = false;
601 let mut in_backtick = false;
602
603 for c in stmt.chars() {
604 if c == '\'' && !in_backtick {
605 in_string = !in_string;
606 result.push(c);
607 } else if c == '`' && !in_string {
608 in_backtick = !in_backtick;
609 result.push('"');
610 } else {
611 result.push(c);
612 }
613 }
614 result
615 }
616 SqlDialect::Mssql => {
617 let mut result = String::with_capacity(stmt.len());
619 let mut in_string = false;
620 let mut in_bracket = false;
621 let mut chars = stmt.chars().peekable();
622
623 while let Some(c) = chars.next() {
624 if c == '\'' && !in_bracket {
625 in_string = !in_string;
626 result.push(c);
627 } else if c == '[' && !in_string {
628 in_bracket = true;
629 result.push('"');
630 } else if c == ']' && !in_string {
631 if chars.peek() == Some(&']') {
633 chars.next();
634 result.push(']');
635 } else {
636 in_bracket = false;
637 result.push('"');
638 }
639 } else if c == 'N' && !in_string && !in_bracket && chars.peek() == Some(&'\'') {
640 } else {
643 result.push(c);
644 }
645 }
646 result
647 }
648 _ => stmt.to_string(),
649 }
650 }
651
652 fn convert_types_in_statement(stmt: &str) -> String {
654 static RE_COLUMN_TYPE: Lazy<Regex> = Lazy::new(|| {
661 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()
662 });
663
664 RE_COLUMN_TYPE
665 .replace_all(stmt, |caps: ®ex::Captures| {
666 let full_match = caps.get(0).unwrap().as_str();
667 let leading_char = caps.get(1).unwrap().as_str();
668 let type_part = caps.get(2).unwrap().as_str();
669 let size_part = caps.get(3).map(|m| m.as_str()).unwrap_or("");
670 let suffix = caps.get(4).map(|m| m.as_str()).unwrap_or("");
671
672 let end_pos = caps.get(0).unwrap().end();
675 let stmt_bytes = stmt.as_bytes();
676 if end_pos < stmt_bytes.len() {
677 let next_char = stmt_bytes[end_pos] as char;
678 if next_char == '"' || next_char == '\'' || next_char == '`' {
680 return full_match.to_string();
681 }
682 }
683
684 let ws_len = full_match.len()
686 - leading_char.len()
687 - type_part.len()
688 - size_part.len()
689 - suffix.len();
690 let ws = &full_match[leading_char.len()..leading_char.len() + ws_len];
691
692 let converted =
693 TypeConverter::convert(&format!("{}{}{}", type_part, size_part, suffix));
694 format!("{}{}{}", leading_char, ws, converted)
695 })
696 .to_string()
697 }
698
699 fn strip_mysql_clauses(stmt: &str) -> String {
701 let mut result = stmt.to_string();
702
703 static RE_ENGINE: Lazy<Regex> =
705 Lazy::new(|| Regex::new(r"(?i)\s*ENGINE\s*=\s*\w+").unwrap());
706 result = RE_ENGINE.replace_all(&result, "").to_string();
707
708 static RE_AUTO_INC: Lazy<Regex> =
710 Lazy::new(|| Regex::new(r"(?i)\s*AUTO_INCREMENT\s*=\s*\d+").unwrap());
711 result = RE_AUTO_INC.replace_all(&result, "").to_string();
712
713 result = result.replace(" AUTO_INCREMENT", "");
715 result = result.replace(" auto_increment", "");
716
717 static RE_CHAR_SET: Lazy<Regex> =
719 Lazy::new(|| Regex::new(r"(?i)\s*CHARACTER\s+SET\s+\w+").unwrap());
720 result = RE_CHAR_SET.replace_all(&result, "").to_string();
721
722 static RE_CHARSET: Lazy<Regex> =
724 Lazy::new(|| Regex::new(r"(?i)\s*(DEFAULT\s+)?CHARSET\s*=\s*\w+").unwrap());
725 result = RE_CHARSET.replace_all(&result, "").to_string();
726
727 static RE_COLLATE: Lazy<Regex> =
729 Lazy::new(|| Regex::new(r"(?i)\s*COLLATE\s*=?\s*\w+").unwrap());
730 result = RE_COLLATE.replace_all(&result, "").to_string();
731
732 static RE_ROW_FORMAT: Lazy<Regex> =
734 Lazy::new(|| Regex::new(r"(?i)\s*ROW_FORMAT\s*=\s*\w+").unwrap());
735 result = RE_ROW_FORMAT.replace_all(&result, "").to_string();
736
737 static RE_KEY_BLOCK: Lazy<Regex> =
739 Lazy::new(|| Regex::new(r"(?i)\s*KEY_BLOCK_SIZE\s*=\s*\d+").unwrap());
740 result = RE_KEY_BLOCK.replace_all(&result, "").to_string();
741
742 static RE_COMMENT: Lazy<Regex> =
744 Lazy::new(|| Regex::new(r"(?i)\s*COMMENT\s*=?\s*'[^']*'").unwrap());
745 result = RE_COMMENT.replace_all(&result, "").to_string();
746
747 static RE_COND_COMMENT: Lazy<Regex> = Lazy::new(|| Regex::new(r"/\*!\d+\s*|\*/").unwrap());
749 result = RE_COND_COMMENT.replace_all(&result, "").to_string();
750
751 static RE_ON_UPDATE: Lazy<Regex> =
753 Lazy::new(|| Regex::new(r"(?i)\s*ON\s+UPDATE\s+CURRENT_TIMESTAMP").unwrap());
754 result = RE_ON_UPDATE.replace_all(&result, "").to_string();
755
756 static RE_UNIQUE_KEY: Lazy<Regex> = Lazy::new(|| {
759 Regex::new(r#"(?i),?\s*UNIQUE\s+KEY\s+[`"']?\w+[`"']?\s*\([^)]+\)"#).unwrap()
760 });
761 result = RE_UNIQUE_KEY.replace_all(&result, "").to_string();
762
763 static RE_KEY_INDEX: Lazy<Regex> = Lazy::new(|| {
767 Regex::new(
768 r#"(?i)(?:,\s*|\n\s*)(?:FULLTEXT\s+|SPATIAL\s+)?KEY\s+[`"']?\w+[`"']?\s*\([^)]+\)"#,
769 )
770 .unwrap()
771 });
772 result = RE_KEY_INDEX.replace_all(&result, "").to_string();
773
774 static RE_GENERATED_COL: Lazy<Regex> = Lazy::new(|| {
778 Regex::new(r#"(?i),?\s*[`"']?\w+[`"']?\s+\w+\s+GENERATED\s+ALWAYS\s+AS\s*\((?:[^()]+|\([^()]*\))+\)\s*(?:STORED|VIRTUAL)?"#).unwrap()
779 });
780 result = RE_GENERATED_COL.replace_all(&result, "").to_string();
781
782 static RE_FK_CONSTRAINT: Lazy<Regex> = Lazy::new(|| {
786 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()
787 });
788 result = RE_FK_CONSTRAINT.replace_all(&result, "").to_string();
789
790 result
791 }
792
793 fn strip_postgres_syntax(stmt: &str) -> String {
795 let mut result = stmt.to_string();
796
797 result = Self::strip_schema_prefix(&result);
799
800 static RE_CAST: Lazy<Regex> = Lazy::new(|| {
802 Regex::new(r"::[a-zA-Z_][a-zA-Z0-9_]*(?:\s+[a-zA-Z_][a-zA-Z0-9_]*)*").unwrap()
803 });
804 result = RE_CAST.replace_all(&result, "").to_string();
805
806 static RE_NEXTVAL: Lazy<Regex> =
808 Lazy::new(|| Regex::new(r"(?i)\s*DEFAULT\s+nextval\s*\([^)]+\)").unwrap());
809 result = RE_NEXTVAL.replace_all(&result, "").to_string();
810
811 static RE_NOW: Lazy<Regex> =
813 Lazy::new(|| Regex::new(r"(?i)\bDEFAULT\s+now\s*\(\s*\)").unwrap());
814 result = RE_NOW
815 .replace_all(&result, "DEFAULT CURRENT_TIMESTAMP")
816 .to_string();
817
818 static RE_INHERITS: Lazy<Regex> =
820 Lazy::new(|| Regex::new(r"(?i)\s*INHERITS\s*\([^)]+\)").unwrap());
821 result = RE_INHERITS.replace_all(&result, "").to_string();
822
823 static RE_WITH: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\s*WITH\s*\([^)]+\)").unwrap());
825 result = RE_WITH.replace_all(&result, "").to_string();
826
827 result
828 }
829
830 fn strip_schema_prefix(stmt: &str) -> String {
832 static RE_SCHEMA: Lazy<Regex> =
833 Lazy::new(|| Regex::new(r#"(?i)\b(public|pg_catalog|pg_temp)\s*\.\s*"#).unwrap());
834 RE_SCHEMA.replace_all(stmt, "").to_string()
835 }
836
837 fn strip_mssql_schema_prefix(stmt: &str) -> String {
839 static RE_SCHEMA: Lazy<Regex> =
841 Lazy::new(|| Regex::new(r#"(?i)"?(dbo|master|tempdb|model|msdb)"?\s*\.\s*"#).unwrap());
842 RE_SCHEMA.replace_all(stmt, "").to_string()
843 }
844
845 fn strip_mssql_syntax(stmt: &str) -> String {
847 let mut result = Self::strip_mssql_schema_prefix(stmt);
848
849 static RE_IDENTITY_NOT_NULL: Lazy<Regex> = Lazy::new(|| {
852 Regex::new(r"(?i)\s*IDENTITY\s*\(\s*\d+\s*,\s*\d+\s*\)\s*NOT\s+NULL").unwrap()
853 });
854 result = RE_IDENTITY_NOT_NULL.replace_all(&result, "").to_string();
855
856 static RE_IDENTITY: Lazy<Regex> =
858 Lazy::new(|| Regex::new(r"(?i)\s*IDENTITY\s*\(\s*\d+\s*,\s*\d+\s*\)").unwrap());
859 result = RE_IDENTITY.replace_all(&result, "").to_string();
860
861 static RE_CLUSTERED: Lazy<Regex> =
863 Lazy::new(|| Regex::new(r"(?i)\s*(?:NON)?CLUSTERED\s*").unwrap());
864 result = RE_CLUSTERED.replace_all(&result, " ").to_string();
865
866 static RE_FILEGROUP: Lazy<Regex> =
868 Lazy::new(|| Regex::new(r#"(?i)\s*ON\s*"?PRIMARY"?"#).unwrap());
869 result = RE_FILEGROUP.replace_all(&result, "").to_string();
870
871 static RE_PK_CONSTRAINT: Lazy<Regex> = Lazy::new(|| {
873 Regex::new(r#"(?i),?\s*CONSTRAINT\s+"?\w+"?\s+PRIMARY\s+KEY\s+\([^)]+\)"#).unwrap()
874 });
875 result = RE_PK_CONSTRAINT.replace_all(&result, "").to_string();
876
877 static RE_FK_CONSTRAINT: Lazy<Regex> = Lazy::new(|| {
879 Regex::new(r#"(?i),?\s*CONSTRAINT\s+"?\w+"?\s+FOREIGN\s+KEY\s*\([^)]+\)\s*REFERENCES\s+[^\s(]+\s*\([^)]+\)"#).unwrap()
880 });
881 result = RE_FK_CONSTRAINT.replace_all(&result, "").to_string();
882
883 static RE_WITH: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\s*WITH\s*\([^)]+\)").unwrap());
885 result = RE_WITH.replace_all(&result, "").to_string();
886
887 static RE_TEXTIMAGE: Lazy<Regex> =
889 Lazy::new(|| Regex::new(r#"(?i)\s*TEXTIMAGE_ON\s*"?\w+"?"#).unwrap());
890 result = RE_TEXTIMAGE.replace_all(&result, "").to_string();
891
892 static RE_GETDATE: Lazy<Regex> =
894 Lazy::new(|| Regex::new(r"(?i)\bGETDATE\s*\(\s*\)").unwrap());
895 result = RE_GETDATE
896 .replace_all(&result, "CURRENT_TIMESTAMP")
897 .to_string();
898
899 static RE_NEWID: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bNEWID\s*\(\s*\)").unwrap());
901 result = RE_NEWID
902 .replace_all(&result, "gen_random_uuid()")
903 .to_string();
904
905 result
906 }
907
908 fn strip_sqlite_syntax(stmt: &str) -> String {
910 let mut result = stmt.to_string();
911
912 result = result.replace(" AUTOINCREMENT", "");
915 result = result.replace(" autoincrement", "");
916
917 static RE_STRICT: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\)\s*STRICT\s*;").unwrap());
922 result = RE_STRICT.replace_all(&result, ");").to_string();
923
924 static RE_WITHOUT_ROWID: Lazy<Regex> =
926 Lazy::new(|| Regex::new(r"(?i)\)\s*WITHOUT\s+ROWID\s*;").unwrap());
927 result = RE_WITHOUT_ROWID.replace_all(&result, ");").to_string();
928
929 result
930 }
931
932 fn count_insert_rows(sql: &str) -> u64 {
934 if let Some(values_pos) = sql.to_uppercase().find("VALUES") {
936 let after_values = &sql[values_pos + 6..];
937 let mut count = 0u64;
939 let mut depth = 0;
940 let mut in_string = false;
941 let mut prev_char = ' ';
942
943 for c in after_values.chars() {
944 if c == '\'' && prev_char != '\\' {
945 in_string = !in_string;
946 }
947 if !in_string {
948 if c == '(' {
949 if depth == 0 {
950 count += 1;
951 }
952 depth += 1;
953 } else if c == ')' {
954 depth -= 1;
955 }
956 }
957 prev_char = c;
958 }
959 count
960 } else {
961 1
962 }
963 }
964}
965
966#[cfg(test)]
967mod tests {
968 use super::*;
969
970 #[test]
971 fn unsupported_clause_check_ignores_row_data() {
972 assert!(!DumpLoader::has_unsupported_insert_clause(
976 "INSERT INTO `t` (`a`) VALUES ('https://x.test/?q=select'),('replace me'),('ignore')"
977 ));
978 assert!(!DumpLoader::has_unsupported_insert_clause(
979 "INSERT INTO `t` VALUES (1,'plain')"
980 ));
981 }
982
983 #[test]
984 fn unsupported_clause_check_still_catches_real_clauses() {
985 assert!(DumpLoader::has_unsupported_insert_clause(
986 "INSERT IGNORE INTO `t` VALUES (1)"
987 ));
988 assert!(DumpLoader::has_unsupported_insert_clause(
989 "REPLACE INTO `t` VALUES (1)"
990 ));
991 assert!(DumpLoader::has_unsupported_insert_clause(
992 "INSERT INTO `t` SELECT * FROM `u`"
993 ));
994 assert!(DumpLoader::has_unsupported_insert_clause(
995 "INSERT INTO `t` VALUES (1) ON DUPLICATE KEY UPDATE `a` = 2"
996 ));
997 assert!(DumpLoader::has_unsupported_insert_clause(
998 "INSERT INTO `t` VALUES (1) ON CONFLICT DO NOTHING"
999 ));
1000 assert!(DumpLoader::has_unsupported_insert_clause(
1001 "INSERT INTO `t` VALUES (1) RETURNING `id`"
1002 ));
1003 assert!(DumpLoader::has_unsupported_insert_clause(
1005 "insert into `t` values (1) on duplicate key update `a` = 2"
1006 ));
1007 assert!(DumpLoader::has_unsupported_insert_clause(
1008 "Insert Into `t` Values (1) Returning `id`"
1009 ));
1010 }
1011
1012 #[test]
1013 fn test_count_insert_rows() {
1014 assert_eq!(
1015 DumpLoader::count_insert_rows("INSERT INTO t VALUES (1, 'a')"),
1016 1
1017 );
1018 assert_eq!(
1019 DumpLoader::count_insert_rows("INSERT INTO t VALUES (1, 'a'), (2, 'b'), (3, 'c')"),
1020 3
1021 );
1022 assert_eq!(
1023 DumpLoader::count_insert_rows("INSERT INTO t VALUES (1, '(test)')"),
1024 1
1025 );
1026 }
1027
1028 #[test]
1029 fn test_strip_mysql_clauses() {
1030 let sql = "CREATE TABLE t (id INT) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";
1031 let result = DumpLoader::strip_mysql_clauses(sql);
1032 assert!(!result.contains("ENGINE"));
1033 assert!(!result.contains("CHARSET"));
1034 }
1035
1036 #[test]
1037 fn test_convert_identifiers() {
1038 let sql = "INSERT INTO `users` (`id`, `name`) VALUES (1, 'test')";
1039 let result = DumpLoader::convert_identifiers(sql, SqlDialect::MySql);
1040 assert_eq!(
1041 result,
1042 "INSERT INTO \"users\" (\"id\", \"name\") VALUES (1, 'test')"
1043 );
1044 }
1045
1046 #[test]
1047 fn test_strip_mssql_syntax() {
1048 let sql = r#"CREATE TABLE "users" (
1049 "id" INTEGER NOT NULL,
1050 "email" VARCHAR(255) NOT NULL
1051)"#;
1052 let result = DumpLoader::strip_mssql_syntax(sql);
1054 assert!(!result.contains("IDENTITY"), "IDENTITY should be stripped");
1055
1056 let sql_with_identity = r#"CREATE TABLE "users" (
1058 "id" INTEGER IDENTITY(1,1) NOT NULL,
1059 "email" VARCHAR(255) NOT NULL
1060)"#;
1061 let result2 = DumpLoader::strip_mssql_syntax(sql_with_identity);
1062 assert!(
1063 !result2.contains("IDENTITY"),
1064 "IDENTITY should be stripped: {}",
1065 result2
1066 );
1067 assert!(
1069 !result2.contains("IDENTITY(1,1) NOT NULL"),
1070 "Should strip full IDENTITY NOT NULL"
1071 );
1072 }
1073
1074 #[test]
1075 fn test_convert_mssql_identifiers() {
1076 let sql = "INSERT INTO [dbo].[users] ([id], [name]) VALUES (1, N'test')";
1077 let result = DumpLoader::convert_identifiers(sql, SqlDialect::Mssql);
1078 assert_eq!(
1079 result,
1080 "INSERT INTO \"dbo\".\"users\" (\"id\", \"name\") VALUES (1, 'test')"
1081 );
1082 }
1083}