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