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(reader, determine_buffer_size(file_size), dialect, &mut stats)?;
86
87 if let Some(pb) = progress_bar {
88 pb.finish_with_message("Import complete");
89 }
90
91 stats.duration_secs = start.elapsed().as_secs_f64();
92 Ok(stats)
93 }
94
95 fn load_statements<R: Read>(
97 &self,
98 reader: R,
99 buffer_size: usize,
100 dialect: SqlDialect,
101 stats: &mut ImportStats,
102 ) -> Result<()> {
103 let mut parser = Parser::with_dialect(reader, buffer_size, dialect);
104
105 let mut pending_copy: Option<CopyHeader> = None;
111 let mut skipping_copy_data = false;
112
113 let mut failed_tables: std::collections::HashSet<String> = std::collections::HashSet::new();
115
116 let mut batch_mgr = BatchManager::new(MAX_ROWS_PER_BATCH);
118
119 while let Some(raw) = parser.read_statement()? {
120 if let Some(header) = pending_copy.take() {
124 self.process_copy_batch(&header, &raw, stats, &mut failed_tables);
131 continue;
132 }
133 if skipping_copy_data {
134 skipping_copy_data = false;
135 stats.statements_skipped += 1;
136 continue;
137 }
138
139 let (stmt_type, table_name) =
140 Parser::<&[u8]>::parse_statement_with_dialect(&raw, dialect);
141
142 if let Some(ref tables) = self.config.tables {
146 if !table_name.is_empty()
147 && !tables.iter().any(|t| t.eq_ignore_ascii_case(&table_name))
148 {
149 skipping_copy_data = parser.in_copy_data();
150 continue;
151 }
152 }
153
154 let stmt = String::from_utf8_lossy(&raw);
155
156 match stmt_type {
157 StatementType::CreateTable => {
158 let duckdb_sql = self.convert_create_table(&stmt, dialect)?;
159 match self.conn.execute(&duckdb_sql, []) {
160 Ok(_) => stats.tables_created += 1,
161 Err(e) => {
162 stats
163 .warnings
164 .push(format!("Failed to create table {}: {}", table_name, e));
165 stats.statements_skipped += 1;
166 }
167 }
168 }
169 StatementType::Insert => {
170 if !self.try_queue_for_bulk(
172 &stmt,
173 dialect,
174 &mut batch_mgr,
175 stats,
176 &mut failed_tables,
177 ) {
178 let duckdb_sql = self.convert_insert(&stmt, dialect)?;
180 match self.conn.execute(&duckdb_sql, []) {
181 Ok(_) => {
182 stats.insert_statements += 1;
183 stats.rows_inserted += Self::count_insert_rows(&duckdb_sql);
184 }
185 Err(e) => {
186 stats
187 .warnings
188 .push(format!("Failed INSERT for {}: {}", table_name, e));
189 stats.statements_skipped += 1;
190 }
191 }
192 }
193
194 for mut batch in batch_mgr.get_ready_batches() {
196 flush_batch(self.conn, &mut batch, stats, &mut failed_tables)?;
197 }
198 }
199 StatementType::Copy => {
200 let has_data_block = parser.in_copy_data();
204 match parse_copy_header(&stmt) {
205 Some(header) if has_data_block => {
206 if !failed_tables.contains(&header.table)
210 && !self.table_exists(&header.table)
211 {
212 failed_tables.insert(header.table.clone());
213 if stats.warnings.len() < 100 {
214 stats.warnings.push(format!(
215 "Skipping COPY for non-existent table {}",
216 header.table
217 ));
218 }
219 }
220
221 if failed_tables.contains(&header.table) {
222 skipping_copy_data = true;
223 } else {
224 pending_copy = Some(header);
225 }
226 }
227 _ => skipping_copy_data = has_data_block,
230 }
231 }
232 StatementType::CreateIndex => {
233 stats.statements_skipped += 1;
235 }
236 _ => {
237 stats.statements_skipped += 1;
239 }
240 }
241 }
242
243 for mut batch in batch_mgr.drain_all() {
245 flush_batch(self.conn, &mut batch, stats, &mut failed_tables)?;
246 }
247
248 Ok(())
249 }
250
251 fn process_copy_batch(
253 &self,
254 header: &CopyHeader,
255 batch_data: &[u8],
256 stats: &mut ImportStats,
257 failed_tables: &mut std::collections::HashSet<String>,
258 ) {
259 if batch_data.is_empty() {
260 return;
261 }
262
263 if failed_tables.contains(&header.table) {
265 return;
266 }
267
268 let rows = parse_copy_data(batch_data);
269 for chunk in rows.chunks(MAX_ROWS_PER_INSERT) {
270 let insert = copy_rows_to_insert(header, chunk, SqlDialect::Postgres);
271 let insert_sql = String::from_utf8_lossy(&insert);
272 match self.conn.execute(&insert_sql, []) {
273 Ok(_) => {
274 stats.rows_inserted += chunk.len() as u64;
275 }
276 Err(e) => {
277 if Self::is_missing_table_error(&e) {
279 Self::mark_missing_copy_table(header, stats, failed_tables);
280 return; }
282
283 if chunk.len() > 1 {
287 self.process_copy_rows(header, chunk, stats, failed_tables);
288 } else {
289 Self::record_copy_insert_error(header, &e, stats);
290 }
291 }
292 }
293 }
294 }
295
296 fn process_copy_rows(
297 &self,
298 header: &CopyHeader,
299 rows: &[Vec<CopyValue>],
300 stats: &mut ImportStats,
301 failed_tables: &mut std::collections::HashSet<String>,
302 ) {
303 for row in rows {
304 let insert =
305 copy_rows_to_insert(header, std::slice::from_ref(row), SqlDialect::Postgres);
306 let insert_sql = String::from_utf8_lossy(&insert);
307
308 match self.conn.execute(&insert_sql, []) {
309 Ok(_) => stats.rows_inserted += 1,
310 Err(e) if Self::is_missing_table_error(&e) => {
311 Self::mark_missing_copy_table(header, stats, failed_tables);
312 return;
313 }
314 Err(e) => Self::record_copy_insert_error(header, &e, stats),
315 }
316 }
317 }
318
319 fn is_missing_table_error(error: &duckdb::Error) -> bool {
322 matches!(
323 error,
324 duckdb::Error::DuckDBFailure(_, Some(message))
325 if message.starts_with("Catalog Error: Table with name ")
326 )
327 }
328
329 fn mark_missing_copy_table(
330 header: &CopyHeader,
331 stats: &mut ImportStats,
332 failed_tables: &mut std::collections::HashSet<String>,
333 ) {
334 failed_tables.insert(header.table.clone());
335 if stats.warnings.len() < 100 {
336 stats.warnings.push(format!(
337 "Table {} does not exist, skipping COPY data",
338 header.table
339 ));
340 }
341 }
342
343 fn record_copy_insert_error(
344 header: &CopyHeader,
345 error: &duckdb::Error,
346 stats: &mut ImportStats,
347 ) {
348 if stats.warnings.len() < 100 {
349 stats.warnings.push(format!(
350 "Failed to insert COPY data for {}: {}",
351 header.table, error
352 ));
353 }
354 stats.statements_skipped += 1;
355 }
356
357 fn table_exists(&self, table: &str) -> bool {
359 let query = "SELECT 1 FROM information_schema.tables WHERE table_name = ? LIMIT 1";
360 match self.conn.prepare(query) {
361 Ok(mut stmt) => stmt.exists([table]).unwrap_or(false),
362 Err(_) => false,
363 }
364 }
365
366 fn try_queue_for_bulk(
369 &self,
370 stmt: &str,
371 dialect: SqlDialect,
372 batch_mgr: &mut BatchManager,
373 stats: &mut ImportStats,
374 failed_tables: &mut std::collections::HashSet<String>,
375 ) -> bool {
376 let upper = stmt.to_uppercase();
378 if upper.contains("ON DUPLICATE KEY")
379 || upper.contains("ON CONFLICT")
380 || upper.contains("REPLACE")
381 || upper.contains("IGNORE")
382 || upper.contains("RETURNING")
383 || upper.contains("SELECT")
384 {
385 return false;
386 }
387
388 let parsed = match parse_insert_for_bulk(stmt.as_bytes(), dialect) {
390 Ok(p) => p,
391 Err(_) => return false, };
393
394 if failed_tables.contains(&parsed.table) {
396 return true; }
398
399 if parsed.rows.is_empty() {
401 return false;
402 }
403
404 let duckdb_sql = match self.convert_insert(stmt, dialect) {
406 Ok(sql) => sql,
407 Err(_) => return false,
408 };
409
410 if let Some(mut batch) = batch_mgr.queue_insert(
412 &parsed.table,
413 parsed.columns,
414 parsed.rows,
415 duckdb_sql,
416 dialect,
417 ) {
418 if let Err(e) = flush_batch(self.conn, &mut batch, stats, failed_tables) {
420 if stats.warnings.len() < 100 {
421 stats.warnings.push(format!("Batch flush error: {}", e));
422 }
423 }
424 }
425
426 true
427 }
428
429
430 fn convert_create_table(&self, stmt: &str, dialect: SqlDialect) -> Result<String> {
432 let mut result = stmt.to_string();
433
434 result = Self::convert_identifiers(&result, dialect);
436
437 result = Self::strip_mysql_clauses(&result);
440
441 result = Self::convert_types_in_statement(&result);
443
444 if dialect == SqlDialect::Postgres {
446 result = Self::strip_postgres_syntax(&result);
447 }
448
449 if dialect == SqlDialect::Mssql {
451 result = Self::strip_mssql_syntax(&result);
452 }
453
454 if dialect == SqlDialect::Sqlite {
456 result = Self::strip_sqlite_syntax(&result);
457 }
458
459 Ok(result)
460 }
461
462 fn convert_insert(&self, stmt: &str, dialect: SqlDialect) -> Result<String> {
464 let mut result = stmt.to_string();
465
466 result = Self::convert_identifiers(&result, dialect);
468
469 if dialect == SqlDialect::MySql {
471 result = Self::convert_mysql_escapes(&result);
472 }
473
474 if dialect == SqlDialect::Postgres {
476 result = Self::strip_schema_prefix(&result);
477 }
478
479 if dialect == SqlDialect::Mssql {
481 result = Self::strip_mssql_schema_prefix(&result);
482 }
483
484 Ok(result)
485 }
486
487 fn convert_mysql_escapes(stmt: &str) -> String {
489 let mut result = String::with_capacity(stmt.len() + 100);
490 let mut chars = stmt.chars().peekable();
491 let mut in_string = false;
492
493 while let Some(c) = chars.next() {
494 if c == '\'' {
495 in_string = !in_string;
496 result.push(c);
497 } else if c == '\\' && in_string {
498 match chars.peek() {
500 Some('\'') => {
501 chars.next();
503 result.push_str("''");
504 }
505 Some('\\') => {
506 chars.next();
508 result.push('\\');
509 }
510 Some('n') => {
511 chars.next();
513 result.push('\n');
514 }
515 Some('r') => {
516 chars.next();
518 result.push('\r');
519 }
520 Some('t') => {
521 chars.next();
523 result.push('\t');
524 }
525 Some('0') => {
526 chars.next();
528 }
529 Some('"') => {
530 chars.next();
532 result.push('"');
533 }
534 _ => {
535 result.push(c);
537 }
538 }
539 } else {
540 result.push(c);
541 }
542 }
543 result
544 }
545
546 fn convert_identifiers(stmt: &str, dialect: SqlDialect) -> String {
548 match dialect {
549 SqlDialect::MySql => {
550 let mut result = String::with_capacity(stmt.len());
552 let mut in_string = false;
553 let mut in_backtick = false;
554
555 for c in stmt.chars() {
556 if c == '\'' && !in_backtick {
557 in_string = !in_string;
558 result.push(c);
559 } else if c == '`' && !in_string {
560 in_backtick = !in_backtick;
561 result.push('"');
562 } else {
563 result.push(c);
564 }
565 }
566 result
567 }
568 SqlDialect::Mssql => {
569 let mut result = String::with_capacity(stmt.len());
571 let mut in_string = false;
572 let mut in_bracket = false;
573 let mut chars = stmt.chars().peekable();
574
575 while let Some(c) = chars.next() {
576 if c == '\'' && !in_bracket {
577 in_string = !in_string;
578 result.push(c);
579 } else if c == '[' && !in_string {
580 in_bracket = true;
581 result.push('"');
582 } else if c == ']' && !in_string {
583 if chars.peek() == Some(&']') {
585 chars.next();
586 result.push(']');
587 } else {
588 in_bracket = false;
589 result.push('"');
590 }
591 } else if c == 'N' && !in_string && !in_bracket && chars.peek() == Some(&'\'') {
592 } else {
595 result.push(c);
596 }
597 }
598 result
599 }
600 _ => stmt.to_string(),
601 }
602 }
603
604 fn convert_types_in_statement(stmt: &str) -> String {
606 static RE_COLUMN_TYPE: Lazy<Regex> = Lazy::new(|| {
613 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()
614 });
615
616 RE_COLUMN_TYPE
617 .replace_all(stmt, |caps: ®ex::Captures| {
618 let full_match = caps.get(0).unwrap().as_str();
619 let leading_char = caps.get(1).unwrap().as_str();
620 let type_part = caps.get(2).unwrap().as_str();
621 let size_part = caps.get(3).map(|m| m.as_str()).unwrap_or("");
622 let suffix = caps.get(4).map(|m| m.as_str()).unwrap_or("");
623
624 let end_pos = caps.get(0).unwrap().end();
627 let stmt_bytes = stmt.as_bytes();
628 if end_pos < stmt_bytes.len() {
629 let next_char = stmt_bytes[end_pos] as char;
630 if next_char == '"' || next_char == '\'' || next_char == '`' {
632 return full_match.to_string();
633 }
634 }
635
636 let ws_len = full_match.len()
638 - leading_char.len()
639 - type_part.len()
640 - size_part.len()
641 - suffix.len();
642 let ws = &full_match[leading_char.len()..leading_char.len() + ws_len];
643
644 let converted =
645 TypeConverter::convert(&format!("{}{}{}", type_part, size_part, suffix));
646 format!("{}{}{}", leading_char, ws, converted)
647 })
648 .to_string()
649 }
650
651 fn strip_mysql_clauses(stmt: &str) -> String {
653 let mut result = stmt.to_string();
654
655 static RE_ENGINE: Lazy<Regex> =
657 Lazy::new(|| Regex::new(r"(?i)\s*ENGINE\s*=\s*\w+").unwrap());
658 result = RE_ENGINE.replace_all(&result, "").to_string();
659
660 static RE_AUTO_INC: Lazy<Regex> =
662 Lazy::new(|| Regex::new(r"(?i)\s*AUTO_INCREMENT\s*=\s*\d+").unwrap());
663 result = RE_AUTO_INC.replace_all(&result, "").to_string();
664
665 result = result.replace(" AUTO_INCREMENT", "");
667 result = result.replace(" auto_increment", "");
668
669 static RE_CHAR_SET: Lazy<Regex> =
671 Lazy::new(|| Regex::new(r"(?i)\s*CHARACTER\s+SET\s+\w+").unwrap());
672 result = RE_CHAR_SET.replace_all(&result, "").to_string();
673
674 static RE_CHARSET: Lazy<Regex> =
676 Lazy::new(|| Regex::new(r"(?i)\s*(DEFAULT\s+)?CHARSET\s*=\s*\w+").unwrap());
677 result = RE_CHARSET.replace_all(&result, "").to_string();
678
679 static RE_COLLATE: Lazy<Regex> =
681 Lazy::new(|| Regex::new(r"(?i)\s*COLLATE\s*=?\s*\w+").unwrap());
682 result = RE_COLLATE.replace_all(&result, "").to_string();
683
684 static RE_ROW_FORMAT: Lazy<Regex> =
686 Lazy::new(|| Regex::new(r"(?i)\s*ROW_FORMAT\s*=\s*\w+").unwrap());
687 result = RE_ROW_FORMAT.replace_all(&result, "").to_string();
688
689 static RE_KEY_BLOCK: Lazy<Regex> =
691 Lazy::new(|| Regex::new(r"(?i)\s*KEY_BLOCK_SIZE\s*=\s*\d+").unwrap());
692 result = RE_KEY_BLOCK.replace_all(&result, "").to_string();
693
694 static RE_COMMENT: Lazy<Regex> =
696 Lazy::new(|| Regex::new(r"(?i)\s*COMMENT\s*=?\s*'[^']*'").unwrap());
697 result = RE_COMMENT.replace_all(&result, "").to_string();
698
699 static RE_COND_COMMENT: Lazy<Regex> = Lazy::new(|| Regex::new(r"/\*!\d+\s*|\*/").unwrap());
701 result = RE_COND_COMMENT.replace_all(&result, "").to_string();
702
703 static RE_ON_UPDATE: Lazy<Regex> =
705 Lazy::new(|| Regex::new(r"(?i)\s*ON\s+UPDATE\s+CURRENT_TIMESTAMP").unwrap());
706 result = RE_ON_UPDATE.replace_all(&result, "").to_string();
707
708 static RE_UNIQUE_KEY: Lazy<Regex> = Lazy::new(|| {
711 Regex::new(r#"(?i),?\s*UNIQUE\s+KEY\s+[`"']?\w+[`"']?\s*\([^)]+\)"#).unwrap()
712 });
713 result = RE_UNIQUE_KEY.replace_all(&result, "").to_string();
714
715 static RE_KEY_INDEX: Lazy<Regex> = Lazy::new(|| {
719 Regex::new(
720 r#"(?i)(?:,\s*|\n\s*)(?:FULLTEXT\s+|SPATIAL\s+)?KEY\s+[`"']?\w+[`"']?\s*\([^)]+\)"#,
721 )
722 .unwrap()
723 });
724 result = RE_KEY_INDEX.replace_all(&result, "").to_string();
725
726 static RE_GENERATED_COL: Lazy<Regex> = Lazy::new(|| {
730 Regex::new(r#"(?i),?\s*[`"']?\w+[`"']?\s+\w+\s+GENERATED\s+ALWAYS\s+AS\s*\((?:[^()]+|\([^()]*\))+\)\s*(?:STORED|VIRTUAL)?"#).unwrap()
731 });
732 result = RE_GENERATED_COL.replace_all(&result, "").to_string();
733
734 static RE_FK_CONSTRAINT: Lazy<Regex> = Lazy::new(|| {
738 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()
739 });
740 result = RE_FK_CONSTRAINT.replace_all(&result, "").to_string();
741
742 result
743 }
744
745 fn strip_postgres_syntax(stmt: &str) -> String {
747 let mut result = stmt.to_string();
748
749 result = Self::strip_schema_prefix(&result);
751
752 static RE_CAST: Lazy<Regex> = Lazy::new(|| {
754 Regex::new(r"::[a-zA-Z_][a-zA-Z0-9_]*(?:\s+[a-zA-Z_][a-zA-Z0-9_]*)*").unwrap()
755 });
756 result = RE_CAST.replace_all(&result, "").to_string();
757
758 static RE_NEXTVAL: Lazy<Regex> =
760 Lazy::new(|| Regex::new(r"(?i)\s*DEFAULT\s+nextval\s*\([^)]+\)").unwrap());
761 result = RE_NEXTVAL.replace_all(&result, "").to_string();
762
763 static RE_NOW: Lazy<Regex> =
765 Lazy::new(|| Regex::new(r"(?i)\bDEFAULT\s+now\s*\(\s*\)").unwrap());
766 result = RE_NOW
767 .replace_all(&result, "DEFAULT CURRENT_TIMESTAMP")
768 .to_string();
769
770 static RE_INHERITS: Lazy<Regex> =
772 Lazy::new(|| Regex::new(r"(?i)\s*INHERITS\s*\([^)]+\)").unwrap());
773 result = RE_INHERITS.replace_all(&result, "").to_string();
774
775 static RE_WITH: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\s*WITH\s*\([^)]+\)").unwrap());
777 result = RE_WITH.replace_all(&result, "").to_string();
778
779 result
780 }
781
782 fn strip_schema_prefix(stmt: &str) -> String {
784 static RE_SCHEMA: Lazy<Regex> =
785 Lazy::new(|| Regex::new(r#"(?i)\b(public|pg_catalog|pg_temp)\s*\.\s*"#).unwrap());
786 RE_SCHEMA.replace_all(stmt, "").to_string()
787 }
788
789 fn strip_mssql_schema_prefix(stmt: &str) -> String {
791 static RE_SCHEMA: Lazy<Regex> =
793 Lazy::new(|| Regex::new(r#"(?i)"?(dbo|master|tempdb|model|msdb)"?\s*\.\s*"#).unwrap());
794 RE_SCHEMA.replace_all(stmt, "").to_string()
795 }
796
797 fn strip_mssql_syntax(stmt: &str) -> String {
799 let mut result = Self::strip_mssql_schema_prefix(stmt);
800
801 static RE_IDENTITY_NOT_NULL: Lazy<Regex> = Lazy::new(|| {
804 Regex::new(r"(?i)\s*IDENTITY\s*\(\s*\d+\s*,\s*\d+\s*\)\s*NOT\s+NULL").unwrap()
805 });
806 result = RE_IDENTITY_NOT_NULL.replace_all(&result, "").to_string();
807
808 static RE_IDENTITY: Lazy<Regex> =
810 Lazy::new(|| Regex::new(r"(?i)\s*IDENTITY\s*\(\s*\d+\s*,\s*\d+\s*\)").unwrap());
811 result = RE_IDENTITY.replace_all(&result, "").to_string();
812
813 static RE_CLUSTERED: Lazy<Regex> =
815 Lazy::new(|| Regex::new(r"(?i)\s*(?:NON)?CLUSTERED\s*").unwrap());
816 result = RE_CLUSTERED.replace_all(&result, " ").to_string();
817
818 static RE_FILEGROUP: Lazy<Regex> =
820 Lazy::new(|| Regex::new(r#"(?i)\s*ON\s*"?PRIMARY"?"#).unwrap());
821 result = RE_FILEGROUP.replace_all(&result, "").to_string();
822
823 static RE_PK_CONSTRAINT: Lazy<Regex> = Lazy::new(|| {
825 Regex::new(r#"(?i),?\s*CONSTRAINT\s+"?\w+"?\s+PRIMARY\s+KEY\s+\([^)]+\)"#).unwrap()
826 });
827 result = RE_PK_CONSTRAINT.replace_all(&result, "").to_string();
828
829 static RE_FK_CONSTRAINT: Lazy<Regex> = Lazy::new(|| {
831 Regex::new(r#"(?i),?\s*CONSTRAINT\s+"?\w+"?\s+FOREIGN\s+KEY\s*\([^)]+\)\s*REFERENCES\s+[^\s(]+\s*\([^)]+\)"#).unwrap()
832 });
833 result = RE_FK_CONSTRAINT.replace_all(&result, "").to_string();
834
835 static RE_WITH: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\s*WITH\s*\([^)]+\)").unwrap());
837 result = RE_WITH.replace_all(&result, "").to_string();
838
839 static RE_TEXTIMAGE: Lazy<Regex> =
841 Lazy::new(|| Regex::new(r#"(?i)\s*TEXTIMAGE_ON\s*"?\w+"?"#).unwrap());
842 result = RE_TEXTIMAGE.replace_all(&result, "").to_string();
843
844 static RE_GETDATE: Lazy<Regex> =
846 Lazy::new(|| Regex::new(r"(?i)\bGETDATE\s*\(\s*\)").unwrap());
847 result = RE_GETDATE
848 .replace_all(&result, "CURRENT_TIMESTAMP")
849 .to_string();
850
851 static RE_NEWID: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bNEWID\s*\(\s*\)").unwrap());
853 result = RE_NEWID
854 .replace_all(&result, "gen_random_uuid()")
855 .to_string();
856
857 result
858 }
859
860 fn strip_sqlite_syntax(stmt: &str) -> String {
862 let mut result = stmt.to_string();
863
864 result = result.replace(" AUTOINCREMENT", "");
867 result = result.replace(" autoincrement", "");
868
869 static RE_STRICT: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\)\s*STRICT\s*;").unwrap());
874 result = RE_STRICT.replace_all(&result, ");").to_string();
875
876 static RE_WITHOUT_ROWID: Lazy<Regex> =
878 Lazy::new(|| Regex::new(r"(?i)\)\s*WITHOUT\s+ROWID\s*;").unwrap());
879 result = RE_WITHOUT_ROWID.replace_all(&result, ");").to_string();
880
881 result
882 }
883
884 fn count_insert_rows(sql: &str) -> u64 {
886 if let Some(values_pos) = sql.to_uppercase().find("VALUES") {
888 let after_values = &sql[values_pos + 6..];
889 let mut count = 0u64;
891 let mut depth = 0;
892 let mut in_string = false;
893 let mut prev_char = ' ';
894
895 for c in after_values.chars() {
896 if c == '\'' && prev_char != '\\' {
897 in_string = !in_string;
898 }
899 if !in_string {
900 if c == '(' {
901 if depth == 0 {
902 count += 1;
903 }
904 depth += 1;
905 } else if c == ')' {
906 depth -= 1;
907 }
908 }
909 prev_char = c;
910 }
911 count
912 } else {
913 1
914 }
915 }
916}
917
918#[cfg(test)]
919mod tests {
920 use super::*;
921
922 #[test]
923 fn test_count_insert_rows() {
924 assert_eq!(
925 DumpLoader::count_insert_rows("INSERT INTO t VALUES (1, 'a')"),
926 1
927 );
928 assert_eq!(
929 DumpLoader::count_insert_rows("INSERT INTO t VALUES (1, 'a'), (2, 'b'), (3, 'c')"),
930 3
931 );
932 assert_eq!(
933 DumpLoader::count_insert_rows("INSERT INTO t VALUES (1, '(test)')"),
934 1
935 );
936 }
937
938 #[test]
939 fn test_strip_mysql_clauses() {
940 let sql = "CREATE TABLE t (id INT) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";
941 let result = DumpLoader::strip_mysql_clauses(sql);
942 assert!(!result.contains("ENGINE"));
943 assert!(!result.contains("CHARSET"));
944 }
945
946 #[test]
947 fn test_convert_identifiers() {
948 let sql = "INSERT INTO `users` (`id`, `name`) VALUES (1, 'test')";
949 let result = DumpLoader::convert_identifiers(sql, SqlDialect::MySql);
950 assert_eq!(
951 result,
952 "INSERT INTO \"users\" (\"id\", \"name\") VALUES (1, 'test')"
953 );
954 }
955
956 #[test]
957 fn test_strip_mssql_syntax() {
958 let sql = r#"CREATE TABLE "users" (
959 "id" INTEGER NOT NULL,
960 "email" VARCHAR(255) NOT NULL
961)"#;
962 let result = DumpLoader::strip_mssql_syntax(sql);
964 assert!(!result.contains("IDENTITY"), "IDENTITY should be stripped");
965
966 let sql_with_identity = r#"CREATE TABLE "users" (
968 "id" INTEGER IDENTITY(1,1) NOT NULL,
969 "email" VARCHAR(255) NOT NULL
970)"#;
971 let result2 = DumpLoader::strip_mssql_syntax(sql_with_identity);
972 assert!(
973 !result2.contains("IDENTITY"),
974 "IDENTITY should be stripped: {}",
975 result2
976 );
977 assert!(
979 !result2.contains("IDENTITY(1,1) NOT NULL"),
980 "Should strip full IDENTITY NOT NULL"
981 );
982 }
983
984 #[test]
985 fn test_convert_mssql_identifiers() {
986 let sql = "INSERT INTO [dbo].[users] ([id], [name]) VALUES (1, N'test')";
987 let result = DumpLoader::convert_identifiers(sql, SqlDialect::Mssql);
988 assert_eq!(
989 result,
990 "INSERT INTO \"dbo\".\"users\" (\"id\", \"name\") VALUES (1, 'test')"
991 );
992 }
993}