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    // Simple "substring present => add weight to a dialect" markers. Confidence
90    // is encoded by the weight: 20/10 = high, 5 = medium, 2 = low.
91    const MARKERS: &[(&[u8], SqlDialect, u32)] = &[
92        (b"pg_dump", SqlDialect::Postgres, 10),
93        (b"PostgreSQL database dump", SqlDialect::Postgres, 10),
94        (b"MySQL dump", SqlDialect::MySql, 10),
95        (b"MariaDB dump", SqlDialect::MySql, 10),
96        (b"SQLite", SqlDialect::Sqlite, 10),
97        (b"search_path", SqlDialect::Postgres, 5),
98        (b"LOCK TABLES", SqlDialect::MySql, 5),
99        (b"PRAGMA", SqlDialect::Sqlite, 5),
100        (b"CREATE EXTENSION", SqlDialect::Postgres, 2),
101        // BEGIN TRANSACTION is generic ANSI SQL, only slightly suggests SQLite
102        (b"BEGIN TRANSACTION", SqlDialect::Sqlite, 2),
103        (b"SET ANSI_NULLS", SqlDialect::Mssql, 20),
104        (b"SET QUOTED_IDENTIFIER", SqlDialect::Mssql, 20),
105        (b"IDENTITY(", SqlDialect::Mssql, 10),
106        (b"ON [PRIMARY]", SqlDialect::Mssql, 10),
107        (b"NVARCHAR", SqlDialect::Mssql, 5),
108        (b"CLUSTERED", SqlDialect::Mssql, 5),
109        (b"SET NOCOUNT", SqlDialect::Mssql, 5),
110    ];
111    for &(needle, dialect, weight) in MARKERS {
112        if contains_bytes(header, needle) {
113            match dialect {
114                SqlDialect::MySql => score.mysql += weight,
115                SqlDialect::Postgres => score.postgres += weight,
116                SqlDialect::Sqlite => score.sqlite += weight,
117                SqlDialect::Mssql => score.mssql += weight,
118            }
119        }
120    }
121
122    // Compound / structural markers that don't fit the simple table.
123    if contains_bytes(header, b"COPY ") && contains_bytes(header, b"FROM stdin") {
124        score.postgres += 5;
125    }
126    if contains_bytes(header, b"/*!40") || contains_bytes(header, b"/*!50") {
127        score.mysql += 5;
128    }
129    if contains_bytes(header, b"$$") {
130        score.postgres += 2;
131    }
132    // Backticks suggest MySQL (could also appear in data/comments)
133    if header.contains(&b'`') {
134        score.mysql += 2;
135    }
136    // GO as batch separator on its own line (check for common patterns)
137    if contains_bytes(header, b"\nGO\n") || contains_bytes(header, b"\nGO\r\n") {
138        score.mssql += 15;
139    }
140    // Square-bracket identifiers, but distinguish them from PostgreSQL array
141    // types: `[id]`/`[dbo]` (identifier-shaped) => MSSQL; `integer[]` (empty)
142    // or `[5]` (non-identifier) => not MSSQL (bug #9).
143    {
144        let mut mssql_bracket_ident = false;
145        let mut pg_array_brackets = false;
146        let mut k = 0;
147        while k < header.len() {
148            if header[k] == b'[' {
149                if let Some(rel) = header[k + 1..].iter().position(|&c| c == b']') {
150                    let inner = &header[k + 1..k + 1 + rel];
151                    let ident_shaped = inner
152                        .first()
153                        .is_some_and(|&c| c.is_ascii_alphabetic() || c == b'_')
154                        && inner
155                            .iter()
156                            .all(|&c| c.is_ascii_alphanumeric() || c == b'_' || c == b' ');
157                    if inner.is_empty() {
158                        pg_array_brackets = true;
159                    } else if ident_shaped {
160                        mssql_bracket_ident = true;
161                    }
162                    k += rel + 2;
163                    continue;
164                }
165            }
166            k += 1;
167        }
168        if mssql_bracket_ident {
169            score.mssql += 10;
170        }
171        if pg_array_brackets {
172            score.postgres += 2;
173        }
174    }
175
176    // N'unicode' literal — require a non-word char before N so ordinary data
177    // ending in N before a quote (e.g. ...JOHN') doesn't score MSSQL (bug #9).
178    {
179        let mut k = 0;
180        while k + 1 < header.len() {
181            if header[k] == b'N' && header[k + 1] == b'\'' {
182                let before_ok =
183                    k == 0 || !(header[k - 1].is_ascii_alphanumeric() || header[k - 1] == b'_');
184                if before_ok {
185                    score.mssql += 5;
186                    break;
187                }
188            }
189            k += 1;
190        }
191    }
192
193    // Determine winner and confidence
194    let max_score = score
195        .mysql
196        .max(score.postgres)
197        .max(score.sqlite)
198        .max(score.mssql);
199
200    if max_score == 0 {
201        return DialectDetectionResult {
202            dialect: SqlDialect::MySql,
203            confidence: DialectConfidence::Low,
204        };
205    }
206
207    // Find the dialect with the highest score
208    let (dialect, winning_score) = if score.mssql > score.mysql
209        && score.mssql > score.postgres
210        && score.mssql > score.sqlite
211    {
212        (SqlDialect::Mssql, score.mssql)
213    } else if score.postgres > score.mysql && score.postgres > score.sqlite {
214        (SqlDialect::Postgres, score.postgres)
215    } else if score.sqlite > score.mysql {
216        (SqlDialect::Sqlite, score.sqlite)
217    } else {
218        (SqlDialect::MySql, score.mysql)
219    };
220
221    // Determine confidence based on winning score
222    let confidence = if winning_score >= 10 {
223        DialectConfidence::High
224    } else if winning_score >= 5 {
225        DialectConfidence::Medium
226    } else {
227        DialectConfidence::Low
228    };
229
230    DialectDetectionResult {
231        dialect,
232        confidence,
233    }
234}
235
236/// Detect dialect from a file, reading first 8KB
237pub fn detect_dialect_from_file(path: &std::path::Path) -> std::io::Result<DialectDetectionResult> {
238    use std::fs::File;
239    use std::io::Read;
240
241    let mut file = File::open(path)?;
242    let mut buf = [0u8; 8192];
243    let n = file.read(&mut buf)?;
244    Ok(detect_dialect(&buf[..n]))
245}
246
247#[inline]
248fn contains_bytes(haystack: &[u8], needle: &[u8]) -> bool {
249    memchr::memmem::find(haystack, needle).is_some()
250}
251
252/// Check if a line is a MSSQL GO batch separator
253/// GO must be on its own line (with optional whitespace and optional repeat count)
254/// Examples: "GO\n", "  GO  \n", "GO 100\n", "go\r\n"
255fn is_go_line(line: &[u8]) -> bool {
256    // Trim leading whitespace
257    let mut start = 0;
258    while start < line.len()
259        && (line[start] == b' ' || line[start] == b'\t' || line[start] == b'\r')
260    {
261        start += 1;
262    }
263
264    // Trim trailing whitespace and newlines
265    let mut end = line.len();
266    while end > start
267        && (line[end - 1] == b' '
268            || line[end - 1] == b'\t'
269            || line[end - 1] == b'\r'
270            || line[end - 1] == b'\n')
271    {
272        end -= 1;
273    }
274
275    let trimmed = &line[start..end];
276
277    if trimmed.len() < 2 {
278        return false;
279    }
280
281    // Check for "GO" (case-insensitive)
282    if trimmed.len() == 2 {
283        return (trimmed[0] == b'G' || trimmed[0] == b'g')
284            && (trimmed[1] == b'O' || trimmed[1] == b'o');
285    }
286
287    // Check for "GO <number>" pattern
288    if (trimmed[0] == b'G' || trimmed[0] == b'g')
289        && (trimmed[1] == b'O' || trimmed[1] == b'o')
290        && (trimmed[2] == b' ' || trimmed[2] == b'\t')
291    {
292        // Rest should be whitespace and digits (allocation-free scan)
293        return trimmed[3..]
294            .iter()
295            .skip_while(|&&b| b == b' ' || b == b'\t')
296            .all(|&b| b.is_ascii_digit());
297    }
298
299    false
300}
301
302#[derive(Debug, Clone, Copy, PartialEq, Eq)]
303pub enum StatementType {
304    Unknown,
305    CreateTable,
306    Insert,
307    CreateIndex,
308    AlterTable,
309    DropTable,
310    /// PostgreSQL COPY FROM stdin
311    Copy,
312}
313
314impl StatementType {
315    /// Returns true if this is a schema-related statement (DDL)
316    pub fn is_schema(&self) -> bool {
317        matches!(
318            self,
319            StatementType::CreateTable
320                | StatementType::CreateIndex
321                | StatementType::AlterTable
322                | StatementType::DropTable
323        )
324    }
325
326    /// Returns true if this is a data-related statement (DML)
327    pub fn is_data(&self) -> bool {
328        matches!(self, StatementType::Insert | StatementType::Copy)
329    }
330}
331
332/// Content filter mode for splitting
333#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
334pub enum ContentFilter {
335    /// Include both schema and data statements (default)
336    #[default]
337    All,
338    /// Only schema statements (CREATE TABLE, CREATE INDEX, ALTER TABLE, DROP TABLE)
339    SchemaOnly,
340    /// Only data statements (INSERT, COPY)
341    DataOnly,
342}
343
344// Word boundary before ON so index names ending in "on" (idx_position,
345// idx_created_on, ...) don't match the "on" inside the identifier.
346static CREATE_INDEX_RE: Lazy<Regex> =
347    Lazy::new(|| Regex::new(r"(?i)\bON\s+`?([^\s`(;]+)`?").unwrap());
348
349// MSSQL CREATE INDEX: extracts table from ON [schema].[table] or ON [table]
350// Matches: ON [table], ON [dbo].[table], ON [db].[dbo].[table]
351// Captures the last bracketed or unbracketed identifier before (
352static CREATE_INDEX_MSSQL_RE: Lazy<Regex> =
353    Lazy::new(|| Regex::new(r"(?i)ON\s+(?:\[?[^\[\]\s]+\]?\s*\.\s*)*\[([^\[\]]+)\]").unwrap());
354
355static ALTER_TABLE_RE: Lazy<Regex> =
356    Lazy::new(|| Regex::new(r"(?i)ALTER\s+TABLE\s+`?([^\s`;]+)`?").unwrap());
357
358static DROP_TABLE_RE: Lazy<Regex> = Lazy::new(|| {
359    Regex::new(r#"(?i)DROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?[`"]?([^\s`"`;]+)[`"]?"#).unwrap()
360});
361
362// PostgreSQL COPY statement regex
363static COPY_RE: Lazy<Regex> =
364    Lazy::new(|| Regex::new(r#"(?i)^\s*COPY\s+(?:ONLY\s+)?[`"]?([^\s`"(]+)[`"]?"#).unwrap());
365
366// More flexible table name regex that handles:
367// - Backticks: `table`
368// - Double quotes: "table"
369// - Schema qualified: schema.table, `schema`.`table`, "schema"."table"
370// - IF NOT EXISTS
371static CREATE_TABLE_FLEXIBLE_RE: Lazy<Regex> = Lazy::new(|| {
372    Regex::new(r#"(?i)^\s*CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(?:[`"]?[\w]+[`"]?\s*\.\s*)?[`"]?([\w]+)[`"]?"#).unwrap()
373});
374
375static INSERT_FLEXIBLE_RE: Lazy<Regex> = Lazy::new(|| {
376    Regex::new(
377        r#"(?i)^\s*INSERT\s+INTO\s+(?:ONLY\s+)?(?:[`"]?[\w]+[`"]?\s*\.\s*)?[`"]?([\w]+)[`"]?"#,
378    )
379    .unwrap()
380});
381
382pub struct Parser<R: Read> {
383    reader: BufReader<R>,
384    dialect: SqlDialect,
385    /// For PostgreSQL: true when reading COPY data block
386    in_copy_data: bool,
387    /// Accumulated, not-yet-returned input. The scanners read whole `fill_buf`
388    /// chunks into `buf` and scan it with an index cursor, so a multi-byte
389    /// token (`--`, `/* */`, `$tag$`, `]]`) can never straddle an internal
390    /// buffer boundary. `buf_pos` is the start of the next statement to return;
391    /// bytes before it are already-returned and are dropped on the next refill
392    /// (never per-statement) so scanning stays O(n) rather than O(n²).
393    buf: Vec<u8>,
394    buf_pos: usize,
395}
396
397impl<R: Read> Parser<R> {
398    #[allow(dead_code)]
399    pub fn new(reader: R, buffer_size: usize) -> Self {
400        Self::with_dialect(reader, buffer_size, SqlDialect::default())
401    }
402
403    pub fn with_dialect(reader: R, buffer_size: usize, dialect: SqlDialect) -> Self {
404        Self {
405            reader: BufReader::with_capacity(buffer_size, reader),
406            dialect,
407            in_copy_data: false,
408            buf: Vec::new(),
409            buf_pos: 0,
410        }
411    }
412
413    /// Drop the already-returned prefix `buf[..keep_from]` and append the next
414    /// `fill_buf` chunk. Returns `(bytes_removed_from_front, got_more_data)`.
415    /// Callers subtract `bytes_removed_from_front` from their scan indices.
416    #[inline]
417    fn grow_buffer(&mut self, keep_from: usize) -> std::io::Result<(usize, bool)> {
418        if keep_from > 0 {
419            self.buf.drain(..keep_from);
420        }
421        let chunk = self.reader.fill_buf()?;
422        if chunk.is_empty() {
423            return Ok((keep_from, false));
424        }
425        self.buf.extend_from_slice(chunk);
426        let n = chunk.len();
427        self.reader.consume(n);
428        Ok((keep_from, true))
429    }
430
431    pub fn read_statement(&mut self) -> std::io::Result<Option<Vec<u8>>> {
432        // If we're in PostgreSQL COPY data mode, read until we see the terminator
433        if self.in_copy_data {
434            return self.read_copy_data();
435        }
436
437        // For MSSQL, use line-based parsing to handle GO batch separator
438        if self.dialect == SqlDialect::Mssql {
439            return self.read_statement_mssql();
440        }
441
442        let is_mysql = self.dialect == SqlDialect::MySql;
443        let is_postgres = self.dialect == SqlDialect::Postgres;
444
445        // Scan `self.buf` from the current statement start with an index cursor.
446        // More data is appended by `grow_buffer` (which also drops already-
447        // returned statements), so a multi-byte token (`--`, `/* */`, `$tag$`)
448        // never straddles a chunk boundary: the scan waits for more bytes with
449        // its state (`i`, quote/comment flags) intact.
450        let mut start = self.buf_pos;
451        let mut i = self.buf_pos;
452
453        let mut inside_single_quote = false;
454        let mut inside_double_quote = false;
455        let mut inside_backtick = false; // MySQL `identifier` quoting (bug #10)
456        let mut escaped = false;
457        let mut in_line_comment = false;
458        let mut in_block_comment = false; // /* ... */ (bug #5)
459        let mut in_dollar_quote = false;
460        let mut dollar_tag: Vec<u8> = Vec::new();
461        let mut at_eof = false;
462
463        // Lookup table of bytes that are significant outside strings/comments;
464        // everything else can be skipped in a tight loop.
465        let mut sig = [false; 256];
466        for &c in b";'\"-/" {
467            sig[c as usize] = true;
468        }
469        if is_mysql {
470            sig[b'`' as usize] = true;
471            sig[b'#' as usize] = true;
472        }
473        if is_postgres {
474            sig[b'$' as usize] = true;
475        }
476
477        loop {
478            'scan: while i < self.buf.len() {
479                let b = self.buf[i];
480
481                // Inside a /* */ block comment: only the closing */ ends it.
482                if in_block_comment {
483                    if b == b'*' {
484                        match self.buf.get(i + 1) {
485                            Some(b'/') => {
486                                in_block_comment = false;
487                                i += 2;
488                                continue;
489                            }
490                            Some(_) => {
491                                i += 1;
492                                continue;
493                            }
494                            None if at_eof => {
495                                i += 1;
496                                continue;
497                            }
498                            None => break 'scan,
499                        }
500                    }
501                    i += 1;
502                    continue;
503                }
504
505                // Inside a -- or # line comment: consume until newline.
506                if in_line_comment {
507                    if b == b'\n' {
508                        in_line_comment = false;
509                    }
510                    i += 1;
511                    continue;
512                }
513
514                if escaped {
515                    escaped = false;
516                    i += 1;
517                    continue;
518                }
519
520                let inside_string = inside_single_quote
521                    || inside_double_quote
522                    || inside_backtick
523                    || in_dollar_quote;
524
525                // Fast path: inside a string/quoted region only the closing
526                // delimiter (and, for MySQL, a `\` escape) is significant, so
527                // memchr past the ordinary bytes. This is the hot loop for
528                // INSERT string data.
529                if inside_string {
530                    let rest = &self.buf[i..];
531                    let hit = if inside_single_quote {
532                        if is_mysql {
533                            memchr::memchr2(b'\'', b'\\', rest)
534                        } else {
535                            memchr::memchr(b'\'', rest)
536                        }
537                    } else if inside_double_quote {
538                        if is_mysql {
539                            memchr::memchr2(b'"', b'\\', rest)
540                        } else {
541                            memchr::memchr(b'"', rest)
542                        }
543                    } else if inside_backtick {
544                        memchr::memchr(b'`', rest)
545                    } else {
546                        // in_dollar_quote: only `$` can start the closing tag
547                        memchr::memchr(b'$', rest)
548                    };
549                    match hit {
550                        Some(0) => {} // significant byte at i
551                        Some(off) => {
552                            i += off;
553                            continue;
554                        }
555                        None if at_eof => {
556                            i = self.buf.len();
557                            continue;
558                        }
559                        None => break 'scan,
560                    }
561                }
562
563                // MySQL backslash escapes apply inside both '…' and "…" string
564                // literals (but not backtick identifiers or dollar quotes).
565                if b == b'\\' && (inside_single_quote || inside_double_quote) && is_mysql {
566                    escaped = true;
567                    i += 1;
568                    continue;
569                }
570
571                if !inside_string {
572                    // Fast path: skip runs of insignificant bytes outside any
573                    // string/comment with a tight table lookup.
574                    if !sig[b as usize] {
575                        let mut j = i + 1;
576                        while j < self.buf.len() && !sig[self.buf[j] as usize] {
577                            j += 1;
578                        }
579                        i = j;
580                        continue;
581                    }
582                    // -- line comment
583                    if b == b'-' {
584                        match self.buf.get(i + 1) {
585                            Some(b'-') => {
586                                // MySQL requires whitespace/EOL after `--` for it
587                                // to be a comment; `a--b` is arithmetic. Other
588                                // dialects always treat `--` as a comment.
589                                if is_mysql {
590                                    match self.buf.get(i + 2) {
591                                        Some(&c)
592                                            if c == b' '
593                                                || c == b'\t'
594                                                || c == b'\n'
595                                                || c == b'\r' =>
596                                        {
597                                            in_line_comment = true;
598                                            i += 2;
599                                            continue;
600                                        }
601                                        None if at_eof => {
602                                            in_line_comment = true;
603                                            i += 2;
604                                            continue;
605                                        }
606                                        None => break 'scan,
607                                        // `--x`: not a comment, just consume one `-`.
608                                        Some(_) => {
609                                            i += 1;
610                                            continue;
611                                        }
612                                    }
613                                }
614                                in_line_comment = true;
615                                i += 2;
616                                continue;
617                            }
618                            Some(_) => {
619                                i += 1;
620                                continue;
621                            }
622                            None if at_eof => {
623                                i += 1;
624                                continue;
625                            }
626                            None => break 'scan,
627                        }
628                    }
629                    // MySQL # line comment
630                    if b == b'#' && is_mysql {
631                        in_line_comment = true;
632                        i += 1;
633                        continue;
634                    }
635                    // /* block comment
636                    if b == b'/' {
637                        match self.buf.get(i + 1) {
638                            Some(b'*') => {
639                                in_block_comment = true;
640                                i += 2;
641                                continue;
642                            }
643                            Some(_) => {
644                                i += 1;
645                                continue;
646                            }
647                            None if at_eof => {
648                                i += 1;
649                                continue;
650                            }
651                            None => break 'scan,
652                        }
653                    }
654                }
655
656                // PostgreSQL dollar-quoting (outside other quotes).
657                if is_postgres && !inside_single_quote && !inside_double_quote && !inside_backtick {
658                    if b == b'$' && !in_dollar_quote {
659                        match self.buf[i + 1..].iter().position(|&c| c == b'$') {
660                            Some(end) => {
661                                let tag_bytes = &self.buf[i + 1..i + 1 + end];
662                                if is_valid_dollar_tag(tag_bytes) {
663                                    dollar_tag = tag_bytes.to_vec();
664                                    in_dollar_quote = true;
665                                    // Skip the whole opening $tag$ so its trailing
666                                    // $ is not re-read as a closer (bug #7).
667                                    i += end + 2;
668                                    continue;
669                                }
670                                // Not a valid tag: treat $ as an ordinary byte.
671                                i += 1;
672                                continue;
673                            }
674                            None if at_eof => {
675                                i += 1;
676                                continue;
677                            }
678                            // No closing $ yet — it may arrive in the next chunk.
679                            None => break 'scan,
680                        }
681                    } else if b == b'$' && in_dollar_quote {
682                        let tag_len = dollar_tag.len();
683                        if i + 1 + tag_len < self.buf.len() {
684                            if self.buf[i + 1..i + 1 + tag_len] == dollar_tag[..]
685                                && self.buf[i + 1 + tag_len] == b'$'
686                            {
687                                in_dollar_quote = false;
688                                dollar_tag.clear();
689                                i += tag_len + 2;
690                                continue;
691                            }
692                            i += 1;
693                            continue;
694                        } else if at_eof {
695                            i += 1;
696                            continue;
697                        } else {
698                            break 'scan;
699                        }
700                    }
701                }
702
703                if b == b'\'' && !inside_double_quote && !inside_backtick && !in_dollar_quote {
704                    inside_single_quote = !inside_single_quote;
705                } else if b == b'"' && !inside_single_quote && !inside_backtick && !in_dollar_quote
706                {
707                    inside_double_quote = !inside_double_quote;
708                } else if b == b'`'
709                    && is_mysql
710                    && !inside_single_quote
711                    && !inside_double_quote
712                    && !in_dollar_quote
713                {
714                    inside_backtick = !inside_backtick;
715                } else if b == b';' && !inside_string {
716                    // Statement terminator. The bytes after it stay in `buf` and
717                    // become the next statement (buf_pos advances, no shifting).
718                    let result = self.buf[start..=i].to_vec();
719                    self.buf_pos = i + 1;
720
721                    if is_postgres && self.is_copy_from_stdin(&result) {
722                        self.in_copy_data = true;
723                    }
724                    return Ok(Some(result));
725                }
726
727                i += 1;
728            }
729
730            if at_eof {
731                if start >= self.buf.len() {
732                    return Ok(None);
733                }
734                let result = self.buf[start..].to_vec();
735                self.buf_pos = self.buf.len();
736                return Ok(Some(result));
737            }
738
739            // Need more bytes. Drop already-returned statements before `start`.
740            let (removed, got_more) = self.grow_buffer(start)?;
741            start -= removed;
742            i -= removed;
743            if !got_more {
744                // Re-scan the remaining bytes once more with at_eof set so any
745                // incomplete token at the tail is treated literally.
746                at_eof = true;
747            }
748        }
749    }
750
751    /// Check if statement is a PostgreSQL COPY FROM stdin
752    fn is_copy_from_stdin(&self, stmt: &[u8]) -> bool {
753        // Strip leading comments (pg_dump adds -- comments before COPY statements)
754        let stmt = strip_leading_comments_and_whitespace(stmt);
755        if stmt.len() < 17 {
756            // Minimum: "COPY x FROM STDIN" = 17 chars
757            return false;
758        }
759
760        // Check prefix with stack-allocated buffer (avoid heap allocation)
761        let mut prefix = [0u8; 5];
762        for (i, &b) in stmt.iter().take(5).enumerate() {
763            prefix[i] = b.to_ascii_uppercase();
764        }
765        if &prefix != b"COPY " {
766            return false;
767        }
768
769        // Search for "FROM STDIN" case-insensitively without allocating
770        // Look within first 500 bytes (typical COPY statements are shorter)
771        let search_len = stmt.len().min(500);
772        if search_len >= 10 {
773            // Inclusive upper bound so a "FROM STDIN" ending exactly at the
774            // window edge isn't missed.
775            for i in 0..=(search_len - 10) {
776                if stmt[i..i + 10]
777                    .iter()
778                    .zip(b"FROM STDIN".iter())
779                    .all(|(&a, &b)| a.to_ascii_uppercase() == b)
780                {
781                    return true;
782                }
783            }
784        }
785        false
786    }
787
788    /// Read PostgreSQL COPY data block until we see the terminator line (\.).
789    /// The returned block includes everything up to and including the
790    /// terminator line; anything after it is carried in `pending`.
791    ///
792    /// Note: a COPY block is buffered whole in memory (like every other
793    /// statement here) — its size sets the memory floor for a pg_dump with one
794    /// very large table. This is intentional: downstream consumers (redact,
795    /// diff, sample) operate on a full block at a time.
796    fn read_copy_data(&mut self) -> std::io::Result<Option<Vec<u8>>> {
797        let mut start = self.buf_pos;
798        let mut scan = self.buf_pos;
799
800        loop {
801            // Scan completed lines for the terminator.
802            while let Some(rel) = memchr::memchr(b'\n', &self.buf[scan..]) {
803                let nl = scan + rel;
804                let line = &self.buf[scan..=nl];
805                if line == b"\\.\n" || line == b"\\.\r\n" {
806                    self.in_copy_data = false;
807                    let result = self.buf[start..=nl].to_vec();
808                    self.buf_pos = nl + 1;
809                    return Ok(Some(result));
810                }
811                scan = nl + 1;
812            }
813
814            let (removed, got_more) = self.grow_buffer(start)?;
815            start -= removed;
816            scan -= removed;
817            if !got_more {
818                self.in_copy_data = false;
819                if start >= self.buf.len() {
820                    return Ok(None);
821                }
822                let result = self.buf[start..].to_vec();
823                self.buf_pos = self.buf.len();
824                return Ok(Some(result));
825            }
826        }
827    }
828
829    /// Read MSSQL statement with GO batch separator support.
830    /// GO is a batch separator that appears on its own line; `;` also
831    /// terminates. Uses the same `buf` + cursor model as [`read_statement`] so
832    /// tokens can't straddle a chunk boundary and scanning stays O(n).
833    fn read_statement_mssql(&mut self) -> std::io::Result<Option<Vec<u8>>> {
834        let mut start = self.buf_pos;
835        let mut i = self.buf_pos;
836        let mut line_start = self.buf_pos;
837
838        let mut inside_single_quote = false;
839        let mut inside_bracket_quote = false;
840        let mut in_line_comment = false;
841        let mut in_block_comment = false;
842        let mut at_eof = false;
843
844        loop {
845            'scan: while i < self.buf.len() {
846                let b = self.buf[i];
847
848                if in_block_comment {
849                    if b == b'*' {
850                        match self.buf.get(i + 1) {
851                            Some(b'/') => {
852                                in_block_comment = false;
853                                i += 2;
854                                continue;
855                            }
856                            Some(_) => {
857                                i += 1;
858                                continue;
859                            }
860                            None if at_eof => {
861                                i += 1;
862                                continue;
863                            }
864                            None => break 'scan,
865                        }
866                    }
867                    i += 1;
868                    continue;
869                }
870
871                if in_line_comment {
872                    if b == b'\n' {
873                        in_line_comment = false;
874                        line_start = i + 1;
875                    }
876                    i += 1;
877                    continue;
878                }
879
880                if inside_bracket_quote {
881                    if b == b']' {
882                        match self.buf.get(i + 1) {
883                            // Escaped ]] stays inside the identifier (bug #8)
884                            Some(b']') => {
885                                i += 2;
886                                continue;
887                            }
888                            Some(_) => {
889                                inside_bracket_quote = false;
890                                i += 1;
891                                continue;
892                            }
893                            None if at_eof => {
894                                inside_bracket_quote = false;
895                                i += 1;
896                                continue;
897                            }
898                            None => break 'scan,
899                        }
900                    }
901                    i += 1;
902                    continue;
903                }
904
905                if inside_single_quote {
906                    // Fast-skip to the closing quote (MSSQL has no `\` escapes).
907                    match memchr::memchr(b'\'', &self.buf[i..]) {
908                        Some(0) => inside_single_quote = false,
909                        Some(off) => {
910                            i += off;
911                            continue;
912                        }
913                        None if at_eof => {
914                            i = self.buf.len();
915                            continue;
916                        }
917                        None => break 'scan,
918                    }
919                    i += 1;
920                    continue;
921                }
922
923                // Outside strings/comments.
924                if b == b'-' {
925                    match self.buf.get(i + 1) {
926                        Some(b'-') => {
927                            in_line_comment = true;
928                            i += 2;
929                            continue;
930                        }
931                        Some(_) => {
932                            i += 1;
933                            continue;
934                        }
935                        None if at_eof => {
936                            i += 1;
937                            continue;
938                        }
939                        None => break 'scan,
940                    }
941                }
942                if b == b'/' {
943                    match self.buf.get(i + 1) {
944                        Some(b'*') => {
945                            in_block_comment = true;
946                            i += 2;
947                            continue;
948                        }
949                        Some(_) => {
950                            i += 1;
951                            continue;
952                        }
953                        None if at_eof => {
954                            i += 1;
955                            continue;
956                        }
957                        None => break 'scan,
958                    }
959                }
960                if b == b'\'' {
961                    inside_single_quote = true;
962                    i += 1;
963                    continue;
964                }
965                if b == b'[' {
966                    inside_bracket_quote = true;
967                    i += 1;
968                    continue;
969                }
970                if b == b';' {
971                    let result = self.buf[start..=i].to_vec();
972                    self.buf_pos = i + 1;
973                    return Ok(Some(result));
974                }
975                if b == b'\n' {
976                    if is_go_line(&self.buf[line_start..=i]) {
977                        // Trim trailing whitespace before the GO line.
978                        let mut stmt_end = line_start;
979                        while stmt_end > start
980                            && matches!(self.buf[stmt_end - 1], b'\n' | b'\r' | b' ' | b'\t')
981                        {
982                            stmt_end -= 1;
983                        }
984                        self.buf_pos = i + 1;
985                        if stmt_end > start {
986                            return Ok(Some(self.buf[start..stmt_end].to_vec()));
987                        }
988                        // Empty batch: start a new statement after the GO line.
989                        start = i + 1;
990                        line_start = i + 1;
991                        i += 1;
992                        continue;
993                    }
994                    line_start = i + 1;
995                    i += 1;
996                    continue;
997                }
998
999                i += 1;
1000            }
1001
1002            if at_eof {
1003                if start >= self.buf.len() {
1004                    return Ok(None);
1005                }
1006                // Handle a trailing GO with no final newline (bug #12).
1007                if is_go_line(&self.buf[line_start..]) {
1008                    let mut stmt_end = line_start;
1009                    while stmt_end > start
1010                        && matches!(self.buf[stmt_end - 1], b'\n' | b'\r' | b' ' | b'\t')
1011                    {
1012                        stmt_end -= 1;
1013                    }
1014                    self.buf_pos = self.buf.len();
1015                    if stmt_end > start {
1016                        return Ok(Some(self.buf[start..stmt_end].to_vec()));
1017                    }
1018                    return Ok(None);
1019                }
1020                let result = self.buf[start..].to_vec();
1021                self.buf_pos = self.buf.len();
1022                return Ok(Some(result));
1023            }
1024
1025            let (removed, got_more) = self.grow_buffer(start)?;
1026            start -= removed;
1027            i -= removed;
1028            line_start -= removed;
1029            if !got_more {
1030                at_eof = true;
1031            }
1032        }
1033    }
1034
1035    #[allow(dead_code)]
1036    pub fn parse_statement(stmt: &[u8]) -> (StatementType, String) {
1037        Self::parse_statement_with_dialect(stmt, SqlDialect::MySql)
1038    }
1039
1040    /// Parse a statement with dialect-specific handling
1041    pub fn parse_statement_with_dialect(
1042        stmt: &[u8],
1043        dialect: SqlDialect,
1044    ) -> (StatementType, String) {
1045        // Strip leading comments (e.g., pg_dump adds -- comments before statements)
1046        let stmt = strip_leading_comments_and_whitespace(stmt);
1047
1048        if stmt.len() < 4 {
1049            return (StatementType::Unknown, String::new());
1050        }
1051
1052        // Use stack-allocated buffer to avoid heap allocation in hot path
1053        let mut upper_prefix = [0u8; 25];
1054        let prefix_len = stmt.len().min(25);
1055        for (i, &b) in stmt.iter().take(prefix_len).enumerate() {
1056            upper_prefix[i] = b.to_ascii_uppercase();
1057        }
1058        let upper_prefix = &upper_prefix[..prefix_len];
1059
1060        // PostgreSQL COPY statement
1061        if upper_prefix.starts_with(b"COPY ") {
1062            if let Some(caps) = COPY_RE.captures(stmt) {
1063                if let Some(m) = caps.get(1) {
1064                    let name = String::from_utf8_lossy(m.as_bytes()).into_owned();
1065                    // Handle schema.table - extract just the table name
1066                    let table_name = name.split('.').next_back().unwrap_or(&name).to_string();
1067                    return (StatementType::Copy, table_name);
1068                }
1069            }
1070        }
1071
1072        if upper_prefix.starts_with(b"CREATE TABLE") {
1073            // Try fast extraction first
1074            if let Some(name) = extract_table_name_flexible(stmt, 12, dialect) {
1075                return (StatementType::CreateTable, name);
1076            }
1077            // Fall back to flexible regex
1078            if let Some(caps) = CREATE_TABLE_FLEXIBLE_RE.captures(stmt) {
1079                if let Some(m) = caps.get(1) {
1080                    return (
1081                        StatementType::CreateTable,
1082                        String::from_utf8_lossy(m.as_bytes()).into_owned(),
1083                    );
1084                }
1085            }
1086        }
1087
1088        if upper_prefix.starts_with(b"INSERT INTO") || upper_prefix.starts_with(b"INSERT ONLY") {
1089            if let Some(name) = extract_table_name_flexible(stmt, 11, dialect) {
1090                return (StatementType::Insert, name);
1091            }
1092            if let Some(caps) = INSERT_FLEXIBLE_RE.captures(stmt) {
1093                if let Some(m) = caps.get(1) {
1094                    return (
1095                        StatementType::Insert,
1096                        String::from_utf8_lossy(m.as_bytes()).into_owned(),
1097                    );
1098                }
1099            }
1100        }
1101
1102        if upper_prefix.starts_with(b"CREATE INDEX")
1103            || upper_prefix.starts_with(b"CREATE UNIQUE")
1104            || upper_prefix.starts_with(b"CREATE CLUSTERED")
1105            || upper_prefix.starts_with(b"CREATE NONCLUSTER")
1106        {
1107            // For MSSQL, try the bracket-aware regex first
1108            if dialect == SqlDialect::Mssql {
1109                if let Some(caps) = CREATE_INDEX_MSSQL_RE.captures(stmt) {
1110                    if let Some(m) = caps.get(1) {
1111                        return (
1112                            StatementType::CreateIndex,
1113                            String::from_utf8_lossy(m.as_bytes()).into_owned(),
1114                        );
1115                    }
1116                }
1117            }
1118            // Fall back to generic regex for MySQL/PostgreSQL/SQLite
1119            if let Some(caps) = CREATE_INDEX_RE.captures(stmt) {
1120                if let Some(m) = caps.get(1) {
1121                    let name = String::from_utf8_lossy(m.as_bytes());
1122                    // Strip schema qualifier (public.users -> users) so indexes
1123                    // group under the same key as their CREATE TABLE, which also
1124                    // strips the schema.
1125                    let table_name = name.split('.').next_back().unwrap_or(&name).to_string();
1126                    return (StatementType::CreateIndex, table_name);
1127                }
1128            }
1129        }
1130
1131        if upper_prefix.starts_with(b"ALTER TABLE") {
1132            if let Some(name) = extract_table_name_flexible(stmt, 11, dialect) {
1133                return (StatementType::AlterTable, name);
1134            }
1135            if let Some(caps) = ALTER_TABLE_RE.captures(stmt) {
1136                if let Some(m) = caps.get(1) {
1137                    return (
1138                        StatementType::AlterTable,
1139                        String::from_utf8_lossy(m.as_bytes()).into_owned(),
1140                    );
1141                }
1142            }
1143        }
1144
1145        if upper_prefix.starts_with(b"DROP TABLE") {
1146            if let Some(name) = extract_table_name_flexible(stmt, 10, dialect) {
1147                return (StatementType::DropTable, name);
1148            }
1149            if let Some(caps) = DROP_TABLE_RE.captures(stmt) {
1150                if let Some(m) = caps.get(1) {
1151                    return (
1152                        StatementType::DropTable,
1153                        String::from_utf8_lossy(m.as_bytes()).into_owned(),
1154                    );
1155                }
1156            }
1157        }
1158
1159        // MSSQL BULK INSERT - treat as Insert statement type
1160        if upper_prefix.starts_with(b"BULK INSERT") {
1161            if let Some(name) = extract_table_name_flexible(stmt, 11, dialect) {
1162                return (StatementType::Insert, name);
1163            }
1164        }
1165
1166        (StatementType::Unknown, String::new())
1167    }
1168}
1169
1170#[inline]
1171fn trim_ascii_start(data: &[u8]) -> &[u8] {
1172    let start = data
1173        .iter()
1174        .position(|&b| !matches!(b, b' ' | b'\t' | b'\n' | b'\r'))
1175        .unwrap_or(data.len());
1176    &data[start..]
1177}
1178
1179/// Strip leading whitespace and SQL line comments (`-- ...`) from a statement.
1180/// This makes parsing robust to pg_dump-style comment blocks before statements.
1181fn strip_leading_comments_and_whitespace(mut data: &[u8]) -> &[u8] {
1182    loop {
1183        // First trim leading ASCII whitespace
1184        data = trim_ascii_start(data);
1185
1186        // Handle -- line comments
1187        if data.len() >= 2 && data[0] == b'-' && data[1] == b'-' {
1188            // Skip until end of line
1189            if let Some(pos) = data.iter().position(|&b| b == b'\n') {
1190                data = &data[pos + 1..];
1191                continue;
1192            } else {
1193                // Comment runs to EOF, nothing left
1194                return &[];
1195            }
1196        }
1197
1198        // Handle /* */ block comments (including MySQL conditional comments)
1199        if data.len() >= 2 && data[0] == b'/' && data[1] == b'*' {
1200            // Find the closing */
1201            let mut i = 2;
1202            let mut depth = 1;
1203            while i < data.len() - 1 && depth > 0 {
1204                if data[i] == b'*' && data[i + 1] == b'/' {
1205                    depth -= 1;
1206                    i += 2;
1207                } else if data[i] == b'/' && data[i + 1] == b'*' {
1208                    depth += 1;
1209                    i += 2;
1210                } else {
1211                    i += 1;
1212                }
1213            }
1214            if depth == 0 {
1215                data = &data[i..];
1216                continue;
1217            } else {
1218                // Unclosed comment runs to EOF
1219                return &[];
1220            }
1221        }
1222
1223        // Handle # line comments (MySQL)
1224        if !data.is_empty() && data[0] == b'#' {
1225            if let Some(pos) = data.iter().position(|&b| b == b'\n') {
1226                data = &data[pos + 1..];
1227                continue;
1228            } else {
1229                return &[];
1230            }
1231        }
1232
1233        break;
1234    }
1235
1236    data
1237}
1238
1239/// Extract table name with support for:
1240/// - IF NOT EXISTS
1241/// - ONLY (PostgreSQL)
1242/// - Schema-qualified names (schema.table)
1243/// - Both backtick and double-quote quoting
1244#[inline]
1245fn extract_table_name_flexible(stmt: &[u8], offset: usize, dialect: SqlDialect) -> Option<String> {
1246    let mut i = offset;
1247
1248    // Skip whitespace
1249    while i < stmt.len() && is_whitespace(stmt[i]) {
1250        i += 1;
1251    }
1252
1253    if i >= stmt.len() {
1254        return None;
1255    }
1256
1257    // Check for IF NOT EXISTS or IF EXISTS (stack-allocated to avoid heap allocation)
1258    let mut upper_check = [0u8; 20];
1259    let check_len = (stmt.len() - i).min(20);
1260    for (idx, &b) in stmt[i..].iter().take(check_len).enumerate() {
1261        upper_check[idx] = b.to_ascii_uppercase();
1262    }
1263    let upper_slice = &upper_check[..check_len];
1264    if upper_slice.starts_with(b"IF NOT EXISTS") {
1265        i += 13; // Skip "IF NOT EXISTS"
1266        while i < stmt.len() && is_whitespace(stmt[i]) {
1267            i += 1;
1268        }
1269    } else if upper_slice.starts_with(b"IF EXISTS") {
1270        i += 9; // Skip "IF EXISTS"
1271        while i < stmt.len() && is_whitespace(stmt[i]) {
1272            i += 1;
1273        }
1274    }
1275
1276    // Check for ONLY (PostgreSQL) - reuse first 10 bytes or re-check if position changed
1277    let only_check = if i < stmt.len() {
1278        let mut buf = [0u8; 10];
1279        let len = (stmt.len() - i).min(10);
1280        for (idx, &b) in stmt[i..].iter().take(len).enumerate() {
1281            buf[idx] = b.to_ascii_uppercase();
1282        }
1283        (buf, len)
1284    } else {
1285        ([0u8; 10], 0)
1286    };
1287    let only_slice = &only_check.0[..only_check.1];
1288    if only_slice.starts_with(b"ONLY ") || only_slice.starts_with(b"ONLY\t") {
1289        i += 4;
1290        while i < stmt.len() && is_whitespace(stmt[i]) {
1291            i += 1;
1292        }
1293    }
1294
1295    if i >= stmt.len() {
1296        return None;
1297    }
1298
1299    // Read identifier (potentially schema-qualified)
1300    let mut parts: Vec<String> = Vec::new();
1301
1302    loop {
1303        // Determine quote character based on dialect
1304        let (quote_char, close_char) = match stmt.get(i) {
1305            Some(b'`') if dialect == SqlDialect::MySql => {
1306                i += 1;
1307                (Some(b'`'), b'`')
1308            }
1309            // Double quotes are the standard identifier quote for
1310            // Postgres/SQLite/MSSQL, and accepted for MySQL too (less common).
1311            Some(b'"') => {
1312                i += 1;
1313                (Some(b'"'), b'"')
1314            }
1315            Some(b'[') if dialect == SqlDialect::Mssql => {
1316                // MSSQL square bracket quoting
1317                i += 1;
1318                (Some(b'['), b']')
1319            }
1320            _ => (None, 0),
1321        };
1322
1323        let start = i;
1324
1325        while i < stmt.len() {
1326            let b = stmt[i];
1327            if quote_char.is_some() {
1328                if b == close_char {
1329                    // For MSSQL, check for escaped ]]
1330                    if dialect == SqlDialect::Mssql
1331                        && close_char == b']'
1332                        && i + 1 < stmt.len()
1333                        && stmt[i + 1] == b']'
1334                    {
1335                        // Escaped bracket, skip both
1336                        i += 2;
1337                        continue;
1338                    }
1339                    let name = &stmt[start..i];
1340                    // For MSSQL, unescape ]] to ]
1341                    let name_str = if dialect == SqlDialect::Mssql {
1342                        String::from_utf8_lossy(name).replace("]]", "]")
1343                    } else {
1344                        String::from_utf8_lossy(name).into_owned()
1345                    };
1346                    parts.push(name_str);
1347                    i += 1; // Skip closing quote
1348                    break;
1349                }
1350            } else if is_whitespace(b) || b == b'(' || b == b';' || b == b',' || b == b'.' {
1351                if i > start {
1352                    let name = &stmt[start..i];
1353                    parts.push(String::from_utf8_lossy(name).into_owned());
1354                }
1355                break;
1356            }
1357            i += 1;
1358        }
1359
1360        // If at end of quoted name without finding close quote, bail
1361        if quote_char.is_some() && i <= start {
1362            break;
1363        }
1364
1365        // Check for schema separator (.)
1366        while i < stmt.len() && is_whitespace(stmt[i]) {
1367            i += 1;
1368        }
1369
1370        if i < stmt.len() && stmt[i] == b'.' {
1371            i += 1; // Skip the dot
1372            while i < stmt.len() && is_whitespace(stmt[i]) {
1373                i += 1;
1374            }
1375            // Continue to read the next identifier (table name)
1376        } else {
1377            break;
1378        }
1379    }
1380
1381    // Return the last part (table name), not the schema
1382    parts.pop()
1383}
1384
1385#[inline]
1386fn is_whitespace(b: u8) -> bool {
1387    matches!(b, b' ' | b'\t' | b'\n' | b'\r')
1388}
1389
1390/// A dollar-quote tag is either empty (`$$`) or an identifier
1391/// (`[A-Za-z_][A-Za-z0-9_]*`), matching PostgreSQL's rules.
1392#[inline]
1393fn is_valid_dollar_tag(tag: &[u8]) -> bool {
1394    match tag.first() {
1395        None => true,
1396        Some(&first) if first.is_ascii_alphabetic() || first == b'_' => tag[1..]
1397            .iter()
1398            .all(|&c| c.is_ascii_alphanumeric() || c == b'_'),
1399        _ => false,
1400    }
1401}
1402
1403pub fn determine_buffer_size(file_size: u64) -> usize {
1404    if file_size > 1024 * 1024 * 1024 {
1405        MEDIUM_BUFFER_SIZE
1406    } else {
1407        SMALL_BUFFER_SIZE
1408    }
1409}