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::{copy_to_inserts, parse_copy_header, CopyHeader};
7use crate::parser::{
8    detect_dialect_from_file, parse_insert_for_bulk, Parser, SqlDialect, StatementType,
9};
10use anyhow::{Context, Result};
11use duckdb::Connection;
12use indicatif::{ProgressBar, ProgressStyle};
13use once_cell::sync::Lazy;
14use regex::Regex;
15use std::io::{BufRead, BufReader, Read};
16use std::path::Path;
17
18/// Maximum COPY rows to accumulate per batch before converting to INSERTs.
19/// This bounds memory usage while still enabling large batches for performance.
20const MAX_COPY_ROWS_PER_BATCH: usize = 10_000;
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        let buf_reader = BufReader::with_capacity(256 * 1024, reader);
84
85        // Parse and load statements
86        self.load_statements(buf_reader, dialect, &mut stats)?;
87
88        if let Some(pb) = progress_bar {
89            pb.finish_with_message("Import complete");
90        }
91
92        stats.duration_secs = start.elapsed().as_secs_f64();
93        Ok(stats)
94    }
95
96    /// Load statements from a reader
97    fn load_statements<R: Read>(
98        &self,
99        reader: BufReader<R>,
100        dialect: SqlDialect,
101        stats: &mut ImportStats,
102    ) -> Result<()> {
103        let mut parser = StatementReader::new(reader, dialect);
104        let mut pending_copy: Option<CopyHeader> = None;
105
106        // Batched COPY data accumulator
107        let mut copy_batch_data: Vec<u8> = Vec::new();
108        let mut copy_batch_rows: usize = 0;
109
110        // Track tables that failed (don't exist) to skip subsequent inserts
111        let mut failed_tables: std::collections::HashSet<String> = std::collections::HashSet::new();
112
113        // Batch manager for bulk INSERT loading via Appender API
114        let mut batch_mgr = BatchManager::new(MAX_ROWS_PER_BATCH);
115
116        while let Some(stmt_result) = parser.next_statement() {
117            let stmt = stmt_result?;
118
119            // Handle COPY data blocks with batching
120            if let Some(ref header) = pending_copy {
121                let trimmed = stmt.trim();
122
123                // End-of-COPY marker: "\."
124                if trimmed == "\\." {
125                    // Flush any remaining batched rows
126                    if !copy_batch_data.is_empty() {
127                        self.process_copy_batch(
128                            header,
129                            &copy_batch_data,
130                            stats,
131                            &mut failed_tables,
132                        );
133                        copy_batch_data.clear();
134                        copy_batch_rows = 0;
135                    }
136                    pending_copy = None;
137                    parser.set_copy_mode(false);
138                    continue;
139                }
140
141                // Empty/whitespace line inside COPY: skip
142                if trimmed.is_empty() {
143                    continue;
144                }
145
146                // Normal COPY data line - accumulate into batch
147                if Self::looks_like_copy_data(&stmt) {
148                    // Skip if we know this table doesn't exist
149                    if failed_tables.contains(&header.table) {
150                        continue;
151                    }
152
153                    copy_batch_data.extend_from_slice(stmt.as_bytes());
154                    copy_batch_data.push(b'\n');
155                    copy_batch_rows += 1;
156
157                    // Flush when batch gets large enough
158                    if copy_batch_rows >= MAX_COPY_ROWS_PER_BATCH {
159                        self.process_copy_batch(
160                            header,
161                            &copy_batch_data,
162                            stats,
163                            &mut failed_tables,
164                        );
165                        copy_batch_data.clear();
166                        copy_batch_rows = 0;
167                    }
168                    continue;
169                }
170
171                // Unexpected content inside COPY - flush and fall through to normal handling
172                if !copy_batch_data.is_empty() {
173                    self.process_copy_batch(header, &copy_batch_data, stats, &mut failed_tables);
174                    copy_batch_data.clear();
175                    copy_batch_rows = 0;
176                }
177                pending_copy = None;
178                parser.set_copy_mode(false);
179                // Fall through to normal statement handling
180            }
181
182            let (mut stmt_type, table_name) =
183                Parser::<&[u8]>::parse_statement_with_dialect(stmt.as_bytes(), dialect);
184
185            // For Postgres, check if statement contains COPY ... FROM stdin (may be after comments)
186            if dialect == SqlDialect::Postgres && stmt_type == StatementType::Unknown {
187                let upper = stmt.to_uppercase();
188                if let Some(copy_pos) = upper.find("COPY ") {
189                    let after_copy = &upper[copy_pos..];
190                    if after_copy.contains("FROM STDIN") {
191                        stmt_type = StatementType::Copy;
192                    }
193                }
194            }
195
196            // Filter tables if specified
197            if let Some(ref tables) = self.config.tables {
198                if !table_name.is_empty()
199                    && !tables.iter().any(|t| t.eq_ignore_ascii_case(&table_name))
200                {
201                    continue;
202                }
203            }
204
205            match stmt_type {
206                StatementType::CreateTable => {
207                    let duckdb_sql = self.convert_create_table(&stmt, dialect)?;
208                    match self.conn.execute(&duckdb_sql, []) {
209                        Ok(_) => stats.tables_created += 1,
210                        Err(e) => {
211                            stats
212                                .warnings
213                                .push(format!("Failed to create table {}: {}", table_name, e));
214                            stats.statements_skipped += 1;
215                        }
216                    }
217                }
218                StatementType::Insert => {
219                    // Try bulk loading via Appender API first
220                    if !self.try_queue_for_bulk(
221                        &stmt,
222                        dialect,
223                        &mut batch_mgr,
224                        stats,
225                        &mut failed_tables,
226                    ) {
227                        // Fallback to direct execution
228                        let duckdb_sql = self.convert_insert(&stmt, dialect)?;
229                        match self.conn.execute(&duckdb_sql, []) {
230                            Ok(_) => {
231                                stats.insert_statements += 1;
232                                stats.rows_inserted += Self::count_insert_rows(&duckdb_sql);
233                            }
234                            Err(e) => {
235                                stats
236                                    .warnings
237                                    .push(format!("Failed INSERT for {}: {}", table_name, e));
238                                stats.statements_skipped += 1;
239                            }
240                        }
241                    }
242
243                    // Flush any ready batches
244                    for mut batch in batch_mgr.get_ready_batches() {
245                        flush_batch(self.conn, &mut batch, stats, &mut failed_tables)?;
246                    }
247                }
248                StatementType::Copy => {
249                    // Parse COPY header and start buffering data
250                    if let Some(header) = parse_copy_header(&stmt) {
251                        // Check if table already known to be missing
252                        if failed_tables.contains(&header.table) {
253                            // Enter COPY mode to skip line-by-line, then exit
254                            parser.set_copy_mode(true);
255                            Self::skip_copy_block(&mut parser);
256                            parser.set_copy_mode(false);
257                            continue;
258                        }
259
260                        // Proactively check if table exists before buffering data
261                        if !self.table_exists(&header.table) {
262                            failed_tables.insert(header.table.clone());
263                            if stats.warnings.len() < 100 {
264                                stats.warnings.push(format!(
265                                    "Skipping COPY for non-existent table {}",
266                                    header.table
267                                ));
268                            }
269                            // Enter COPY mode to skip line-by-line, then exit
270                            parser.set_copy_mode(true);
271                            Self::skip_copy_block(&mut parser);
272                            parser.set_copy_mode(false);
273                            continue;
274                        }
275
276                        copy_batch_data.clear();
277                        copy_batch_rows = 0;
278                        pending_copy = Some(header);
279                        parser.set_copy_mode(true);
280                    }
281                }
282                StatementType::CreateIndex => {
283                    // Skip indexes - not needed for analytics queries
284                    stats.statements_skipped += 1;
285                }
286                _ => {
287                    // Skip other statements (ALTER, DROP, etc.)
288                    stats.statements_skipped += 1;
289                }
290            }
291        }
292
293        // Flush any remaining COPY batch (handles truncated dumps)
294        if let Some(ref header) = pending_copy {
295            if !copy_batch_data.is_empty() {
296                self.process_copy_batch(header, &copy_batch_data, stats, &mut failed_tables);
297            }
298        }
299
300        // Flush any remaining INSERT batches
301        for mut batch in batch_mgr.drain_all() {
302            flush_batch(self.conn, &mut batch, stats, &mut failed_tables)?;
303        }
304
305        Ok(())
306    }
307
308    /// Process a batch of COPY data rows, converting them to INSERTs
309    fn process_copy_batch(
310        &self,
311        header: &CopyHeader,
312        batch_data: &[u8],
313        stats: &mut ImportStats,
314        failed_tables: &mut std::collections::HashSet<String>,
315    ) {
316        if batch_data.is_empty() {
317            return;
318        }
319
320        // Skip if we already know this table doesn't exist
321        if failed_tables.contains(&header.table) {
322            return;
323        }
324
325        let inserts = copy_to_inserts(header, batch_data, SqlDialect::Postgres);
326        for insert in inserts {
327            let insert_sql = String::from_utf8_lossy(&insert);
328            match self.conn.execute(&insert_sql, []) {
329                Ok(_) => {
330                    stats.rows_inserted += Self::count_insert_rows(&insert_sql);
331                }
332                Err(e) => {
333                    let err_str = e.to_string();
334                    // If table doesn't exist, mark it and skip future inserts
335                    if err_str.contains("does not exist") {
336                        failed_tables.insert(header.table.clone());
337                        if stats.warnings.len() < 100 {
338                            stats.warnings.push(format!(
339                                "Table {} does not exist, skipping COPY data",
340                                header.table
341                            ));
342                        }
343                        return; // Skip rest of batch
344                    }
345                    // Limit warnings to avoid memory bloat on large failures
346                    if stats.warnings.len() < 100 {
347                        stats.warnings.push(format!(
348                            "Failed to insert COPY data for {}: {}",
349                            header.table, e
350                        ));
351                    }
352                    stats.statements_skipped += 1;
353                }
354            }
355        }
356    }
357
358    /// Check if a table exists in DuckDB
359    fn table_exists(&self, table: &str) -> bool {
360        let query = "SELECT 1 FROM information_schema.tables WHERE table_name = ? LIMIT 1";
361        match self.conn.prepare(query) {
362            Ok(mut stmt) => stmt.exists([table]).unwrap_or(false),
363            Err(_) => false,
364        }
365    }
366
367    /// Try to queue an INSERT statement for bulk loading via Appender API.
368    /// Returns true if successfully queued, false if fallback to direct execution is needed.
369    fn try_queue_for_bulk(
370        &self,
371        stmt: &str,
372        dialect: SqlDialect,
373        batch_mgr: &mut BatchManager,
374        stats: &mut ImportStats,
375        failed_tables: &mut std::collections::HashSet<String>,
376    ) -> bool {
377        // Quick filter: skip statements with complex clauses that Appender can't handle
378        let upper = stmt.to_uppercase();
379        if upper.contains("ON DUPLICATE KEY")
380            || upper.contains("ON CONFLICT")
381            || upper.contains("REPLACE")
382            || upper.contains("IGNORE")
383            || upper.contains("RETURNING")
384            || upper.contains("SELECT")
385        {
386            return false;
387        }
388
389        // Try to parse the INSERT statement
390        let parsed = match parse_insert_for_bulk(stmt.as_bytes(), dialect) {
391            Ok(p) => p,
392            Err(_) => return false, // Parse failed, use fallback
393        };
394
395        // Skip tables we know don't exist
396        if failed_tables.contains(&parsed.table) {
397            return true; // Pretend we handled it to skip the statement
398        }
399
400        // Skip if no rows were parsed
401        if parsed.rows.is_empty() {
402            return false;
403        }
404
405        // Convert the statement for DuckDB (for fallback)
406        let duckdb_sql = match self.convert_insert(stmt, dialect) {
407            Ok(sql) => sql,
408            Err(_) => return false,
409        };
410
411        // Queue the rows
412        if let Some(mut batch) =
413            batch_mgr.queue_insert(&parsed.table, parsed.columns, parsed.rows, duckdb_sql)
414        {
415            // Batch is ready to flush
416            if let Err(e) = flush_batch(self.conn, &mut batch, stats, failed_tables) {
417                if stats.warnings.len() < 100 {
418                    stats.warnings.push(format!("Batch flush error: {}", e));
419                }
420            }
421        }
422
423        true
424    }
425
426    /// Skip a COPY data block without parsing/processing it
427    fn skip_copy_block<R: Read>(parser: &mut StatementReader<R>) {
428        while let Some(Ok(line)) = parser.next_statement() {
429            if line.trim() == "\\." {
430                break;
431            }
432        }
433    }
434
435    /// Check if a line looks like COPY data (tab-separated values or single-column values)
436    fn looks_like_copy_data(line: &str) -> bool {
437        let trimmed = line.trim();
438
439        // Empty line is not COPY data
440        if trimmed.is_empty() {
441            return false;
442        }
443
444        // End-of-COPY marker
445        if trimmed == "\\." {
446            return false;
447        }
448
449        // Lines with tabs are definitely COPY data (multi-column)
450        // For single-column data, we need to check it doesn't look like SQL
451        let first_char = trimmed.chars().next().unwrap_or(' ');
452
453        // Quick check: if starts with common SQL keyword first char, verify it's not SQL
454        if matches!(
455            first_char,
456            'S' | 's'
457                | 'I'
458                | 'i'
459                | 'C'
460                | 'c'
461                | 'D'
462                | 'd'
463                | 'A'
464                | 'a'
465                | 'U'
466                | 'u'
467                | 'G'
468                | 'g'
469                | '-'
470                | '/'
471        ) {
472            let upper_prefix: String = trimmed.chars().take(7).collect::<String>().to_uppercase();
473            if upper_prefix.starts_with("SELECT")
474                || upper_prefix.starts_with("INSERT")
475                || upper_prefix.starts_with("CREATE")
476                || upper_prefix.starts_with("DROP")
477                || upper_prefix.starts_with("ALTER")
478                || upper_prefix.starts_with("UPDATE")
479                || upper_prefix.starts_with("GRANT")
480                || upper_prefix.starts_with("--")
481                || upper_prefix.starts_with("/*")
482            {
483                return false;
484            }
485        }
486
487        // If it contains a tab, it's multi-column COPY data
488        // If it doesn't contain a tab but passed the SQL check, it's single-column data
489        true
490    }
491
492    /// Convert a CREATE TABLE statement to DuckDB-compatible SQL
493    fn convert_create_table(&self, stmt: &str, dialect: SqlDialect) -> Result<String> {
494        let mut result = stmt.to_string();
495
496        // Convert identifier quoting
497        result = Self::convert_identifiers(&result, dialect);
498
499        // Remove MySQL-specific clauses FIRST (before type conversion)
500        // This prevents "CHARACTER SET" from being confused with "CHAR" type
501        result = Self::strip_mysql_clauses(&result);
502
503        // Convert data types in column definitions
504        result = Self::convert_types_in_statement(&result);
505
506        // Remove PostgreSQL-specific syntax
507        if dialect == SqlDialect::Postgres {
508            result = Self::strip_postgres_syntax(&result);
509        }
510
511        // Remove MSSQL-specific syntax
512        if dialect == SqlDialect::Mssql {
513            result = Self::strip_mssql_syntax(&result);
514        }
515
516        // Remove SQLite-specific syntax
517        if dialect == SqlDialect::Sqlite {
518            result = Self::strip_sqlite_syntax(&result);
519        }
520
521        Ok(result)
522    }
523
524    /// Convert an INSERT statement to DuckDB-compatible SQL
525    fn convert_insert(&self, stmt: &str, dialect: SqlDialect) -> Result<String> {
526        let mut result = stmt.to_string();
527
528        // Convert identifier quoting
529        result = Self::convert_identifiers(&result, dialect);
530
531        // Convert MySQL backslash escapes to SQL standard
532        if dialect == SqlDialect::MySql {
533            result = Self::convert_mysql_escapes(&result);
534        }
535
536        // Remove PostgreSQL schema prefix
537        if dialect == SqlDialect::Postgres {
538            result = Self::strip_schema_prefix(&result);
539        }
540
541        // Remove MSSQL schema prefix (dbo., etc.)
542        if dialect == SqlDialect::Mssql {
543            result = Self::strip_mssql_schema_prefix(&result);
544        }
545
546        Ok(result)
547    }
548
549    /// Convert MySQL backslash escapes to SQL standard
550    fn convert_mysql_escapes(stmt: &str) -> String {
551        let mut result = String::with_capacity(stmt.len() + 100);
552        let mut chars = stmt.chars().peekable();
553        let mut in_string = false;
554
555        while let Some(c) = chars.next() {
556            if c == '\'' {
557                in_string = !in_string;
558                result.push(c);
559            } else if c == '\\' && in_string {
560                // Handle MySQL escape sequences
561                match chars.peek() {
562                    Some('\'') => {
563                        // \' -> ''
564                        chars.next();
565                        result.push_str("''");
566                    }
567                    Some('\\') => {
568                        // \\ -> \
569                        chars.next();
570                        result.push('\\');
571                    }
572                    Some('n') => {
573                        // \n -> newline
574                        chars.next();
575                        result.push('\n');
576                    }
577                    Some('r') => {
578                        // \r -> carriage return
579                        chars.next();
580                        result.push('\r');
581                    }
582                    Some('t') => {
583                        // \t -> tab
584                        chars.next();
585                        result.push('\t');
586                    }
587                    Some('0') => {
588                        // \0 -> NULL character (skip)
589                        chars.next();
590                    }
591                    Some('"') => {
592                        // \" -> "
593                        chars.next();
594                        result.push('"');
595                    }
596                    _ => {
597                        // Unknown escape, keep backslash
598                        result.push(c);
599                    }
600                }
601            } else {
602                result.push(c);
603            }
604        }
605        result
606    }
607
608    /// Convert identifier quoting (backticks/brackets to double quotes)
609    fn convert_identifiers(stmt: &str, dialect: SqlDialect) -> String {
610        match dialect {
611            SqlDialect::MySql => {
612                // Convert backticks to double quotes
613                let mut result = String::with_capacity(stmt.len());
614                let mut in_string = false;
615                let mut in_backtick = false;
616
617                for c in stmt.chars() {
618                    if c == '\'' && !in_backtick {
619                        in_string = !in_string;
620                        result.push(c);
621                    } else if c == '`' && !in_string {
622                        in_backtick = !in_backtick;
623                        result.push('"');
624                    } else {
625                        result.push(c);
626                    }
627                }
628                result
629            }
630            SqlDialect::Mssql => {
631                // Convert brackets to double quotes, strip N prefix from strings
632                let mut result = String::with_capacity(stmt.len());
633                let mut in_string = false;
634                let mut in_bracket = false;
635                let mut chars = stmt.chars().peekable();
636
637                while let Some(c) = chars.next() {
638                    if c == '\'' && !in_bracket {
639                        in_string = !in_string;
640                        result.push(c);
641                    } else if c == '[' && !in_string {
642                        in_bracket = true;
643                        result.push('"');
644                    } else if c == ']' && !in_string {
645                        // Handle ]] escape
646                        if chars.peek() == Some(&']') {
647                            chars.next();
648                            result.push(']');
649                        } else {
650                            in_bracket = false;
651                            result.push('"');
652                        }
653                    } else if c == 'N' && !in_string && !in_bracket && chars.peek() == Some(&'\'') {
654                        // Strip N prefix from N'string'
655                        // Don't push the N, the quote will be pushed in next iteration
656                    } else {
657                        result.push(c);
658                    }
659                }
660                result
661            }
662            _ => stmt.to_string(),
663        }
664    }
665
666    /// Convert SQL types in a statement
667    fn convert_types_in_statement(stmt: &str) -> String {
668        // Pattern to match column definitions with types
669        // Handles: TYPE, TYPE(size), TYPE UNSIGNED, TYPE WITH TIME ZONE
670        // IMPORTANT: Order matters - longer types first to avoid partial matches (INTEGER before INT)
671        // IMPORTANT: Types must be preceded by quote/whitespace AND followed by whitespace/paren/comma (not a closing quote)
672        // This prevents matching "date" as DATE type (column names inside quotes)
673        // Includes MySQL, PostgreSQL, SQLite, and MSSQL types
674        static RE_COLUMN_TYPE: Lazy<Regex> = Lazy::new(|| {
675            Regex::new(r#"(?i)(["'`\]\s])\s*(BIGSERIAL|SMALLSERIAL|SERIAL|BIGINT|SMALLINT|MEDIUMINT|TINYINT|INTEGER|INT|DOUBLE\s+PRECISION|DOUBLE|FLOAT|DECIMAL|NUMERIC|CHARACTER\s+VARYING|NVARCHAR|NCHAR|VARCHAR|CHAR|VARBINARY|BINARY|LONGTEXT|MEDIUMTEXT|TINYTEXT|NTEXT|TEXT|LONGBLOB|MEDIUMBLOB|TINYBLOB|IMAGE|BLOB|DATETIME2|DATETIMEOFFSET|SMALLDATETIME|DATETIME|TIMESTAMPTZ|TIMESTAMP|TIMETZ|TIME|DATE|YEAR|ENUM|SET|JSONB|JSON|UUID|UNIQUEIDENTIFIER|BYTEA|BOOLEAN|BOOL|BIT|REAL|MONEY|SMALLMONEY|INTERVAL|ROWVERSION|XML|SQL_VARIANT)\b(\s*\([^)]+\))?(\s+(?:UNSIGNED|WITH(?:OUT)?\s+TIME\s+ZONE))?"#).unwrap()
676        });
677
678        RE_COLUMN_TYPE
679            .replace_all(stmt, |caps: &regex::Captures| {
680                let full_match = caps.get(0).unwrap().as_str();
681                let leading_char = caps.get(1).unwrap().as_str();
682                let type_part = caps.get(2).unwrap().as_str();
683                let size_part = caps.get(3).map(|m| m.as_str()).unwrap_or("");
684                let suffix = caps.get(4).map(|m| m.as_str()).unwrap_or("");
685
686                // Check if this looks like a quoted identifier (type is inside quotes)
687                // If leading char is a quote and the character before the match is also a quote, skip
688                let end_pos = caps.get(0).unwrap().end();
689                let stmt_bytes = stmt.as_bytes();
690                if end_pos < stmt_bytes.len() {
691                    let next_char = stmt_bytes[end_pos] as char;
692                    // If next character is a closing quote, this is a quoted identifier, not a type
693                    if next_char == '"' || next_char == '\'' || next_char == '`' {
694                        return full_match.to_string();
695                    }
696                }
697
698                // Calculate the whitespace between leading char and type
699                let ws_len = full_match.len()
700                    - leading_char.len()
701                    - type_part.len()
702                    - size_part.len()
703                    - suffix.len();
704                let ws = &full_match[leading_char.len()..leading_char.len() + ws_len];
705
706                let converted =
707                    TypeConverter::convert(&format!("{}{}{}", type_part, size_part, suffix));
708                format!("{}{}{}", leading_char, ws, converted)
709            })
710            .to_string()
711    }
712
713    /// Strip MySQL-specific clauses
714    fn strip_mysql_clauses(stmt: &str) -> String {
715        let mut result = stmt.to_string();
716
717        // Remove ENGINE clause
718        static RE_ENGINE: Lazy<Regex> =
719            Lazy::new(|| Regex::new(r"(?i)\s*ENGINE\s*=\s*\w+").unwrap());
720        result = RE_ENGINE.replace_all(&result, "").to_string();
721
722        // Remove AUTO_INCREMENT clause at table level
723        static RE_AUTO_INC: Lazy<Regex> =
724            Lazy::new(|| Regex::new(r"(?i)\s*AUTO_INCREMENT\s*=\s*\d+").unwrap());
725        result = RE_AUTO_INC.replace_all(&result, "").to_string();
726
727        // Remove column AUTO_INCREMENT
728        result = result.replace(" AUTO_INCREMENT", "");
729        result = result.replace(" auto_increment", "");
730
731        // Remove CHARACTER SET in column definitions (must come before CHARSET)
732        static RE_CHAR_SET: Lazy<Regex> =
733            Lazy::new(|| Regex::new(r"(?i)\s*CHARACTER\s+SET\s+\w+").unwrap());
734        result = RE_CHAR_SET.replace_all(&result, "").to_string();
735
736        // Remove DEFAULT CHARSET
737        static RE_CHARSET: Lazy<Regex> =
738            Lazy::new(|| Regex::new(r"(?i)\s*(DEFAULT\s+)?CHARSET\s*=\s*\w+").unwrap());
739        result = RE_CHARSET.replace_all(&result, "").to_string();
740
741        // Remove COLLATE
742        static RE_COLLATE: Lazy<Regex> =
743            Lazy::new(|| Regex::new(r"(?i)\s*COLLATE\s*=?\s*\w+").unwrap());
744        result = RE_COLLATE.replace_all(&result, "").to_string();
745
746        // Remove ROW_FORMAT
747        static RE_ROW_FORMAT: Lazy<Regex> =
748            Lazy::new(|| Regex::new(r"(?i)\s*ROW_FORMAT\s*=\s*\w+").unwrap());
749        result = RE_ROW_FORMAT.replace_all(&result, "").to_string();
750
751        // Remove KEY_BLOCK_SIZE
752        static RE_KEY_BLOCK: Lazy<Regex> =
753            Lazy::new(|| Regex::new(r"(?i)\s*KEY_BLOCK_SIZE\s*=\s*\d+").unwrap());
754        result = RE_KEY_BLOCK.replace_all(&result, "").to_string();
755
756        // Remove COMMENT
757        static RE_COMMENT: Lazy<Regex> =
758            Lazy::new(|| Regex::new(r"(?i)\s*COMMENT\s*=?\s*'[^']*'").unwrap());
759        result = RE_COMMENT.replace_all(&result, "").to_string();
760
761        // Remove MySQL conditional comments
762        static RE_COND_COMMENT: Lazy<Regex> = Lazy::new(|| Regex::new(r"/\*!\d+\s*|\*/").unwrap());
763        result = RE_COND_COMMENT.replace_all(&result, "").to_string();
764
765        // Remove ON UPDATE CURRENT_TIMESTAMP
766        static RE_ON_UPDATE: Lazy<Regex> =
767            Lazy::new(|| Regex::new(r"(?i)\s*ON\s+UPDATE\s+CURRENT_TIMESTAMP").unwrap());
768        result = RE_ON_UPDATE.replace_all(&result, "").to_string();
769
770        // Remove UNIQUE KEY constraint lines: UNIQUE KEY `name` (`col1`, `col2`)
771        // Must handle both: ,UNIQUE KEY... at end of column list and UNIQUE KEY... on its own line
772        static RE_UNIQUE_KEY: Lazy<Regex> = Lazy::new(|| {
773            Regex::new(r#"(?i),?\s*UNIQUE\s+KEY\s+[`"']?\w+[`"']?\s*\([^)]+\)"#).unwrap()
774        });
775        result = RE_UNIQUE_KEY.replace_all(&result, "").to_string();
776
777        // Remove KEY (index) constraint lines: KEY `name` (`col1`, `col2`)
778        // This handles regular indexes and FULLTEXT indexes, but NOT PRIMARY KEY or FOREIGN KEY
779        // We use a negative lookbehind pattern by only matching KEY that is preceded by comma or newline (not FOREIGN/PRIMARY)
780        static RE_KEY_INDEX: Lazy<Regex> = Lazy::new(|| {
781            Regex::new(
782                r#"(?i)(?:,\s*|\n\s*)(?:FULLTEXT\s+|SPATIAL\s+)?KEY\s+[`"']?\w+[`"']?\s*\([^)]+\)"#,
783            )
784            .unwrap()
785        });
786        result = RE_KEY_INDEX.replace_all(&result, "").to_string();
787
788        // Remove GENERATED ALWAYS AS columns entirely
789        // Match: `col` TYPE GENERATED ALWAYS AS (expr) STORED/VIRTUAL
790        // The expression can contain nested parentheses so we match one level deep
791        static RE_GENERATED_COL: Lazy<Regex> = Lazy::new(|| {
792            Regex::new(r#"(?i),?\s*[`"']?\w+[`"']?\s+\w+\s+GENERATED\s+ALWAYS\s+AS\s*\((?:[^()]+|\([^()]*\))+\)\s*(?:STORED|VIRTUAL)?"#).unwrap()
793        });
794        result = RE_GENERATED_COL.replace_all(&result, "").to_string();
795
796        // Remove entire FOREIGN KEY constraints (DuckDB enforces them which causes issues with batch loading)
797        // Match: CONSTRAINT `name` FOREIGN KEY (...) REFERENCES ... [ON DELETE/UPDATE ...]
798        // or just: FOREIGN KEY (...) REFERENCES ... [ON DELETE/UPDATE ...]
799        static RE_FK_CONSTRAINT: Lazy<Regex> = Lazy::new(|| {
800            Regex::new(r#"(?i),?\s*(?:CONSTRAINT\s+[`"']?\w+[`"']?\s+)?FOREIGN\s+KEY\s*\([^)]+\)\s*REFERENCES\s+[`"']?\w+[`"']?\s*\([^)]+\)(?:\s+ON\s+(?:DELETE|UPDATE)\s+(?:CASCADE|SET\s+NULL|SET\s+DEFAULT|NO\s+ACTION|RESTRICT))*"#).unwrap()
801        });
802        result = RE_FK_CONSTRAINT.replace_all(&result, "").to_string();
803
804        result
805    }
806
807    /// Strip PostgreSQL-specific syntax
808    fn strip_postgres_syntax(stmt: &str) -> String {
809        let mut result = stmt.to_string();
810
811        // Remove schema prefix
812        result = Self::strip_schema_prefix(&result);
813
814        // Remove type casts
815        static RE_CAST: Lazy<Regex> = Lazy::new(|| {
816            Regex::new(r"::[a-zA-Z_][a-zA-Z0-9_]*(?:\s+[a-zA-Z_][a-zA-Z0-9_]*)*").unwrap()
817        });
818        result = RE_CAST.replace_all(&result, "").to_string();
819
820        // Remove nextval() - DuckDB handles sequences differently
821        static RE_NEXTVAL: Lazy<Regex> =
822            Lazy::new(|| Regex::new(r"(?i)\s*DEFAULT\s+nextval\s*\([^)]+\)").unwrap());
823        result = RE_NEXTVAL.replace_all(&result, "").to_string();
824
825        // Convert now() to CURRENT_TIMESTAMP
826        static RE_NOW: Lazy<Regex> =
827            Lazy::new(|| Regex::new(r"(?i)\bDEFAULT\s+now\s*\(\s*\)").unwrap());
828        result = RE_NOW
829            .replace_all(&result, "DEFAULT CURRENT_TIMESTAMP")
830            .to_string();
831
832        // Remove INHERITS clause
833        static RE_INHERITS: Lazy<Regex> =
834            Lazy::new(|| Regex::new(r"(?i)\s*INHERITS\s*\([^)]+\)").unwrap());
835        result = RE_INHERITS.replace_all(&result, "").to_string();
836
837        // Remove WITH clause (storage parameters)
838        static RE_WITH: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\s*WITH\s*\([^)]+\)").unwrap());
839        result = RE_WITH.replace_all(&result, "").to_string();
840
841        result
842    }
843
844    /// Strip schema prefix (e.g., public.users -> users)
845    fn strip_schema_prefix(stmt: &str) -> String {
846        static RE_SCHEMA: Lazy<Regex> =
847            Lazy::new(|| Regex::new(r#"(?i)\b(public|pg_catalog|pg_temp)\s*\.\s*"#).unwrap());
848        RE_SCHEMA.replace_all(stmt, "").to_string()
849    }
850
851    /// Strip MSSQL schema prefix (dbo., etc.) for both CREATE TABLE and INSERT
852    fn strip_mssql_schema_prefix(stmt: &str) -> String {
853        // Remove schema prefix (dbo., schema.) - quoted or unquoted
854        static RE_SCHEMA: Lazy<Regex> =
855            Lazy::new(|| Regex::new(r#"(?i)"?(dbo|master|tempdb|model|msdb)"?\s*\.\s*"#).unwrap());
856        RE_SCHEMA.replace_all(stmt, "").to_string()
857    }
858
859    /// Strip MSSQL-specific syntax
860    fn strip_mssql_syntax(stmt: &str) -> String {
861        let mut result = Self::strip_mssql_schema_prefix(stmt);
862
863        // Remove IDENTITY clause and make the column nullable (so INSERTs without id work)
864        // Pattern matches: INT IDENTITY(1,1) NOT NULL -> INT
865        static RE_IDENTITY_NOT_NULL: Lazy<Regex> = Lazy::new(|| {
866            Regex::new(r"(?i)\s*IDENTITY\s*\(\s*\d+\s*,\s*\d+\s*\)\s*NOT\s+NULL").unwrap()
867        });
868        result = RE_IDENTITY_NOT_NULL.replace_all(&result, "").to_string();
869
870        // Also handle IDENTITY without NOT NULL
871        static RE_IDENTITY: Lazy<Regex> =
872            Lazy::new(|| Regex::new(r"(?i)\s*IDENTITY\s*\(\s*\d+\s*,\s*\d+\s*\)").unwrap());
873        result = RE_IDENTITY.replace_all(&result, "").to_string();
874
875        // Remove CLUSTERED/NONCLUSTERED
876        static RE_CLUSTERED: Lazy<Regex> =
877            Lazy::new(|| Regex::new(r"(?i)\s*(?:NON)?CLUSTERED\s*").unwrap());
878        result = RE_CLUSTERED.replace_all(&result, " ").to_string();
879
880        // Remove ON [PRIMARY] (filegroup)
881        static RE_FILEGROUP: Lazy<Regex> =
882            Lazy::new(|| Regex::new(r#"(?i)\s*ON\s*"?PRIMARY"?"#).unwrap());
883        result = RE_FILEGROUP.replace_all(&result, "").to_string();
884
885        // Remove PRIMARY KEY constraints (they make columns NOT NULL which breaks IDENTITY column INSERTs)
886        static RE_PK_CONSTRAINT: Lazy<Regex> = Lazy::new(|| {
887            Regex::new(r#"(?i),?\s*CONSTRAINT\s+"?\w+"?\s+PRIMARY\s+KEY\s+\([^)]+\)"#).unwrap()
888        });
889        result = RE_PK_CONSTRAINT.replace_all(&result, "").to_string();
890
891        // Remove FOREIGN KEY constraints (analytics queries don't need FK enforcement)
892        static RE_FK_CONSTRAINT: Lazy<Regex> = Lazy::new(|| {
893            Regex::new(r#"(?i),?\s*CONSTRAINT\s+"?\w+"?\s+FOREIGN\s+KEY\s*\([^)]+\)\s*REFERENCES\s+[^\s(]+\s*\([^)]+\)"#).unwrap()
894        });
895        result = RE_FK_CONSTRAINT.replace_all(&result, "").to_string();
896
897        // Remove WITH clause for indexes
898        static RE_WITH: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\s*WITH\s*\([^)]+\)").unwrap());
899        result = RE_WITH.replace_all(&result, "").to_string();
900
901        // Remove TEXTIMAGE_ON
902        static RE_TEXTIMAGE: Lazy<Regex> =
903            Lazy::new(|| Regex::new(r#"(?i)\s*TEXTIMAGE_ON\s*"?\w+"?"#).unwrap());
904        result = RE_TEXTIMAGE.replace_all(&result, "").to_string();
905
906        // Convert GETDATE() to CURRENT_TIMESTAMP
907        static RE_GETDATE: Lazy<Regex> =
908            Lazy::new(|| Regex::new(r"(?i)\bGETDATE\s*\(\s*\)").unwrap());
909        result = RE_GETDATE
910            .replace_all(&result, "CURRENT_TIMESTAMP")
911            .to_string();
912
913        // Convert NEWID() to gen_random_uuid()
914        static RE_NEWID: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bNEWID\s*\(\s*\)").unwrap());
915        result = RE_NEWID
916            .replace_all(&result, "gen_random_uuid()")
917            .to_string();
918
919        result
920    }
921
922    /// Strip SQLite-specific syntax not supported by DuckDB
923    fn strip_sqlite_syntax(stmt: &str) -> String {
924        let mut result = stmt.to_string();
925
926        // Remove AUTOINCREMENT (DuckDB handles auto-increment via sequences)
927        // SQLite uses "INTEGER PRIMARY KEY AUTOINCREMENT"
928        result = result.replace(" AUTOINCREMENT", "");
929        result = result.replace(" autoincrement", "");
930
931        // Remove IF NOT EXISTS (DuckDB supports this but we want clean imports)
932        // Actually DuckDB does support IF NOT EXISTS, so leave it
933
934        // Remove STRICT table modifier (SQLite 3.37+)
935        static RE_STRICT: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\)\s*STRICT\s*;").unwrap());
936        result = RE_STRICT.replace_all(&result, ");").to_string();
937
938        // Remove WITHOUT ROWID (SQLite optimization not needed for analytics)
939        static RE_WITHOUT_ROWID: Lazy<Regex> =
940            Lazy::new(|| Regex::new(r"(?i)\)\s*WITHOUT\s+ROWID\s*;").unwrap());
941        result = RE_WITHOUT_ROWID.replace_all(&result, ");").to_string();
942
943        result
944    }
945
946    /// Count rows in an INSERT statement
947    fn count_insert_rows(sql: &str) -> u64 {
948        // Count VALUES clauses by counting opening parentheses after VALUES
949        if let Some(values_pos) = sql.to_uppercase().find("VALUES") {
950            let after_values = &sql[values_pos + 6..];
951            // Count top-level opening parens (simple heuristic)
952            let mut count = 0u64;
953            let mut depth = 0;
954            let mut in_string = false;
955            let mut prev_char = ' ';
956
957            for c in after_values.chars() {
958                if c == '\'' && prev_char != '\\' {
959                    in_string = !in_string;
960                }
961                if !in_string {
962                    if c == '(' {
963                        if depth == 0 {
964                            count += 1;
965                        }
966                        depth += 1;
967                    } else if c == ')' {
968                        depth -= 1;
969                    }
970                }
971                prev_char = c;
972            }
973            count
974        } else {
975            1
976        }
977    }
978}
979
980/// Statement reader that handles streaming SQL parsing
981struct StatementReader<R> {
982    reader: BufReader<R>,
983    dialect: SqlDialect,
984    buffer: String,
985    /// Position in buffer where unprocessed data starts (avoids O(n) shifts)
986    buffer_pos: usize,
987    eof: bool,
988    /// Track if we're inside a PostgreSQL COPY data block
989    in_copy_mode: bool,
990}
991
992impl<R: Read> StatementReader<R> {
993    fn new(reader: BufReader<R>, dialect: SqlDialect) -> Self {
994        Self {
995            reader,
996            dialect,
997            buffer: String::new(),
998            buffer_pos: 0,
999            eof: false,
1000            in_copy_mode: false,
1001        }
1002    }
1003
1004    /// Compact the buffer by removing already-processed data
1005    /// Only called periodically to avoid O(n²) behavior
1006    fn compact_buffer(&mut self) {
1007        if self.buffer_pos > 0 {
1008            self.buffer.drain(..self.buffer_pos);
1009            self.buffer_pos = 0;
1010        }
1011    }
1012
1013    /// Get the unprocessed portion of the buffer
1014    fn remaining_buffer(&self) -> &str {
1015        &self.buffer[self.buffer_pos..]
1016    }
1017
1018    /// Set COPY mode explicitly (called by DumpLoader when entering/exiting COPY blocks)
1019    fn set_copy_mode(&mut self, enabled: bool) {
1020        self.in_copy_mode = enabled;
1021    }
1022
1023    /// Strip leading SQL comments (-- and /* */) from a string
1024    fn strip_leading_sql_comments(s: &str) -> &str {
1025        let mut result = s.trim();
1026        loop {
1027            // Skip -- line comments
1028            if result.starts_with("--") {
1029                if let Some(pos) = result.find('\n') {
1030                    result = result[pos + 1..].trim();
1031                    continue;
1032                } else {
1033                    return ""; // Only comment, no newline
1034                }
1035            }
1036            // Skip /* */ block comments
1037            if result.starts_with("/*") {
1038                if let Some(pos) = result.find("*/") {
1039                    result = result[pos + 2..].trim();
1040                    continue;
1041                } else {
1042                    return ""; // Unclosed block comment
1043                }
1044            }
1045            break;
1046        }
1047        result
1048    }
1049
1050    fn next_statement(&mut self) -> Option<Result<String>> {
1051        if self.eof && self.remaining_buffer().is_empty() {
1052            return None;
1053        }
1054
1055        loop {
1056            // In COPY mode, return each line individually until we see \.
1057            if self.in_copy_mode {
1058                if let Some(line) = self.extract_copy_line() {
1059                    return Some(Ok(line));
1060                }
1061            } else {
1062                // Try to find a complete statement in the buffer
1063                if let Some(stmt) = self.extract_statement() {
1064                    // COPY mode is now managed explicitly by DumpLoader via set_copy_mode()
1065                    return Some(Ok(stmt));
1066                }
1067            }
1068
1069            // Compact buffer periodically to prevent unbounded growth
1070            // Only compact when processed portion is significant
1071            if self.buffer_pos > 64 * 1024 {
1072                self.compact_buffer();
1073            }
1074
1075            // Read more data
1076            let mut line = String::new();
1077            match self.reader.read_line(&mut line) {
1078                Ok(0) => {
1079                    self.eof = true;
1080                    self.in_copy_mode = false; // Reset on EOF
1081                    let remaining = self.remaining_buffer().trim();
1082                    if !remaining.is_empty() {
1083                        let stmt = remaining.to_string();
1084                        self.buffer.clear();
1085                        self.buffer_pos = 0;
1086                        return Some(Ok(stmt));
1087                    }
1088                    return None;
1089                }
1090                Ok(_) => {
1091                    self.buffer.push_str(&line);
1092                }
1093                Err(e) => return Some(Err(e.into())),
1094            }
1095        }
1096    }
1097
1098    /// Extract a single line from the buffer for COPY data mode
1099    fn extract_copy_line(&mut self) -> Option<String> {
1100        let remaining = self.remaining_buffer();
1101        if let Some(newline_pos) = remaining.find('\n') {
1102            let line = remaining[..newline_pos].to_string();
1103            self.buffer_pos += newline_pos + 1;
1104            // COPY mode is managed by DumpLoader via set_copy_mode(), not here
1105            Some(line)
1106        } else {
1107            None
1108        }
1109    }
1110
1111    fn extract_statement(&mut self) -> Option<String> {
1112        let remaining = self.remaining_buffer();
1113        let mut in_string = false;
1114        let mut in_dollar_quote = false;
1115        let mut in_bracket = false;
1116        let mut in_line_comment = false;
1117        let mut in_block_comment = false;
1118        let mut escape_next = false;
1119        let mut chars = remaining.char_indices().peekable();
1120        let mut end_pos = None;
1121
1122        // For MSSQL, check for GO at start of line
1123        if self.dialect == SqlDialect::Mssql {
1124            if let Some(go_pos) = self.find_go_separator() {
1125                let stmt = remaining[..go_pos].to_string();
1126                // Skip past GO and any whitespace
1127                let after_go = &remaining[go_pos..];
1128                if let Some(line_end) = after_go.find('\n') {
1129                    self.buffer_pos += go_pos + line_end + 1;
1130                } else {
1131                    self.buffer_pos = self.buffer.len();
1132                }
1133
1134                let trimmed = stmt.trim();
1135                if trimmed.is_empty()
1136                    || trimmed.starts_with("--")
1137                    || (trimmed.starts_with("/*") && !trimmed.contains("/*!"))
1138                {
1139                    return self.extract_statement();
1140                }
1141                return Some(stmt);
1142            }
1143        }
1144
1145        while let Some((i, c)) = chars.next() {
1146            if escape_next {
1147                escape_next = false;
1148                continue;
1149            }
1150
1151            // Handle line comments (-- to end of line)
1152            if in_line_comment {
1153                if c == '\n' {
1154                    in_line_comment = false;
1155                }
1156                continue;
1157            }
1158
1159            // Handle block comments (/* to */)
1160            if in_block_comment {
1161                if c == '*' && chars.peek().map(|(_, c)| *c == '/').unwrap_or(false) {
1162                    chars.next();
1163                    in_block_comment = false;
1164                }
1165                continue;
1166            }
1167
1168            match c {
1169                '\\' if self.dialect == SqlDialect::MySql && in_string => {
1170                    escape_next = true;
1171                }
1172                '\'' if !in_dollar_quote && !in_bracket => {
1173                    in_string = !in_string;
1174                }
1175                '[' if self.dialect == SqlDialect::Mssql && !in_string => {
1176                    in_bracket = true;
1177                }
1178                ']' if self.dialect == SqlDialect::Mssql && !in_string => {
1179                    // Handle ]] escape
1180                    if chars.peek().map(|(_, c)| *c == ']').unwrap_or(false) {
1181                        chars.next();
1182                    } else {
1183                        in_bracket = false;
1184                    }
1185                }
1186                '$' if self.dialect == SqlDialect::Postgres && !in_string => {
1187                    // Check for dollar quote
1188                    if chars.peek().map(|(_, c)| *c == '$').unwrap_or(false) {
1189                        in_dollar_quote = !in_dollar_quote;
1190                        chars.next();
1191                    }
1192                }
1193                '-' if !in_string && !in_dollar_quote && !in_bracket => {
1194                    // Check for -- line comment
1195                    if chars.peek().map(|(_, c)| *c == '-').unwrap_or(false) {
1196                        chars.next();
1197                        in_line_comment = true;
1198                    }
1199                }
1200                '/' if !in_string && !in_dollar_quote && !in_bracket => {
1201                    // Check for /* block comment
1202                    if chars.peek().map(|(_, c)| *c == '*').unwrap_or(false) {
1203                        chars.next();
1204                        in_block_comment = true;
1205                    }
1206                }
1207                ';' if !in_string && !in_dollar_quote && !in_bracket => {
1208                    end_pos = Some(i + 1);
1209                    break;
1210                }
1211                _ => {}
1212            }
1213        }
1214
1215        if let Some(pos) = end_pos {
1216            let stmt = remaining[..pos].to_string();
1217            // Skip past the statement and any leading whitespace
1218            let after_stmt = &remaining[pos..];
1219            let trimmed_len = after_stmt.len() - after_stmt.trim_start().len();
1220            self.buffer_pos += pos + trimmed_len;
1221
1222            // Skip empty statements and comments
1223            let trimmed = stmt.trim();
1224
1225            // Strip leading comments from the statement before checking if it's just a comment
1226            let stripped = Self::strip_leading_sql_comments(trimmed);
1227            if stripped.is_empty() {
1228                return self.extract_statement();
1229            }
1230
1231            // Use the stripped version for further processing
1232            let trimmed = stripped;
1233
1234            // For Postgres COPY statements, auto-enter copy mode
1235            // This prevents accumulating COPY data while looking for the next semicolon
1236            if self.dialect == SqlDialect::Postgres {
1237                let upper = trimmed.to_uppercase();
1238                if upper.ends_with("FROM STDIN;") && upper.contains("COPY ") {
1239                    self.in_copy_mode = true;
1240                }
1241            }
1242
1243            Some(stmt)
1244        } else {
1245            None
1246        }
1247    }
1248
1249    /// Find GO batch separator at start of line (MSSQL)
1250    fn find_go_separator(&self) -> Option<usize> {
1251        let remaining = self.remaining_buffer();
1252        let mut in_string = false;
1253        let mut in_bracket = false;
1254        let mut line_start = 0;
1255
1256        for (i, c) in remaining.char_indices() {
1257            if c == '\'' && !in_bracket {
1258                in_string = !in_string;
1259            } else if c == '[' && !in_string {
1260                in_bracket = true;
1261            } else if c == ']' && !in_string {
1262                in_bracket = false;
1263            } else if c == '\n' {
1264                line_start = i + 1;
1265            } else if !in_string && !in_bracket && i == line_start {
1266                // Check for GO at start of line
1267                let rest = &remaining[i..];
1268                if rest.len() >= 2 {
1269                    let word = &rest[..2.min(rest.len())];
1270                    if word.eq_ignore_ascii_case("GO") {
1271                        // Make sure it's just GO (not GO_SOMETHING)
1272                        let after_go = if rest.len() > 2 {
1273                            rest.chars().nth(2)
1274                        } else {
1275                            None
1276                        };
1277                        if after_go.is_none()
1278                            || after_go == Some('\n')
1279                            || after_go == Some('\r')
1280                            || after_go == Some(' ')
1281                            || after_go.unwrap().is_ascii_digit()
1282                        {
1283                            return Some(i);
1284                        }
1285                    }
1286                }
1287            }
1288        }
1289        None
1290    }
1291}
1292
1293#[cfg(test)]
1294mod tests {
1295    use super::*;
1296
1297    #[test]
1298    fn test_count_insert_rows() {
1299        assert_eq!(
1300            DumpLoader::count_insert_rows("INSERT INTO t VALUES (1, 'a')"),
1301            1
1302        );
1303        assert_eq!(
1304            DumpLoader::count_insert_rows("INSERT INTO t VALUES (1, 'a'), (2, 'b'), (3, 'c')"),
1305            3
1306        );
1307        assert_eq!(
1308            DumpLoader::count_insert_rows("INSERT INTO t VALUES (1, '(test)')"),
1309            1
1310        );
1311    }
1312
1313    #[test]
1314    fn test_strip_mysql_clauses() {
1315        let sql = "CREATE TABLE t (id INT) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";
1316        let result = DumpLoader::strip_mysql_clauses(sql);
1317        assert!(!result.contains("ENGINE"));
1318        assert!(!result.contains("CHARSET"));
1319    }
1320
1321    #[test]
1322    fn test_convert_identifiers() {
1323        let sql = "INSERT INTO `users` (`id`, `name`) VALUES (1, 'test')";
1324        let result = DumpLoader::convert_identifiers(sql, SqlDialect::MySql);
1325        assert_eq!(
1326            result,
1327            "INSERT INTO \"users\" (\"id\", \"name\") VALUES (1, 'test')"
1328        );
1329    }
1330
1331    #[test]
1332    fn test_looks_like_copy_data() {
1333        assert!(DumpLoader::looks_like_copy_data("1\tAlice\t2024-01-01"));
1334        assert!(!DumpLoader::looks_like_copy_data("SELECT * FROM users"));
1335        assert!(!DumpLoader::looks_like_copy_data("INSERT INTO t VALUES"));
1336    }
1337
1338    #[test]
1339    fn test_strip_mssql_syntax() {
1340        let sql = r#"CREATE TABLE "users" (
1341    "id" INTEGER NOT NULL,
1342    "email" VARCHAR(255) NOT NULL
1343)"#;
1344        // The IDENTITY should have been stripped by strip_mssql_syntax
1345        let result = DumpLoader::strip_mssql_syntax(sql);
1346        assert!(!result.contains("IDENTITY"), "IDENTITY should be stripped");
1347
1348        // Test with IDENTITY(1,1) NOT NULL
1349        let sql_with_identity = r#"CREATE TABLE "users" (
1350    "id" INTEGER IDENTITY(1,1) NOT NULL,
1351    "email" VARCHAR(255) NOT NULL
1352)"#;
1353        let result2 = DumpLoader::strip_mssql_syntax(sql_with_identity);
1354        assert!(
1355            !result2.contains("IDENTITY"),
1356            "IDENTITY should be stripped: {}",
1357            result2
1358        );
1359        // Since we strip IDENTITY(1,1) NOT NULL, the column should become nullable
1360        assert!(
1361            !result2.contains("IDENTITY(1,1) NOT NULL"),
1362            "Should strip full IDENTITY NOT NULL"
1363        );
1364    }
1365
1366    #[test]
1367    fn test_convert_mssql_identifiers() {
1368        let sql = "INSERT INTO [dbo].[users] ([id], [name]) VALUES (1, N'test')";
1369        let result = DumpLoader::convert_identifiers(sql, SqlDialect::Mssql);
1370        assert_eq!(
1371            result,
1372            "INSERT INTO \"dbo\".\"users\" (\"id\", \"name\") VALUES (1, 'test')"
1373        );
1374    }
1375}