Skip to main content

sql_splitter/duckdb/
loader.rs

1//! SQL dump loader for importing dumps into DuckDB.
2
3use 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
22/// Loads SQL dumps into a DuckDB database
23pub struct DumpLoader<'a> {
24    conn: &'a Connection,
25    config: &'a QueryConfig,
26}
27
28impl<'a> DumpLoader<'a> {
29    /// Create a new dump loader
30    pub fn new(conn: &'a Connection, config: &'a QueryConfig) -> Self {
31        Self { conn, config }
32    }
33
34    /// Load a SQL dump file into DuckDB
35    pub fn load(&self, dump_path: &Path) -> Result<ImportStats> {
36        let start = std::time::Instant::now();
37        let mut stats = ImportStats::default();
38
39        // Detect dialect
40        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        // Get file size for progress
48        let file_size = std::fs::metadata(dump_path)?.len();
49
50        // Set up progress bar
51        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        // Open file with compression detection (including zip archives,
65        // which need the two-phase open in `crate::splitter::open_input`).
66        // Progress goes through `open_input_with_progress` so the callback
67        // reports raw *compressed* bytes read from disk — the same unit as
68        // the bar's `file_size` total — matching every other call site.
69        // (Wrapping ProgressReader around the decompressed stream made the
70        // bar overshoot its total and pin at 100% for most of the run.)
71        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        // Parse and load statements. `Parser` does its own buffering, sized the
84        // same way every other command sizes it.
85        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    /// Load statements from a reader
101    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        // A `COPY ... FROM stdin;` header is always followed by its data block as
111        // the very next statement. `Some(header)` means load that block; `None`
112        // with `skipping_copy_data` set means discard it. Both are driven off
113        // `parser.in_copy_data()` so the loader can never desync from the parser
114        // about whether a block is even coming.
115        let mut pending_copy: Option<CopyHeader> = None;
116        let mut skipping_copy_data = false;
117
118        // Track tables that failed (don't exist) to skip subsequent inserts
119        let mut failed_tables: std::collections::HashSet<String> = std::collections::HashSet::new();
120
121        // Batch manager for bulk INSERT loading via Appender API
122        let mut batch_mgr = BatchManager::new(MAX_ROWS_PER_BATCH);
123
124        while let Some(raw) = parser.read_statement()? {
125            // COPY data must be claimed before any SQL parsing: a data row whose
126            // first column happens to start with "INSERT INTO ..." would
127            // otherwise be dispatched as a statement and executed.
128            if let Some(header) = pending_copy.take() {
129                // ponytail: `read_statement` hands back a COPY block whole, so peak
130                // memory is one block rather than the old 10k-row window (DuckDB is
131                // still fed in MAX_ROWS_PER_INSERT chunks inside). Same tradeoff the
132                // rest of the codebase already makes. If a pg_dump with one huge
133                // table blows memory, switch this loop to `Parser::visit_events`,
134                // which streams CopyRow/InsertRow without buffering the block.
135                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            // Filter tables if specified. A filtered-out COPY header still has to
148            // arm the skip flag below, or its data block would be dispatched as
149            // SQL on the next iteration.
150            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                    // Try bulk loading via Appender API first
176                    if !self.try_queue_for_bulk(
177                        &stmt,
178                        dialect,
179                        &mut batch_mgr,
180                        stats,
181                        &mut failed_tables,
182                    ) {
183                        // Fallback to direct execution
184                        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                    // Flush any ready batches
200                    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                    // Only a `FROM stdin` COPY is followed by a data block; a
206                    // file-source COPY is a lone statement and must not arm
207                    // either flag, or it would swallow the next statement.
208                    let has_data_block = parser.in_copy_data();
209                    match parse_copy_header(&stmt) {
210                        Some(header) if has_data_block => {
211                            // Proactively check the table exists before loading
212                            // the block, so a missing table costs one lookup
213                            // instead of a failed INSERT per chunk.
214                            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                        // Unparseable header, but the parser is still in copy
233                        // mode: the block must be consumed, not dispatched.
234                        _ => skipping_copy_data = has_data_block,
235                    }
236                }
237                StatementType::CreateIndex => {
238                    // Skip indexes - not needed for analytics queries
239                    stats.statements_skipped += 1;
240                }
241                _ => {
242                    // Skip other statements (ALTER, DROP, etc.)
243                    stats.statements_skipped += 1;
244                }
245            }
246        }
247
248        // Flush any remaining INSERT batches
249        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    /// Process a batch of COPY data rows, converting them to INSERTs
257    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        // Skip if we already know this table doesn't exist
269        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 table doesn't exist, mark it and skip future inserts
283                    if Self::is_missing_table_error(&e) {
284                        Self::mark_missing_copy_table(header, stats, failed_tables);
285                        return; // Skip rest of batch
286                    }
287
288                    // A multi-row INSERT is atomic in DuckDB. Retry a failed
289                    // chunk row by row so a malformed value or rejected child
290                    // row does not discard the valid rows beside it.
291                    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    /// DuckDB reports FK violations with "does not exist" in the message, so
325    /// only a catalog missing-table error may disable later COPY batches.
326    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    /// Check if a table exists in DuckDB
363    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    /// Does this INSERT carry a clause the bulk path cannot honour?
372    ///
373    /// Only the statement's head (before `VALUES`) and its tail can hold one --
374    /// everything between is row data. The previous check uppercased the whole
375    /// statement and searched all of it, so a row containing the word "select"
376    /// in a URL or a description looked like `INSERT ... SELECT`. On a real
377    /// dump that pushed 78% of one table onto the slow per-statement path, and
378    /// it copied every statement (~225KB here) just to do the search.
379    ///
380    /// A statement with no `VALUES` is `INSERT ... SELECT` or something equally
381    /// unsupported, so it declines.
382    fn has_unsupported_insert_clause(stmt: &str) -> bool {
383        const HEAD_SCAN_LIMIT: usize = 64 * 1024;
384        // Generous next to a multi-megabyte statement, and far past any real
385        // ON DUPLICATE KEY UPDATE / ON CONFLICT / RETURNING clause.
386        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                // Mixed case such as `Values` is rare; confirm on an uppercased
398                // copy of the window before declining outright.
399                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    /// Try to queue an INSERT statement for bulk loading via Appender API.
423    /// Returns true if successfully queued, false if fallback to direct execution is needed.
424    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        // Skip statements carrying clauses the bulk path cannot honour.
433        if Self::has_unsupported_insert_clause(stmt) {
434            return false;
435        }
436
437        // Try to parse the INSERT statement
438        let parsed = match parse_insert_for_bulk(stmt.as_bytes(), dialect) {
439            Ok(p) => p,
440            Err(_) => return false, // Parse failed, use fallback
441        };
442
443        // Skip tables we know don't exist
444        if failed_tables.contains(&parsed.table) {
445            return true; // Pretend we handled it to skip the statement
446        }
447
448        // Skip if no rows were parsed
449        if parsed.rows.is_empty() {
450            return false;
451        }
452
453        // Convert the statement for DuckDB (for fallback)
454        let duckdb_sql = match self.convert_insert(stmt, dialect) {
455            Ok(sql) => sql,
456            Err(_) => return false,
457        };
458
459        // Queue the rows
460        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            // Batch is ready to flush
468            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    /// Convert a CREATE TABLE statement to DuckDB-compatible SQL
479    fn convert_create_table(&self, stmt: &str, dialect: SqlDialect) -> Result<String> {
480        let mut result = stmt.to_string();
481
482        // Convert identifier quoting
483        result = Self::convert_identifiers(&result, dialect);
484
485        // Remove MySQL-specific clauses FIRST (before type conversion)
486        // This prevents "CHARACTER SET" from being confused with "CHAR" type
487        result = Self::strip_mysql_clauses(&result);
488
489        // Convert data types in column definitions
490        result = Self::convert_types_in_statement(&result);
491
492        // Remove PostgreSQL-specific syntax
493        if dialect == SqlDialect::Postgres {
494            result = Self::strip_postgres_syntax(&result);
495        }
496
497        // Remove MSSQL-specific syntax
498        if dialect == SqlDialect::Mssql {
499            result = Self::strip_mssql_syntax(&result);
500        }
501
502        // Remove SQLite-specific syntax
503        if dialect == SqlDialect::Sqlite {
504            result = Self::strip_sqlite_syntax(&result);
505        }
506
507        Ok(result)
508    }
509
510    /// Convert an INSERT statement to DuckDB-compatible SQL
511    fn convert_insert(&self, stmt: &str, dialect: SqlDialect) -> Result<String> {
512        let mut result = stmt.to_string();
513
514        // Convert identifier quoting
515        result = Self::convert_identifiers(&result, dialect);
516
517        // Convert MySQL backslash escapes to SQL standard
518        if dialect == SqlDialect::MySql {
519            result = Self::convert_mysql_escapes(&result);
520        }
521
522        // Remove PostgreSQL schema prefix
523        if dialect == SqlDialect::Postgres {
524            result = Self::strip_schema_prefix(&result);
525        }
526
527        // Remove MSSQL schema prefix (dbo., etc.)
528        if dialect == SqlDialect::Mssql {
529            result = Self::strip_mssql_schema_prefix(&result);
530        }
531
532        Ok(result)
533    }
534
535    /// Convert MySQL backslash escapes to SQL standard
536    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                // Handle MySQL escape sequences
547                match chars.peek() {
548                    Some('\'') => {
549                        // \' -> ''
550                        chars.next();
551                        result.push_str("''");
552                    }
553                    Some('\\') => {
554                        // \\ -> \
555                        chars.next();
556                        result.push('\\');
557                    }
558                    Some('n') => {
559                        // \n -> newline
560                        chars.next();
561                        result.push('\n');
562                    }
563                    Some('r') => {
564                        // \r -> carriage return
565                        chars.next();
566                        result.push('\r');
567                    }
568                    Some('t') => {
569                        // \t -> tab
570                        chars.next();
571                        result.push('\t');
572                    }
573                    Some('0') => {
574                        // \0 -> NULL character (skip)
575                        chars.next();
576                    }
577                    Some('"') => {
578                        // \" -> "
579                        chars.next();
580                        result.push('"');
581                    }
582                    _ => {
583                        // Unknown escape, keep backslash
584                        result.push(c);
585                    }
586                }
587            } else {
588                result.push(c);
589            }
590        }
591        result
592    }
593
594    /// Convert identifier quoting (backticks/brackets to double quotes)
595    fn convert_identifiers(stmt: &str, dialect: SqlDialect) -> String {
596        match dialect {
597            SqlDialect::MySql => {
598                // Convert backticks to double quotes
599                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                // Convert brackets to double quotes, strip N prefix from strings
618                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                        // Handle ]] escape
632                        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                        // Strip N prefix from N'string'
641                        // Don't push the N, the quote will be pushed in next iteration
642                    } else {
643                        result.push(c);
644                    }
645                }
646                result
647            }
648            _ => stmt.to_string(),
649        }
650    }
651
652    /// Convert SQL types in a statement
653    fn convert_types_in_statement(stmt: &str) -> String {
654        // Pattern to match column definitions with types
655        // Handles: TYPE, TYPE(size), TYPE UNSIGNED, TYPE WITH TIME ZONE
656        // IMPORTANT: Order matters - longer types first to avoid partial matches (INTEGER before INT)
657        // IMPORTANT: Types must be preceded by quote/whitespace AND followed by whitespace/paren/comma (not a closing quote)
658        // This prevents matching "date" as DATE type (column names inside quotes)
659        // Includes MySQL, PostgreSQL, SQLite, and MSSQL types
660        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: &regex::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                // Check if this looks like a quoted identifier (type is inside quotes)
673                // If leading char is a quote and the character before the match is also a quote, skip
674                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 character is a closing quote, this is a quoted identifier, not a type
679                    if next_char == '"' || next_char == '\'' || next_char == '`' {
680                        return full_match.to_string();
681                    }
682                }
683
684                // Calculate the whitespace between leading char and type
685                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    /// Strip MySQL-specific clauses
700    fn strip_mysql_clauses(stmt: &str) -> String {
701        let mut result = stmt.to_string();
702
703        // Remove ENGINE clause
704        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        // Remove AUTO_INCREMENT clause at table level
709        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        // Remove column AUTO_INCREMENT
714        result = result.replace(" AUTO_INCREMENT", "");
715        result = result.replace(" auto_increment", "");
716
717        // Remove CHARACTER SET in column definitions (must come before CHARSET)
718        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        // Remove DEFAULT CHARSET
723        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        // Remove COLLATE
728        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        // Remove ROW_FORMAT
733        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        // Remove KEY_BLOCK_SIZE
738        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        // Remove COMMENT
743        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        // Remove MySQL conditional comments
748        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        // Remove ON UPDATE CURRENT_TIMESTAMP
752        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        // Remove UNIQUE KEY constraint lines: UNIQUE KEY `name` (`col1`, `col2`)
757        // Must handle both: ,UNIQUE KEY... at end of column list and UNIQUE KEY... on its own line
758        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        // Remove KEY (index) constraint lines: KEY `name` (`col1`, `col2`)
764        // This handles regular indexes and FULLTEXT indexes, but NOT PRIMARY KEY or FOREIGN KEY
765        // We use a negative lookbehind pattern by only matching KEY that is preceded by comma or newline (not FOREIGN/PRIMARY)
766        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        // Remove GENERATED ALWAYS AS columns entirely
775        // Match: `col` TYPE GENERATED ALWAYS AS (expr) STORED/VIRTUAL
776        // The expression can contain nested parentheses so we match one level deep
777        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        // Remove entire FOREIGN KEY constraints (DuckDB enforces them which causes issues with batch loading)
783        // Match: CONSTRAINT `name` FOREIGN KEY (...) REFERENCES ... [ON DELETE/UPDATE ...]
784        // or just: FOREIGN KEY (...) REFERENCES ... [ON DELETE/UPDATE ...]
785        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    /// Strip PostgreSQL-specific syntax
794    fn strip_postgres_syntax(stmt: &str) -> String {
795        let mut result = stmt.to_string();
796
797        // Remove schema prefix
798        result = Self::strip_schema_prefix(&result);
799
800        // Remove type casts
801        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        // Remove nextval() - DuckDB handles sequences differently
807        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        // Convert now() to CURRENT_TIMESTAMP
812        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        // Remove INHERITS clause
819        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        // Remove WITH clause (storage parameters)
824        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    /// Strip schema prefix (e.g., public.users -> users)
831    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    /// Strip MSSQL schema prefix (dbo., etc.) for both CREATE TABLE and INSERT
838    fn strip_mssql_schema_prefix(stmt: &str) -> String {
839        // Remove schema prefix (dbo., schema.) - quoted or unquoted
840        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    /// Strip MSSQL-specific syntax
846    fn strip_mssql_syntax(stmt: &str) -> String {
847        let mut result = Self::strip_mssql_schema_prefix(stmt);
848
849        // Remove IDENTITY clause and make the column nullable (so INSERTs without id work)
850        // Pattern matches: INT IDENTITY(1,1) NOT NULL -> INT
851        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        // Also handle IDENTITY without NOT NULL
857        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        // Remove CLUSTERED/NONCLUSTERED
862        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        // Remove ON [PRIMARY] (filegroup)
867        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        // Remove PRIMARY KEY constraints (they make columns NOT NULL which breaks IDENTITY column INSERTs)
872        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        // Remove FOREIGN KEY constraints (analytics queries don't need FK enforcement)
878        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        // Remove WITH clause for indexes
884        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        // Remove TEXTIMAGE_ON
888        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        // Convert GETDATE() to CURRENT_TIMESTAMP
893        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        // Convert NEWID() to gen_random_uuid()
900        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    /// Strip SQLite-specific syntax not supported by DuckDB
909    fn strip_sqlite_syntax(stmt: &str) -> String {
910        let mut result = stmt.to_string();
911
912        // Remove AUTOINCREMENT (DuckDB handles auto-increment via sequences)
913        // SQLite uses "INTEGER PRIMARY KEY AUTOINCREMENT"
914        result = result.replace(" AUTOINCREMENT", "");
915        result = result.replace(" autoincrement", "");
916
917        // Remove IF NOT EXISTS (DuckDB supports this but we want clean imports)
918        // Actually DuckDB does support IF NOT EXISTS, so leave it
919
920        // Remove STRICT table modifier (SQLite 3.37+)
921        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        // Remove WITHOUT ROWID (SQLite optimization not needed for analytics)
925        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    /// Count rows in an INSERT statement
933    fn count_insert_rows(sql: &str) -> u64 {
934        // Count VALUES clauses by counting opening parentheses after VALUES
935        if let Some(values_pos) = sql.to_uppercase().find("VALUES") {
936            let after_values = &sql[values_pos + 6..];
937            // Count top-level opening parens (simple heuristic)
938            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        // The whole point: a value that merely contains a keyword is data, not
973        // a clause. Searching the entire statement put 78% of a real table on
974        // the slow path because rows held URLs containing "select".
975        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        // Lowercase and mixed-case spellings must be caught too.
1004        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        // The IDENTITY should have been stripped by strip_mssql_syntax
1053        let result = DumpLoader::strip_mssql_syntax(sql);
1054        assert!(!result.contains("IDENTITY"), "IDENTITY should be stripped");
1055
1056        // Test with IDENTITY(1,1) NOT NULL
1057        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        // Since we strip IDENTITY(1,1) NOT NULL, the column should become nullable
1068        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}