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(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    /// Load statements from a reader
96    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        // A `COPY ... FROM stdin;` header is always followed by its data block as
106        // the very next statement. `Some(header)` means load that block; `None`
107        // with `skipping_copy_data` set means discard it. Both are driven off
108        // `parser.in_copy_data()` so the loader can never desync from the parser
109        // about whether a block is even coming.
110        let mut pending_copy: Option<CopyHeader> = None;
111        let mut skipping_copy_data = false;
112
113        // Track tables that failed (don't exist) to skip subsequent inserts
114        let mut failed_tables: std::collections::HashSet<String> = std::collections::HashSet::new();
115
116        // Batch manager for bulk INSERT loading via Appender API
117        let mut batch_mgr = BatchManager::new(MAX_ROWS_PER_BATCH);
118
119        while let Some(raw) = parser.read_statement()? {
120            // COPY data must be claimed before any SQL parsing: a data row whose
121            // first column happens to start with "INSERT INTO ..." would
122            // otherwise be dispatched as a statement and executed.
123            if let Some(header) = pending_copy.take() {
124                // ponytail: `read_statement` hands back a COPY block whole, so peak
125                // memory is one block rather than the old 10k-row window (DuckDB is
126                // still fed in MAX_ROWS_PER_INSERT chunks inside). Same tradeoff the
127                // rest of the codebase already makes. If a pg_dump with one huge
128                // table blows memory, switch this loop to `Parser::visit_events`,
129                // which streams CopyRow/InsertRow without buffering the block.
130                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            // Filter tables if specified. A filtered-out COPY header still has to
143            // arm the skip flag below, or its data block would be dispatched as
144            // SQL on the next iteration.
145            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                    // Try bulk loading via Appender API first
171                    if !self.try_queue_for_bulk(
172                        &stmt,
173                        dialect,
174                        &mut batch_mgr,
175                        stats,
176                        &mut failed_tables,
177                    ) {
178                        // Fallback to direct execution
179                        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                    // Flush any ready batches
195                    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                    // Only a `FROM stdin` COPY is followed by a data block; a
201                    // file-source COPY is a lone statement and must not arm
202                    // either flag, or it would swallow the next statement.
203                    let has_data_block = parser.in_copy_data();
204                    match parse_copy_header(&stmt) {
205                        Some(header) if has_data_block => {
206                            // Proactively check the table exists before loading
207                            // the block, so a missing table costs one lookup
208                            // instead of a failed INSERT per chunk.
209                            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                        // Unparseable header, but the parser is still in copy
228                        // mode: the block must be consumed, not dispatched.
229                        _ => skipping_copy_data = has_data_block,
230                    }
231                }
232                StatementType::CreateIndex => {
233                    // Skip indexes - not needed for analytics queries
234                    stats.statements_skipped += 1;
235                }
236                _ => {
237                    // Skip other statements (ALTER, DROP, etc.)
238                    stats.statements_skipped += 1;
239                }
240            }
241        }
242
243        // Flush any remaining INSERT batches
244        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    /// Process a batch of COPY data rows, converting them to INSERTs
252    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        // Skip if we already know this table doesn't exist
264        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 table doesn't exist, mark it and skip future inserts
278                    if Self::is_missing_table_error(&e) {
279                        Self::mark_missing_copy_table(header, stats, failed_tables);
280                        return; // Skip rest of batch
281                    }
282
283                    // A multi-row INSERT is atomic in DuckDB. Retry a failed
284                    // chunk row by row so a malformed value or rejected child
285                    // row does not discard the valid rows beside it.
286                    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    /// DuckDB reports FK violations with "does not exist" in the message, so
320    /// only a catalog missing-table error may disable later COPY batches.
321    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    /// Check if a table exists in DuckDB
358    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    /// Try to queue an INSERT statement for bulk loading via Appender API.
367    /// Returns true if successfully queued, false if fallback to direct execution is needed.
368    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        // Quick filter: skip statements with complex clauses that Appender can't handle
377        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        // Try to parse the INSERT statement
389        let parsed = match parse_insert_for_bulk(stmt.as_bytes(), dialect) {
390            Ok(p) => p,
391            Err(_) => return false, // Parse failed, use fallback
392        };
393
394        // Skip tables we know don't exist
395        if failed_tables.contains(&parsed.table) {
396            return true; // Pretend we handled it to skip the statement
397        }
398
399        // Skip if no rows were parsed
400        if parsed.rows.is_empty() {
401            return false;
402        }
403
404        // Convert the statement for DuckDB (for fallback)
405        let duckdb_sql = match self.convert_insert(stmt, dialect) {
406            Ok(sql) => sql,
407            Err(_) => return false,
408        };
409
410        // Queue the rows
411        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            // Batch is ready to flush
419            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    /// Convert a CREATE TABLE statement to DuckDB-compatible SQL
431    fn convert_create_table(&self, stmt: &str, dialect: SqlDialect) -> Result<String> {
432        let mut result = stmt.to_string();
433
434        // Convert identifier quoting
435        result = Self::convert_identifiers(&result, dialect);
436
437        // Remove MySQL-specific clauses FIRST (before type conversion)
438        // This prevents "CHARACTER SET" from being confused with "CHAR" type
439        result = Self::strip_mysql_clauses(&result);
440
441        // Convert data types in column definitions
442        result = Self::convert_types_in_statement(&result);
443
444        // Remove PostgreSQL-specific syntax
445        if dialect == SqlDialect::Postgres {
446            result = Self::strip_postgres_syntax(&result);
447        }
448
449        // Remove MSSQL-specific syntax
450        if dialect == SqlDialect::Mssql {
451            result = Self::strip_mssql_syntax(&result);
452        }
453
454        // Remove SQLite-specific syntax
455        if dialect == SqlDialect::Sqlite {
456            result = Self::strip_sqlite_syntax(&result);
457        }
458
459        Ok(result)
460    }
461
462    /// Convert an INSERT statement to DuckDB-compatible SQL
463    fn convert_insert(&self, stmt: &str, dialect: SqlDialect) -> Result<String> {
464        let mut result = stmt.to_string();
465
466        // Convert identifier quoting
467        result = Self::convert_identifiers(&result, dialect);
468
469        // Convert MySQL backslash escapes to SQL standard
470        if dialect == SqlDialect::MySql {
471            result = Self::convert_mysql_escapes(&result);
472        }
473
474        // Remove PostgreSQL schema prefix
475        if dialect == SqlDialect::Postgres {
476            result = Self::strip_schema_prefix(&result);
477        }
478
479        // Remove MSSQL schema prefix (dbo., etc.)
480        if dialect == SqlDialect::Mssql {
481            result = Self::strip_mssql_schema_prefix(&result);
482        }
483
484        Ok(result)
485    }
486
487    /// Convert MySQL backslash escapes to SQL standard
488    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                // Handle MySQL escape sequences
499                match chars.peek() {
500                    Some('\'') => {
501                        // \' -> ''
502                        chars.next();
503                        result.push_str("''");
504                    }
505                    Some('\\') => {
506                        // \\ -> \
507                        chars.next();
508                        result.push('\\');
509                    }
510                    Some('n') => {
511                        // \n -> newline
512                        chars.next();
513                        result.push('\n');
514                    }
515                    Some('r') => {
516                        // \r -> carriage return
517                        chars.next();
518                        result.push('\r');
519                    }
520                    Some('t') => {
521                        // \t -> tab
522                        chars.next();
523                        result.push('\t');
524                    }
525                    Some('0') => {
526                        // \0 -> NULL character (skip)
527                        chars.next();
528                    }
529                    Some('"') => {
530                        // \" -> "
531                        chars.next();
532                        result.push('"');
533                    }
534                    _ => {
535                        // Unknown escape, keep backslash
536                        result.push(c);
537                    }
538                }
539            } else {
540                result.push(c);
541            }
542        }
543        result
544    }
545
546    /// Convert identifier quoting (backticks/brackets to double quotes)
547    fn convert_identifiers(stmt: &str, dialect: SqlDialect) -> String {
548        match dialect {
549            SqlDialect::MySql => {
550                // Convert backticks to double quotes
551                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                // Convert brackets to double quotes, strip N prefix from strings
570                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                        // Handle ]] escape
584                        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                        // Strip N prefix from N'string'
593                        // Don't push the N, the quote will be pushed in next iteration
594                    } else {
595                        result.push(c);
596                    }
597                }
598                result
599            }
600            _ => stmt.to_string(),
601        }
602    }
603
604    /// Convert SQL types in a statement
605    fn convert_types_in_statement(stmt: &str) -> String {
606        // Pattern to match column definitions with types
607        // Handles: TYPE, TYPE(size), TYPE UNSIGNED, TYPE WITH TIME ZONE
608        // IMPORTANT: Order matters - longer types first to avoid partial matches (INTEGER before INT)
609        // IMPORTANT: Types must be preceded by quote/whitespace AND followed by whitespace/paren/comma (not a closing quote)
610        // This prevents matching "date" as DATE type (column names inside quotes)
611        // Includes MySQL, PostgreSQL, SQLite, and MSSQL types
612        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: &regex::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                // Check if this looks like a quoted identifier (type is inside quotes)
625                // If leading char is a quote and the character before the match is also a quote, skip
626                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 character is a closing quote, this is a quoted identifier, not a type
631                    if next_char == '"' || next_char == '\'' || next_char == '`' {
632                        return full_match.to_string();
633                    }
634                }
635
636                // Calculate the whitespace between leading char and type
637                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    /// Strip MySQL-specific clauses
652    fn strip_mysql_clauses(stmt: &str) -> String {
653        let mut result = stmt.to_string();
654
655        // Remove ENGINE clause
656        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        // Remove AUTO_INCREMENT clause at table level
661        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        // Remove column AUTO_INCREMENT
666        result = result.replace(" AUTO_INCREMENT", "");
667        result = result.replace(" auto_increment", "");
668
669        // Remove CHARACTER SET in column definitions (must come before CHARSET)
670        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        // Remove DEFAULT CHARSET
675        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        // Remove COLLATE
680        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        // Remove ROW_FORMAT
685        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        // Remove KEY_BLOCK_SIZE
690        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        // Remove COMMENT
695        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        // Remove MySQL conditional comments
700        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        // Remove ON UPDATE CURRENT_TIMESTAMP
704        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        // Remove UNIQUE KEY constraint lines: UNIQUE KEY `name` (`col1`, `col2`)
709        // Must handle both: ,UNIQUE KEY... at end of column list and UNIQUE KEY... on its own line
710        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        // Remove KEY (index) constraint lines: KEY `name` (`col1`, `col2`)
716        // This handles regular indexes and FULLTEXT indexes, but NOT PRIMARY KEY or FOREIGN KEY
717        // We use a negative lookbehind pattern by only matching KEY that is preceded by comma or newline (not FOREIGN/PRIMARY)
718        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        // Remove GENERATED ALWAYS AS columns entirely
727        // Match: `col` TYPE GENERATED ALWAYS AS (expr) STORED/VIRTUAL
728        // The expression can contain nested parentheses so we match one level deep
729        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        // Remove entire FOREIGN KEY constraints (DuckDB enforces them which causes issues with batch loading)
735        // Match: CONSTRAINT `name` FOREIGN KEY (...) REFERENCES ... [ON DELETE/UPDATE ...]
736        // or just: FOREIGN KEY (...) REFERENCES ... [ON DELETE/UPDATE ...]
737        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    /// Strip PostgreSQL-specific syntax
746    fn strip_postgres_syntax(stmt: &str) -> String {
747        let mut result = stmt.to_string();
748
749        // Remove schema prefix
750        result = Self::strip_schema_prefix(&result);
751
752        // Remove type casts
753        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        // Remove nextval() - DuckDB handles sequences differently
759        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        // Convert now() to CURRENT_TIMESTAMP
764        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        // Remove INHERITS clause
771        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        // Remove WITH clause (storage parameters)
776        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    /// Strip schema prefix (e.g., public.users -> users)
783    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    /// Strip MSSQL schema prefix (dbo., etc.) for both CREATE TABLE and INSERT
790    fn strip_mssql_schema_prefix(stmt: &str) -> String {
791        // Remove schema prefix (dbo., schema.) - quoted or unquoted
792        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    /// Strip MSSQL-specific syntax
798    fn strip_mssql_syntax(stmt: &str) -> String {
799        let mut result = Self::strip_mssql_schema_prefix(stmt);
800
801        // Remove IDENTITY clause and make the column nullable (so INSERTs without id work)
802        // Pattern matches: INT IDENTITY(1,1) NOT NULL -> INT
803        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        // Also handle IDENTITY without NOT NULL
809        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        // Remove CLUSTERED/NONCLUSTERED
814        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        // Remove ON [PRIMARY] (filegroup)
819        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        // Remove PRIMARY KEY constraints (they make columns NOT NULL which breaks IDENTITY column INSERTs)
824        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        // Remove FOREIGN KEY constraints (analytics queries don't need FK enforcement)
830        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        // Remove WITH clause for indexes
836        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        // Remove TEXTIMAGE_ON
840        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        // Convert GETDATE() to CURRENT_TIMESTAMP
845        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        // Convert NEWID() to gen_random_uuid()
852        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    /// Strip SQLite-specific syntax not supported by DuckDB
861    fn strip_sqlite_syntax(stmt: &str) -> String {
862        let mut result = stmt.to_string();
863
864        // Remove AUTOINCREMENT (DuckDB handles auto-increment via sequences)
865        // SQLite uses "INTEGER PRIMARY KEY AUTOINCREMENT"
866        result = result.replace(" AUTOINCREMENT", "");
867        result = result.replace(" autoincrement", "");
868
869        // Remove IF NOT EXISTS (DuckDB supports this but we want clean imports)
870        // Actually DuckDB does support IF NOT EXISTS, so leave it
871
872        // Remove STRICT table modifier (SQLite 3.37+)
873        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        // Remove WITHOUT ROWID (SQLite optimization not needed for analytics)
877        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    /// Count rows in an INSERT statement
885    fn count_insert_rows(sql: &str) -> u64 {
886        // Count VALUES clauses by counting opening parentheses after VALUES
887        if let Some(values_pos) = sql.to_uppercase().find("VALUES") {
888            let after_values = &sql[values_pos + 6..];
889            // Count top-level opening parens (simple heuristic)
890            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        // The IDENTITY should have been stripped by strip_mssql_syntax
963        let result = DumpLoader::strip_mssql_syntax(sql);
964        assert!(!result.contains("IDENTITY"), "IDENTITY should be stripped");
965
966        // Test with IDENTITY(1,1) NOT NULL
967        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        // Since we strip IDENTITY(1,1) NOT NULL, the column should become nullable
978        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}