Skip to main content

sql_splitter/parser/
mod.rs

1pub mod mysql_insert;
2pub mod postgres_copy;
3
4// Re-export types for bulk loading (consumed by the duckdb loader and by
5// library users; the bin target without duckdb-query doesn't use them)
6#[cfg_attr(not(feature = "duckdb-query"), allow(unused_imports))]
7pub use mysql_insert::{parse_insert_for_bulk, ParsedValue};
8
9use once_cell::sync::Lazy;
10use regex::bytes::Regex;
11use std::io::{BufRead, BufReader, Read};
12
13pub const SMALL_BUFFER_SIZE: usize = 64 * 1024;
14pub const MEDIUM_BUFFER_SIZE: usize = 256 * 1024;
15
16/// SQL dialect for parser behavior
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
18pub enum SqlDialect {
19    /// MySQL/MariaDB mysqldump format (backtick quoting, backslash escapes)
20    #[default]
21    MySql,
22    /// PostgreSQL pg_dump format (double-quote identifiers, COPY FROM stdin, dollar-quoting)
23    Postgres,
24    /// SQLite .dump format (double-quote identifiers, '' escapes)
25    Sqlite,
26    /// Microsoft SQL Server / T-SQL (square bracket identifiers, GO batches, N'unicode' strings)
27    Mssql,
28}
29
30impl std::str::FromStr for SqlDialect {
31    type Err = String;
32
33    fn from_str(s: &str) -> Result<Self, Self::Err> {
34        match s.to_lowercase().as_str() {
35            "mysql" | "mariadb" => Ok(SqlDialect::MySql),
36            "postgres" | "postgresql" | "pg" => Ok(SqlDialect::Postgres),
37            "sqlite" | "sqlite3" => Ok(SqlDialect::Sqlite),
38            "mssql" | "sqlserver" | "sql_server" | "tsql" => Ok(SqlDialect::Mssql),
39            _ => Err(format!(
40                "Unknown dialect: {}. Valid options: mysql, postgres, sqlite, mssql",
41                s
42            )),
43        }
44    }
45}
46
47impl std::fmt::Display for SqlDialect {
48    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
49        match self {
50            SqlDialect::MySql => write!(f, "mysql"),
51            SqlDialect::Postgres => write!(f, "postgres"),
52            SqlDialect::Sqlite => write!(f, "sqlite"),
53            SqlDialect::Mssql => write!(f, "mssql"),
54        }
55    }
56}
57
58/// Result of dialect auto-detection
59#[derive(Debug, Clone)]
60pub struct DialectDetectionResult {
61    pub dialect: SqlDialect,
62    pub confidence: DialectConfidence,
63}
64
65/// Confidence level of dialect detection
66#[derive(Debug, Clone, Copy, PartialEq, Eq)]
67pub enum DialectConfidence {
68    /// High confidence - found definitive markers (e.g., "pg_dump", "MySQL dump")
69    High,
70    /// Medium confidence - found likely markers
71    Medium,
72    /// Low confidence - defaulting to MySQL
73    Low,
74}
75
76#[derive(Default)]
77struct DialectScore {
78    mysql: u32,
79    postgres: u32,
80    sqlite: u32,
81    mssql: u32,
82}
83
84/// Detect SQL dialect from file header content.
85/// Reads up to 8KB and looks for dialect-specific markers.
86pub fn detect_dialect(header: &[u8]) -> DialectDetectionResult {
87    let mut score = DialectScore::default();
88
89    // High confidence markers (+10)
90    if contains_bytes(header, b"pg_dump") {
91        score.postgres += 10;
92    }
93    if contains_bytes(header, b"PostgreSQL database dump") {
94        score.postgres += 10;
95    }
96    if contains_bytes(header, b"MySQL dump") {
97        score.mysql += 10;
98    }
99    if contains_bytes(header, b"MariaDB dump") {
100        score.mysql += 10;
101    }
102    if contains_bytes(header, b"SQLite") {
103        score.sqlite += 10;
104    }
105
106    // Medium confidence markers (+5)
107    if contains_bytes(header, b"COPY ") && contains_bytes(header, b"FROM stdin") {
108        score.postgres += 5;
109    }
110    if contains_bytes(header, b"search_path") {
111        score.postgres += 5;
112    }
113    if contains_bytes(header, b"/*!40") || contains_bytes(header, b"/*!50") {
114        score.mysql += 5;
115    }
116    if contains_bytes(header, b"LOCK TABLES") {
117        score.mysql += 5;
118    }
119    if contains_bytes(header, b"PRAGMA") {
120        score.sqlite += 5;
121    }
122
123    // Low confidence markers (+2)
124    if contains_bytes(header, b"$$") {
125        score.postgres += 2;
126    }
127    if contains_bytes(header, b"CREATE EXTENSION") {
128        score.postgres += 2;
129    }
130    // BEGIN TRANSACTION is generic ANSI SQL, only slightly suggests SQLite
131    if contains_bytes(header, b"BEGIN TRANSACTION") {
132        score.sqlite += 2;
133    }
134    // Backticks suggest MySQL (could also appear in data/comments)
135    if header.contains(&b'`') {
136        score.mysql += 2;
137    }
138
139    // MSSQL/T-SQL markers
140    // High confidence markers (+20)
141    if contains_bytes(header, b"SET ANSI_NULLS") {
142        score.mssql += 20;
143    }
144    if contains_bytes(header, b"SET QUOTED_IDENTIFIER") {
145        score.mssql += 20;
146    }
147
148    // Medium confidence markers (+10-15)
149    // GO as batch separator on its own line (check for common patterns)
150    if contains_bytes(header, b"\nGO\n") || contains_bytes(header, b"\nGO\r\n") {
151        score.mssql += 15;
152    }
153    // Square bracket identifiers
154    if header.contains(&b'[') && header.contains(&b']') {
155        score.mssql += 10;
156    }
157    if contains_bytes(header, b"IDENTITY(") {
158        score.mssql += 10;
159    }
160    if contains_bytes(header, b"ON [PRIMARY]") {
161        score.mssql += 10;
162    }
163
164    // Low confidence markers (+5)
165    if contains_bytes(header, b"N'") {
166        score.mssql += 5;
167    }
168    if contains_bytes(header, b"NVARCHAR") {
169        score.mssql += 5;
170    }
171    if contains_bytes(header, b"CLUSTERED") {
172        score.mssql += 5;
173    }
174    if contains_bytes(header, b"SET NOCOUNT") {
175        score.mssql += 5;
176    }
177
178    // Determine winner and confidence
179    let max_score = score
180        .mysql
181        .max(score.postgres)
182        .max(score.sqlite)
183        .max(score.mssql);
184
185    if max_score == 0 {
186        return DialectDetectionResult {
187            dialect: SqlDialect::MySql,
188            confidence: DialectConfidence::Low,
189        };
190    }
191
192    // Find the dialect with the highest score
193    let (dialect, winning_score) = if score.mssql > score.mysql
194        && score.mssql > score.postgres
195        && score.mssql > score.sqlite
196    {
197        (SqlDialect::Mssql, score.mssql)
198    } else if score.postgres > score.mysql && score.postgres > score.sqlite {
199        (SqlDialect::Postgres, score.postgres)
200    } else if score.sqlite > score.mysql {
201        (SqlDialect::Sqlite, score.sqlite)
202    } else {
203        (SqlDialect::MySql, score.mysql)
204    };
205
206    // Determine confidence based on winning score
207    let confidence = if winning_score >= 10 {
208        DialectConfidence::High
209    } else if winning_score >= 5 {
210        DialectConfidence::Medium
211    } else {
212        DialectConfidence::Low
213    };
214
215    DialectDetectionResult {
216        dialect,
217        confidence,
218    }
219}
220
221/// Detect dialect from a file, reading first 8KB
222pub fn detect_dialect_from_file(path: &std::path::Path) -> std::io::Result<DialectDetectionResult> {
223    use std::fs::File;
224    use std::io::Read;
225
226    let mut file = File::open(path)?;
227    let mut buf = [0u8; 8192];
228    let n = file.read(&mut buf)?;
229    Ok(detect_dialect(&buf[..n]))
230}
231
232#[inline]
233fn contains_bytes(haystack: &[u8], needle: &[u8]) -> bool {
234    haystack
235        .windows(needle.len())
236        .any(|window| window == needle)
237}
238
239/// Check if a line is a MSSQL GO batch separator
240/// GO must be on its own line (with optional whitespace and optional repeat count)
241/// Examples: "GO\n", "  GO  \n", "GO 100\n", "go\r\n"
242fn is_go_line(line: &[u8]) -> bool {
243    // Trim leading whitespace
244    let mut start = 0;
245    while start < line.len()
246        && (line[start] == b' ' || line[start] == b'\t' || line[start] == b'\r')
247    {
248        start += 1;
249    }
250
251    // Trim trailing whitespace and newlines
252    let mut end = line.len();
253    while end > start
254        && (line[end - 1] == b' '
255            || line[end - 1] == b'\t'
256            || line[end - 1] == b'\r'
257            || line[end - 1] == b'\n')
258    {
259        end -= 1;
260    }
261
262    let trimmed = &line[start..end];
263
264    if trimmed.len() < 2 {
265        return false;
266    }
267
268    // Check for "GO" (case-insensitive)
269    if trimmed.len() == 2 {
270        return (trimmed[0] == b'G' || trimmed[0] == b'g')
271            && (trimmed[1] == b'O' || trimmed[1] == b'o');
272    }
273
274    // Check for "GO <number>" pattern
275    if (trimmed[0] == b'G' || trimmed[0] == b'g')
276        && (trimmed[1] == b'O' || trimmed[1] == b'o')
277        && (trimmed[2] == b' ' || trimmed[2] == b'\t')
278    {
279        // Rest should be whitespace and digits
280        let rest = &trimmed[3..];
281        let rest_trimmed = rest
282            .iter()
283            .skip_while(|&&b| b == b' ' || b == b'\t')
284            .copied()
285            .collect::<Vec<_>>();
286        return rest_trimmed.is_empty() || rest_trimmed.iter().all(|&b| b.is_ascii_digit());
287    }
288
289    false
290}
291
292#[derive(Debug, Clone, Copy, PartialEq, Eq)]
293pub enum StatementType {
294    Unknown,
295    CreateTable,
296    Insert,
297    CreateIndex,
298    AlterTable,
299    DropTable,
300    /// PostgreSQL COPY FROM stdin
301    Copy,
302}
303
304impl StatementType {
305    /// Returns true if this is a schema-related statement (DDL)
306    pub fn is_schema(&self) -> bool {
307        matches!(
308            self,
309            StatementType::CreateTable
310                | StatementType::CreateIndex
311                | StatementType::AlterTable
312                | StatementType::DropTable
313        )
314    }
315
316    /// Returns true if this is a data-related statement (DML)
317    pub fn is_data(&self) -> bool {
318        matches!(self, StatementType::Insert | StatementType::Copy)
319    }
320}
321
322/// Content filter mode for splitting
323#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
324pub enum ContentFilter {
325    /// Include both schema and data statements (default)
326    #[default]
327    All,
328    /// Only schema statements (CREATE TABLE, CREATE INDEX, ALTER TABLE, DROP TABLE)
329    SchemaOnly,
330    /// Only data statements (INSERT, COPY)
331    DataOnly,
332}
333
334static CREATE_TABLE_RE: Lazy<Regex> =
335    Lazy::new(|| Regex::new(r"(?i)^\s*CREATE\s+TABLE\s+`?([^\s`(]+)`?").unwrap());
336
337static INSERT_INTO_RE: Lazy<Regex> =
338    Lazy::new(|| Regex::new(r"(?i)^\s*INSERT\s+INTO\s+`?([^\s`(]+)`?").unwrap());
339
340static CREATE_INDEX_RE: Lazy<Regex> =
341    Lazy::new(|| Regex::new(r"(?i)ON\s+`?([^\s`(;]+)`?").unwrap());
342
343// MSSQL CREATE INDEX: extracts table from ON [schema].[table] or ON [table]
344// Matches: ON [table], ON [dbo].[table], ON [db].[dbo].[table]
345// Captures the last bracketed or unbracketed identifier before (
346static CREATE_INDEX_MSSQL_RE: Lazy<Regex> =
347    Lazy::new(|| Regex::new(r"(?i)ON\s+(?:\[?[^\[\]\s]+\]?\s*\.\s*)*\[([^\[\]]+)\]").unwrap());
348
349static ALTER_TABLE_RE: Lazy<Regex> =
350    Lazy::new(|| Regex::new(r"(?i)ALTER\s+TABLE\s+`?([^\s`;]+)`?").unwrap());
351
352static DROP_TABLE_RE: Lazy<Regex> = Lazy::new(|| {
353    Regex::new(r#"(?i)DROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?[`"]?([^\s`"`;]+)[`"]?"#).unwrap()
354});
355
356// PostgreSQL COPY statement regex
357static COPY_RE: Lazy<Regex> =
358    Lazy::new(|| Regex::new(r#"(?i)^\s*COPY\s+(?:ONLY\s+)?[`"]?([^\s`"(]+)[`"]?"#).unwrap());
359
360// More flexible table name regex that handles:
361// - Backticks: `table`
362// - Double quotes: "table"
363// - Schema qualified: schema.table, `schema`.`table`, "schema"."table"
364// - IF NOT EXISTS
365static CREATE_TABLE_FLEXIBLE_RE: Lazy<Regex> = Lazy::new(|| {
366    Regex::new(r#"(?i)^\s*CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(?:[`"]?[\w]+[`"]?\s*\.\s*)?[`"]?([\w]+)[`"]?"#).unwrap()
367});
368
369static INSERT_FLEXIBLE_RE: Lazy<Regex> = Lazy::new(|| {
370    Regex::new(
371        r#"(?i)^\s*INSERT\s+INTO\s+(?:ONLY\s+)?(?:[`"]?[\w]+[`"]?\s*\.\s*)?[`"]?([\w]+)[`"]?"#,
372    )
373    .unwrap()
374});
375
376pub struct Parser<R: Read> {
377    reader: BufReader<R>,
378    stmt_buffer: Vec<u8>,
379    dialect: SqlDialect,
380    /// For PostgreSQL: true when reading COPY data block
381    in_copy_data: bool,
382}
383
384impl<R: Read> Parser<R> {
385    #[allow(dead_code)]
386    pub fn new(reader: R, buffer_size: usize) -> Self {
387        Self::with_dialect(reader, buffer_size, SqlDialect::default())
388    }
389
390    pub fn with_dialect(reader: R, buffer_size: usize, dialect: SqlDialect) -> Self {
391        Self {
392            reader: BufReader::with_capacity(buffer_size, reader),
393            stmt_buffer: Vec::with_capacity(32 * 1024),
394            dialect,
395            in_copy_data: false,
396        }
397    }
398
399    pub fn read_statement(&mut self) -> std::io::Result<Option<Vec<u8>>> {
400        // If we're in PostgreSQL COPY data mode, read until we see the terminator
401        if self.in_copy_data {
402            return self.read_copy_data();
403        }
404
405        // For MSSQL, use line-based parsing to handle GO batch separator
406        if self.dialect == SqlDialect::Mssql {
407            return self.read_statement_mssql();
408        }
409
410        self.stmt_buffer.clear();
411
412        let mut inside_single_quote = false;
413        let mut inside_double_quote = false;
414        let mut escaped = false;
415        let mut in_line_comment = false;
416        // For PostgreSQL dollar-quoting: track the tag
417        let mut in_dollar_quote = false;
418        let mut dollar_tag: Vec<u8> = Vec::new();
419
420        loop {
421            let buf = self.reader.fill_buf()?;
422            if buf.is_empty() {
423                if self.stmt_buffer.is_empty() {
424                    return Ok(None);
425                }
426                let result = std::mem::take(&mut self.stmt_buffer);
427                return Ok(Some(result));
428            }
429
430            let mut consumed = 0;
431            let mut found_terminator = false;
432
433            for (i, &b) in buf.iter().enumerate() {
434                let inside_string = inside_single_quote || inside_double_quote || in_dollar_quote;
435
436                // End of line comment on newline
437                if in_line_comment {
438                    if b == b'\n' {
439                        in_line_comment = false;
440                    }
441                    continue;
442                }
443
444                if escaped {
445                    escaped = false;
446                    continue;
447                }
448
449                // Handle backslash escapes (MySQL style)
450                if b == b'\\' && inside_string && self.dialect == SqlDialect::MySql {
451                    escaped = true;
452                    continue;
453                }
454
455                // Handle line comments (-- to end of line)
456                if b == b'-' && !inside_string && i + 1 < buf.len() && buf[i + 1] == b'-' {
457                    in_line_comment = true;
458                    continue;
459                }
460
461                // Handle dollar-quoting for PostgreSQL
462                if self.dialect == SqlDialect::Postgres
463                    && !inside_single_quote
464                    && !inside_double_quote
465                {
466                    if b == b'$' && !in_dollar_quote {
467                        // Start of dollar-quote: scan for the closing $
468                        if let Some(end) = buf[i + 1..].iter().position(|&c| c == b'$') {
469                            let tag_bytes = &buf[i + 1..i + 1 + end];
470
471                            // Validate tag: must be empty OR identifier-like [A-Za-z_][A-Za-z0-9_]*
472                            let is_valid_tag = if tag_bytes.is_empty() {
473                                true
474                            } else {
475                                let mut iter = tag_bytes.iter();
476                                match iter.next() {
477                                    Some(&first)
478                                        if first.is_ascii_alphabetic() || first == b'_' =>
479                                    {
480                                        iter.all(|&c| c.is_ascii_alphanumeric() || c == b'_')
481                                    }
482                                    _ => false,
483                                }
484                            };
485
486                            if is_valid_tag {
487                                dollar_tag = tag_bytes.to_vec();
488                                in_dollar_quote = true;
489                                continue;
490                            }
491                            // Invalid tag - treat $ as normal character
492                        }
493                    } else if b == b'$' && in_dollar_quote {
494                        // Potential end of dollar-quote
495                        let tag_len = dollar_tag.len();
496                        if i + 1 + tag_len < buf.len()
497                            && buf[i + 1..i + 1 + tag_len] == dollar_tag[..]
498                            && buf.get(i + 1 + tag_len) == Some(&b'$')
499                        {
500                            in_dollar_quote = false;
501                            dollar_tag.clear();
502                            continue;
503                        }
504                    }
505                }
506
507                if b == b'\'' && !inside_double_quote && !in_dollar_quote {
508                    inside_single_quote = !inside_single_quote;
509                } else if b == b'"' && !inside_single_quote && !in_dollar_quote {
510                    inside_double_quote = !inside_double_quote;
511                } else if b == b';' && !inside_string {
512                    self.stmt_buffer.extend_from_slice(&buf[..=i]);
513                    consumed = i + 1;
514                    found_terminator = true;
515                    break;
516                }
517            }
518
519            if found_terminator {
520                self.reader.consume(consumed);
521                let result = std::mem::take(&mut self.stmt_buffer);
522
523                // Check if this is a PostgreSQL COPY FROM stdin statement
524                if self.dialect == SqlDialect::Postgres && self.is_copy_from_stdin(&result) {
525                    self.in_copy_data = true;
526                }
527
528                return Ok(Some(result));
529            }
530
531            self.stmt_buffer.extend_from_slice(buf);
532            let len = buf.len();
533            self.reader.consume(len);
534        }
535    }
536
537    /// Check if statement is a PostgreSQL COPY FROM stdin
538    fn is_copy_from_stdin(&self, stmt: &[u8]) -> bool {
539        // Strip leading comments (pg_dump adds -- comments before COPY statements)
540        let stmt = strip_leading_comments_and_whitespace(stmt);
541        if stmt.len() < 15 {
542            // Minimum: "COPY x FROM STDIN" = 17 chars
543            return false;
544        }
545
546        // Check prefix with stack-allocated buffer (avoid heap allocation)
547        let mut prefix = [0u8; 5];
548        for (i, &b) in stmt.iter().take(5).enumerate() {
549            prefix[i] = b.to_ascii_uppercase();
550        }
551        if &prefix != b"COPY " {
552            return false;
553        }
554
555        // Search for "FROM STDIN" case-insensitively without allocating
556        // Look within first 500 bytes (typical COPY statements are shorter)
557        let search_len = stmt.len().min(500);
558        for i in 0..search_len.saturating_sub(10) {
559            if stmt[i..i + 10]
560                .iter()
561                .zip(b"FROM STDIN".iter())
562                .all(|(&a, &b)| a.to_ascii_uppercase() == b)
563            {
564                return true;
565            }
566        }
567        false
568    }
569
570    /// Read PostgreSQL COPY data block until we see the terminator line (\.)
571    fn read_copy_data(&mut self) -> std::io::Result<Option<Vec<u8>>> {
572        self.stmt_buffer.clear();
573
574        loop {
575            // First, fill the buffer and check if empty
576            let buf = self.reader.fill_buf()?;
577            if buf.is_empty() {
578                self.in_copy_data = false;
579                if self.stmt_buffer.is_empty() {
580                    return Ok(None);
581                }
582                return Ok(Some(std::mem::take(&mut self.stmt_buffer)));
583            }
584
585            // Look for a newline in the buffer
586            let newline_pos = buf.iter().position(|&b| b == b'\n');
587
588            if let Some(i) = newline_pos {
589                // Include this newline
590                self.stmt_buffer.extend_from_slice(&buf[..=i]);
591                self.reader.consume(i + 1);
592
593                // Check if the line we just added ends the COPY block
594                // Looking for a line that is just "\.\n" or "\.\r\n"
595                if self.ends_with_copy_terminator() {
596                    self.in_copy_data = false;
597                    return Ok(Some(std::mem::take(&mut self.stmt_buffer)));
598                }
599                // Continue reading - we need to process more lines
600            } else {
601                // No newline found, consume the whole buffer and continue
602                let len = buf.len();
603                self.stmt_buffer.extend_from_slice(buf);
604                self.reader.consume(len);
605            }
606        }
607    }
608
609    /// Check if buffer ends with the COPY terminator line (\.)
610    fn ends_with_copy_terminator(&self) -> bool {
611        let data = &self.stmt_buffer;
612        if data.len() < 2 {
613            return false;
614        }
615
616        // Look for a line that is just "\.\n" or "\.\r\n"
617        // We need to find the start of the last line
618        let last_newline = data[..data.len() - 1]
619            .iter()
620            .rposition(|&b| b == b'\n')
621            .map(|i| i + 1)
622            .unwrap_or(0);
623
624        let last_line = &data[last_newline..];
625
626        // Check if it's "\.\n" or "\.\r\n"
627        last_line == b"\\.\n" || last_line == b"\\.\r\n"
628    }
629
630    /// Read MSSQL statement with GO batch separator support
631    /// GO is a batch separator that appears on its own line
632    fn read_statement_mssql(&mut self) -> std::io::Result<Option<Vec<u8>>> {
633        self.stmt_buffer.clear();
634
635        let mut inside_single_quote = false;
636        let mut inside_bracket_quote = false;
637        let mut in_line_comment = false;
638        let mut line_start = 0usize; // Track where current line started in stmt_buffer
639
640        loop {
641            let buf = self.reader.fill_buf()?;
642            if buf.is_empty() {
643                if self.stmt_buffer.is_empty() {
644                    return Ok(None);
645                }
646                let result = std::mem::take(&mut self.stmt_buffer);
647                return Ok(Some(result));
648            }
649
650            let mut consumed = 0;
651            let mut found_terminator = false;
652
653            for (i, &b) in buf.iter().enumerate() {
654                let inside_string = inside_single_quote || inside_bracket_quote;
655
656                // End of line comment on newline
657                if in_line_comment {
658                    if b == b'\n' {
659                        in_line_comment = false;
660                        // Add to buffer and update line_start
661                        self.stmt_buffer.extend_from_slice(&buf[consumed..=i]);
662                        consumed = i + 1;
663                        line_start = self.stmt_buffer.len();
664                    }
665                    continue;
666                }
667
668                // Handle line comments (-- to end of line)
669                if b == b'-' && !inside_string && i + 1 < buf.len() && buf[i + 1] == b'-' {
670                    in_line_comment = true;
671                    continue;
672                }
673
674                // Handle N'...' unicode strings - treat N as prefix, ' as quote start
675                // (The N is just a prefix, single quote handling is the same)
676
677                // Handle string quotes
678                if b == b'\'' && !inside_bracket_quote {
679                    inside_single_quote = !inside_single_quote;
680                } else if b == b'[' && !inside_single_quote {
681                    inside_bracket_quote = true;
682                } else if b == b']' && inside_bracket_quote {
683                    // Check for escaped ]]
684                    if i + 1 < buf.len() && buf[i + 1] == b']' {
685                        // Skip the escape sequence - consume one extra ]
686                        continue;
687                    }
688                    inside_bracket_quote = false;
689                } else if b == b';' && !inside_string {
690                    // Semicolon is a statement terminator in MSSQL too
691                    self.stmt_buffer.extend_from_slice(&buf[consumed..=i]);
692                    consumed = i + 1;
693                    found_terminator = true;
694                    break;
695                } else if b == b'\n' && !inside_string {
696                    // Check if the current line (from line_start to here) is just "GO"
697                    // First, add bytes up to and including the newline
698                    self.stmt_buffer.extend_from_slice(&buf[consumed..=i]);
699                    consumed = i + 1;
700
701                    // Get the line we just completed
702                    let line = &self.stmt_buffer[line_start..];
703                    if is_go_line(line) {
704                        // Remove the GO line from the buffer
705                        self.stmt_buffer.truncate(line_start);
706                        // Trim trailing whitespace from the statement
707                        while self
708                            .stmt_buffer
709                            .last()
710                            .is_some_and(|&b| b == b'\n' || b == b'\r' || b == b' ' || b == b'\t')
711                        {
712                            self.stmt_buffer.pop();
713                        }
714                        // If we have content, return it
715                        if !self.stmt_buffer.is_empty() {
716                            self.reader.consume(consumed);
717                            let result = std::mem::take(&mut self.stmt_buffer);
718                            return Ok(Some(result));
719                        }
720                        // Otherwise, reset and continue (empty batch)
721                        line_start = 0;
722                    } else {
723                        // Update line_start to after the newline
724                        line_start = self.stmt_buffer.len();
725                    }
726                    continue;
727                }
728            }
729
730            if found_terminator {
731                self.reader.consume(consumed);
732                let result = std::mem::take(&mut self.stmt_buffer);
733                return Ok(Some(result));
734            }
735
736            // Add remaining bytes to buffer
737            if consumed < buf.len() {
738                self.stmt_buffer.extend_from_slice(&buf[consumed..]);
739            }
740            let len = buf.len();
741            self.reader.consume(len);
742        }
743    }
744
745    #[allow(dead_code)]
746    pub fn parse_statement(stmt: &[u8]) -> (StatementType, String) {
747        Self::parse_statement_with_dialect(stmt, SqlDialect::MySql)
748    }
749
750    /// Parse a statement with dialect-specific handling
751    pub fn parse_statement_with_dialect(
752        stmt: &[u8],
753        dialect: SqlDialect,
754    ) -> (StatementType, String) {
755        // Strip leading comments (e.g., pg_dump adds -- comments before statements)
756        let stmt = strip_leading_comments_and_whitespace(stmt);
757
758        if stmt.len() < 4 {
759            return (StatementType::Unknown, String::new());
760        }
761
762        // Use stack-allocated buffer to avoid heap allocation in hot path
763        let mut upper_prefix = [0u8; 25];
764        let prefix_len = stmt.len().min(25);
765        for (i, &b) in stmt.iter().take(prefix_len).enumerate() {
766            upper_prefix[i] = b.to_ascii_uppercase();
767        }
768        let upper_prefix = &upper_prefix[..prefix_len];
769
770        // PostgreSQL COPY statement
771        if upper_prefix.starts_with(b"COPY ") {
772            if let Some(caps) = COPY_RE.captures(stmt) {
773                if let Some(m) = caps.get(1) {
774                    let name = String::from_utf8_lossy(m.as_bytes()).into_owned();
775                    // Handle schema.table - extract just the table name
776                    let table_name = name.split('.').next_back().unwrap_or(&name).to_string();
777                    return (StatementType::Copy, table_name);
778                }
779            }
780        }
781
782        if upper_prefix.starts_with(b"CREATE TABLE") {
783            // Try fast extraction first
784            if let Some(name) = extract_table_name_flexible(stmt, 12, dialect) {
785                return (StatementType::CreateTable, name);
786            }
787            // Fall back to flexible regex
788            if let Some(caps) = CREATE_TABLE_FLEXIBLE_RE.captures(stmt) {
789                if let Some(m) = caps.get(1) {
790                    return (
791                        StatementType::CreateTable,
792                        String::from_utf8_lossy(m.as_bytes()).into_owned(),
793                    );
794                }
795            }
796            // Original regex as last resort
797            if let Some(caps) = CREATE_TABLE_RE.captures(stmt) {
798                if let Some(m) = caps.get(1) {
799                    return (
800                        StatementType::CreateTable,
801                        String::from_utf8_lossy(m.as_bytes()).into_owned(),
802                    );
803                }
804            }
805        }
806
807        if upper_prefix.starts_with(b"INSERT INTO") || upper_prefix.starts_with(b"INSERT ONLY") {
808            if let Some(name) = extract_table_name_flexible(stmt, 11, dialect) {
809                return (StatementType::Insert, name);
810            }
811            if let Some(caps) = INSERT_FLEXIBLE_RE.captures(stmt) {
812                if let Some(m) = caps.get(1) {
813                    return (
814                        StatementType::Insert,
815                        String::from_utf8_lossy(m.as_bytes()).into_owned(),
816                    );
817                }
818            }
819            if let Some(caps) = INSERT_INTO_RE.captures(stmt) {
820                if let Some(m) = caps.get(1) {
821                    return (
822                        StatementType::Insert,
823                        String::from_utf8_lossy(m.as_bytes()).into_owned(),
824                    );
825                }
826            }
827        }
828
829        if upper_prefix.starts_with(b"CREATE INDEX")
830            || upper_prefix.starts_with(b"CREATE UNIQUE")
831            || upper_prefix.starts_with(b"CREATE CLUSTERED")
832            || upper_prefix.starts_with(b"CREATE NONCLUSTER")
833        {
834            // For MSSQL, try the bracket-aware regex first
835            if dialect == SqlDialect::Mssql {
836                if let Some(caps) = CREATE_INDEX_MSSQL_RE.captures(stmt) {
837                    if let Some(m) = caps.get(1) {
838                        return (
839                            StatementType::CreateIndex,
840                            String::from_utf8_lossy(m.as_bytes()).into_owned(),
841                        );
842                    }
843                }
844            }
845            // Fall back to generic regex for MySQL/PostgreSQL/SQLite
846            if let Some(caps) = CREATE_INDEX_RE.captures(stmt) {
847                if let Some(m) = caps.get(1) {
848                    return (
849                        StatementType::CreateIndex,
850                        String::from_utf8_lossy(m.as_bytes()).into_owned(),
851                    );
852                }
853            }
854        }
855
856        if upper_prefix.starts_with(b"ALTER TABLE") {
857            if let Some(name) = extract_table_name_flexible(stmt, 11, dialect) {
858                return (StatementType::AlterTable, name);
859            }
860            if let Some(caps) = ALTER_TABLE_RE.captures(stmt) {
861                if let Some(m) = caps.get(1) {
862                    return (
863                        StatementType::AlterTable,
864                        String::from_utf8_lossy(m.as_bytes()).into_owned(),
865                    );
866                }
867            }
868        }
869
870        if upper_prefix.starts_with(b"DROP TABLE") {
871            if let Some(name) = extract_table_name_flexible(stmt, 10, dialect) {
872                return (StatementType::DropTable, name);
873            }
874            if let Some(caps) = DROP_TABLE_RE.captures(stmt) {
875                if let Some(m) = caps.get(1) {
876                    return (
877                        StatementType::DropTable,
878                        String::from_utf8_lossy(m.as_bytes()).into_owned(),
879                    );
880                }
881            }
882        }
883
884        // MSSQL BULK INSERT - treat as Insert statement type
885        if upper_prefix.starts_with(b"BULK INSERT") {
886            if let Some(name) = extract_table_name_flexible(stmt, 11, dialect) {
887                return (StatementType::Insert, name);
888            }
889        }
890
891        (StatementType::Unknown, String::new())
892    }
893}
894
895#[inline]
896fn trim_ascii_start(data: &[u8]) -> &[u8] {
897    let start = data
898        .iter()
899        .position(|&b| !matches!(b, b' ' | b'\t' | b'\n' | b'\r'))
900        .unwrap_or(data.len());
901    &data[start..]
902}
903
904/// Strip leading whitespace and SQL line comments (`-- ...`) from a statement.
905/// This makes parsing robust to pg_dump-style comment blocks before statements.
906fn strip_leading_comments_and_whitespace(mut data: &[u8]) -> &[u8] {
907    loop {
908        // First trim leading ASCII whitespace
909        data = trim_ascii_start(data);
910
911        // Handle -- line comments
912        if data.len() >= 2 && data[0] == b'-' && data[1] == b'-' {
913            // Skip until end of line
914            if let Some(pos) = data.iter().position(|&b| b == b'\n') {
915                data = &data[pos + 1..];
916                continue;
917            } else {
918                // Comment runs to EOF, nothing left
919                return &[];
920            }
921        }
922
923        // Handle /* */ block comments (including MySQL conditional comments)
924        if data.len() >= 2 && data[0] == b'/' && data[1] == b'*' {
925            // Find the closing */
926            let mut i = 2;
927            let mut depth = 1;
928            while i < data.len() - 1 && depth > 0 {
929                if data[i] == b'*' && data[i + 1] == b'/' {
930                    depth -= 1;
931                    i += 2;
932                } else if data[i] == b'/' && data[i + 1] == b'*' {
933                    depth += 1;
934                    i += 2;
935                } else {
936                    i += 1;
937                }
938            }
939            if depth == 0 {
940                data = &data[i..];
941                continue;
942            } else {
943                // Unclosed comment runs to EOF
944                return &[];
945            }
946        }
947
948        // Handle # line comments (MySQL)
949        if !data.is_empty() && data[0] == b'#' {
950            if let Some(pos) = data.iter().position(|&b| b == b'\n') {
951                data = &data[pos + 1..];
952                continue;
953            } else {
954                return &[];
955            }
956        }
957
958        break;
959    }
960
961    data
962}
963
964/// Extract table name with support for:
965/// - IF NOT EXISTS
966/// - ONLY (PostgreSQL)
967/// - Schema-qualified names (schema.table)
968/// - Both backtick and double-quote quoting
969#[inline]
970fn extract_table_name_flexible(stmt: &[u8], offset: usize, dialect: SqlDialect) -> Option<String> {
971    let mut i = offset;
972
973    // Skip whitespace
974    while i < stmt.len() && is_whitespace(stmt[i]) {
975        i += 1;
976    }
977
978    if i >= stmt.len() {
979        return None;
980    }
981
982    // Check for IF NOT EXISTS or IF EXISTS (stack-allocated to avoid heap allocation)
983    let mut upper_check = [0u8; 20];
984    let check_len = (stmt.len() - i).min(20);
985    for (idx, &b) in stmt[i..].iter().take(check_len).enumerate() {
986        upper_check[idx] = b.to_ascii_uppercase();
987    }
988    let upper_slice = &upper_check[..check_len];
989    if upper_slice.starts_with(b"IF NOT EXISTS") {
990        i += 13; // Skip "IF NOT EXISTS"
991        while i < stmt.len() && is_whitespace(stmt[i]) {
992            i += 1;
993        }
994    } else if upper_slice.starts_with(b"IF EXISTS") {
995        i += 9; // Skip "IF EXISTS"
996        while i < stmt.len() && is_whitespace(stmt[i]) {
997            i += 1;
998        }
999    }
1000
1001    // Check for ONLY (PostgreSQL) - reuse first 10 bytes or re-check if position changed
1002    let only_check = if i < stmt.len() {
1003        let mut buf = [0u8; 10];
1004        let len = (stmt.len() - i).min(10);
1005        for (idx, &b) in stmt[i..].iter().take(len).enumerate() {
1006            buf[idx] = b.to_ascii_uppercase();
1007        }
1008        (buf, len)
1009    } else {
1010        ([0u8; 10], 0)
1011    };
1012    let only_slice = &only_check.0[..only_check.1];
1013    if only_slice.starts_with(b"ONLY ") || only_slice.starts_with(b"ONLY\t") {
1014        i += 4;
1015        while i < stmt.len() && is_whitespace(stmt[i]) {
1016            i += 1;
1017        }
1018    }
1019
1020    if i >= stmt.len() {
1021        return None;
1022    }
1023
1024    // Read identifier (potentially schema-qualified)
1025    let mut parts: Vec<String> = Vec::new();
1026
1027    loop {
1028        // Determine quote character based on dialect
1029        let (quote_char, close_char) = match stmt.get(i) {
1030            Some(b'`') if dialect == SqlDialect::MySql => {
1031                i += 1;
1032                (Some(b'`'), b'`')
1033            }
1034            Some(b'"') if dialect != SqlDialect::MySql => {
1035                i += 1;
1036                (Some(b'"'), b'"')
1037            }
1038            Some(b'"') => {
1039                // Allow double quotes for MySQL too (though less common)
1040                i += 1;
1041                (Some(b'"'), b'"')
1042            }
1043            Some(b'[') if dialect == SqlDialect::Mssql => {
1044                // MSSQL square bracket quoting
1045                i += 1;
1046                (Some(b'['), b']')
1047            }
1048            _ => (None, 0),
1049        };
1050
1051        let start = i;
1052
1053        while i < stmt.len() {
1054            let b = stmt[i];
1055            if quote_char.is_some() {
1056                if b == close_char {
1057                    // For MSSQL, check for escaped ]]
1058                    if dialect == SqlDialect::Mssql
1059                        && close_char == b']'
1060                        && i + 1 < stmt.len()
1061                        && stmt[i + 1] == b']'
1062                    {
1063                        // Escaped bracket, skip both
1064                        i += 2;
1065                        continue;
1066                    }
1067                    let name = &stmt[start..i];
1068                    // For MSSQL, unescape ]] to ]
1069                    let name_str = if dialect == SqlDialect::Mssql {
1070                        String::from_utf8_lossy(name).replace("]]", "]")
1071                    } else {
1072                        String::from_utf8_lossy(name).into_owned()
1073                    };
1074                    parts.push(name_str);
1075                    i += 1; // Skip closing quote
1076                    break;
1077                }
1078            } else if is_whitespace(b) || b == b'(' || b == b';' || b == b',' || b == b'.' {
1079                if i > start {
1080                    let name = &stmt[start..i];
1081                    parts.push(String::from_utf8_lossy(name).into_owned());
1082                }
1083                break;
1084            }
1085            i += 1;
1086        }
1087
1088        // If at end of quoted name without finding close quote, bail
1089        if quote_char.is_some() && i <= start {
1090            break;
1091        }
1092
1093        // Check for schema separator (.)
1094        while i < stmt.len() && is_whitespace(stmt[i]) {
1095            i += 1;
1096        }
1097
1098        if i < stmt.len() && stmt[i] == b'.' {
1099            i += 1; // Skip the dot
1100            while i < stmt.len() && is_whitespace(stmt[i]) {
1101                i += 1;
1102            }
1103            // Continue to read the next identifier (table name)
1104        } else {
1105            break;
1106        }
1107    }
1108
1109    // Return the last part (table name), not the schema
1110    parts.pop()
1111}
1112
1113#[inline]
1114fn is_whitespace(b: u8) -> bool {
1115    matches!(b, b' ' | b'\t' | b'\n' | b'\r')
1116}
1117
1118pub fn determine_buffer_size(file_size: u64) -> usize {
1119    if file_size > 1024 * 1024 * 1024 {
1120        MEDIUM_BUFFER_SIZE
1121    } else {
1122        SMALL_BUFFER_SIZE
1123    }
1124}