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 its first 8KB. Goes through
237/// [`crate::splitter::open_input`] so compressed and zipped inputs are
238/// transparently decoded before sniffing — without that, detection would
239/// see raw compressed bytes instead of SQL text.
240pub fn detect_dialect_from_file(path: &std::path::Path) -> anyhow::Result<DialectDetectionResult> {
241    use std::io::Read;
242
243    let mut reader = crate::splitter::open_input(path)?;
244    let mut buf = [0u8; 8192];
245    let n = reader.read(&mut buf)?;
246    Ok(detect_dialect(&buf[..n]))
247}
248
249#[inline]
250fn contains_bytes(haystack: &[u8], needle: &[u8]) -> bool {
251    memchr::memmem::find(haystack, needle).is_some()
252}
253
254/// Check if a line is a MSSQL GO batch separator
255/// GO must be on its own line (with optional whitespace and optional repeat count)
256/// Examples: "GO\n", "  GO  \n", "GO 100\n", "go\r\n"
257fn is_go_line(line: &[u8]) -> bool {
258    // Trim leading whitespace
259    let mut start = 0;
260    while start < line.len()
261        && (line[start] == b' ' || line[start] == b'\t' || line[start] == b'\r')
262    {
263        start += 1;
264    }
265
266    // Trim trailing whitespace and newlines
267    let mut end = line.len();
268    while end > start
269        && (line[end - 1] == b' '
270            || line[end - 1] == b'\t'
271            || line[end - 1] == b'\r'
272            || line[end - 1] == b'\n')
273    {
274        end -= 1;
275    }
276
277    let trimmed = &line[start..end];
278
279    if trimmed.len() < 2 {
280        return false;
281    }
282
283    // Check for "GO" (case-insensitive)
284    if trimmed.len() == 2 {
285        return (trimmed[0] == b'G' || trimmed[0] == b'g')
286            && (trimmed[1] == b'O' || trimmed[1] == b'o');
287    }
288
289    // Check for "GO <number>" pattern
290    if (trimmed[0] == b'G' || trimmed[0] == b'g')
291        && (trimmed[1] == b'O' || trimmed[1] == b'o')
292        && (trimmed[2] == b' ' || trimmed[2] == b'\t')
293    {
294        // Rest should be whitespace and digits (allocation-free scan)
295        return trimmed[3..]
296            .iter()
297            .skip_while(|&&b| b == b' ' || b == b'\t')
298            .all(|&b| b.is_ascii_digit());
299    }
300
301    false
302}
303
304#[derive(Debug, Clone, Copy, PartialEq, Eq)]
305pub enum StatementType {
306    Unknown,
307    CreateTable,
308    Insert,
309    CreateIndex,
310    AlterTable,
311    DropTable,
312    /// PostgreSQL COPY FROM stdin
313    Copy,
314}
315
316impl StatementType {
317    /// Returns true if this is a schema-related statement (DDL)
318    pub fn is_schema(&self) -> bool {
319        matches!(
320            self,
321            StatementType::CreateTable
322                | StatementType::CreateIndex
323                | StatementType::AlterTable
324                | StatementType::DropTable
325        )
326    }
327
328    /// Returns true if this is a data-related statement (DML)
329    pub fn is_data(&self) -> bool {
330        matches!(self, StatementType::Insert | StatementType::Copy)
331    }
332}
333
334/// Content filter mode for splitting
335#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
336pub enum ContentFilter {
337    /// Include both schema and data statements (default)
338    #[default]
339    All,
340    /// Only schema statements (CREATE TABLE, CREATE INDEX, ALTER TABLE, DROP TABLE)
341    SchemaOnly,
342    /// Only data statements (INSERT, COPY)
343    DataOnly,
344}
345
346// Word boundary before ON so index names ending in "on" (idx_position,
347// idx_created_on, ...) don't match the "on" inside the identifier.
348static CREATE_INDEX_RE: Lazy<Regex> =
349    Lazy::new(|| Regex::new(r"(?i)\bON\s+`?([^\s`(;]+)`?").unwrap());
350
351// MSSQL CREATE INDEX: extracts table from ON [schema].[table] or ON [table]
352// Matches: ON [table], ON [dbo].[table], ON [db].[dbo].[table]
353// Captures the last bracketed or unbracketed identifier before (
354static CREATE_INDEX_MSSQL_RE: Lazy<Regex> =
355    Lazy::new(|| Regex::new(r"(?i)ON\s+(?:\[?[^\[\]\s]+\]?\s*\.\s*)*\[([^\[\]]+)\]").unwrap());
356
357static ALTER_TABLE_RE: Lazy<Regex> =
358    Lazy::new(|| Regex::new(r"(?i)ALTER\s+TABLE\s+`?([^\s`;]+)`?").unwrap());
359
360static DROP_TABLE_RE: Lazy<Regex> = Lazy::new(|| {
361    Regex::new(r#"(?i)DROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?[`"]?([^\s`"`;]+)[`"]?"#).unwrap()
362});
363
364// PostgreSQL COPY statement regex
365static COPY_RE: Lazy<Regex> =
366    Lazy::new(|| Regex::new(r#"(?i)^\s*COPY\s+(?:ONLY\s+)?[`"]?([^\s`"(]+)[`"]?"#).unwrap());
367
368// More flexible table name regex that handles:
369// - Backticks: `table`
370// - Double quotes: "table"
371// - Schema qualified: schema.table, `schema`.`table`, "schema"."table"
372// - IF NOT EXISTS
373static CREATE_TABLE_FLEXIBLE_RE: Lazy<Regex> = Lazy::new(|| {
374    Regex::new(r#"(?i)^\s*CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(?:[`"]?[\w]+[`"]?\s*\.\s*)?[`"]?([\w]+)[`"]?"#).unwrap()
375});
376
377static INSERT_FLEXIBLE_RE: Lazy<Regex> = Lazy::new(|| {
378    Regex::new(
379        r#"(?i)^\s*INSERT\s+INTO\s+(?:ONLY\s+)?(?:[`"]?[\w]+[`"]?\s*\.\s*)?[`"]?([\w]+)[`"]?"#,
380    )
381    .unwrap()
382});
383
384/// Result of peeking at the byte after position `i` for a two-byte token
385/// (`--`, `/*`, `*/`, `]]`). See [`Parser::peek2`].
386#[derive(Clone, Copy, PartialEq, Eq)]
387enum Peek2 {
388    /// The next byte is present and matches: the token is complete.
389    Hit,
390    /// The next byte differs, or input ended at EOF (a dangling first byte at
391    /// the tail is treated as a literal byte).
392    Miss,
393    /// The buffer ends here but more input may arrive: the caller must pause
394    /// the scan (`break 'scan`) with its state intact so the token can never
395    /// straddle a refill (see the `buf` field docs).
396    NeedMore,
397}
398
399/// Control-flow signal returned by row/event visitors.
400///
401/// Lives in the parser layer (rather than a consumer module) so the streaming
402/// row visitors ([`crate::parser::mysql_insert::visit_insert_rows_with`],
403/// [`crate::parser::postgres_copy::visit_postgres_copy_rows_with`]) and
404/// [`Parser::visit_events`] can all speak the same vocabulary. Re-exported from
405/// `crate::transform_common` for the sample/shard consumers.
406#[derive(Debug, Clone, Copy, PartialEq, Eq)]
407pub enum RowFlow {
408    /// Keep iterating.
409    Continue,
410    /// Skip the remaining rows of the current INSERT/COPY statement, then
411    /// resume with the next statement.
412    SkipStatement,
413    /// Stop the walk entirely.
414    Stop,
415}
416
417/// A single streaming event emitted by [`Parser::visit_events`].
418///
419/// Data rows are treated as stream boundaries: a multi-row INSERT is delivered
420/// as its shared header plus one [`ParserEvent::InsertRow`] per tuple, and a
421/// COPY block as [`ParserEvent::CopyStart`] / one [`ParserEvent::CopyRow`] per
422/// line / [`ParserEvent::CopyEnd`] — never buffering the whole block. All byte
423/// slices borrow from the parser's internal buffer (or, for `InsertRow.header`,
424/// a small owned copy of the header) and are only valid until the callback
425/// returns.
426pub enum ParserEvent<'a> {
427    /// A complete non-data statement (DDL / control), including its terminator.
428    Statement(&'a [u8]),
429    /// One INSERT `(...)` value tuple. `header` is the statement text up to and
430    /// including the `VALUES` keyword (so the column list can be recovered);
431    /// `first_in_statement` is true for the first row of each INSERT so callers
432    /// can rebuild per-statement column context exactly once.
433    InsertRow {
434        header: &'a [u8],
435        row: &'a [u8],
436        first_in_statement: bool,
437    },
438    /// The `COPY ... FROM stdin;` header line that opens a COPY data block.
439    CopyStart(&'a [u8]),
440    /// One raw COPY data line (newline stripped; a trailing `\r`, if any, is
441    /// left for the consumer to strip so it matches the collecting parser).
442    CopyRow(&'a [u8]),
443    /// The `\.` terminator that closes a COPY data block.
444    CopyEnd,
445}
446
447/// Configurable safety caps on how much a single buffered unit may grow before
448/// [`Parser::visit_events`] reports an error (rather than silently truncating
449/// or buffering without bound). Defaults are generous; they exist to turn a
450/// pathological/corrupt input into a diagnosable error instead of an OOM.
451#[derive(Debug, Clone, Copy)]
452pub struct ParserLimits {
453    /// Max bytes for one non-data statement (DDL/control).
454    pub max_ddl: usize,
455    /// Max bytes for an INSERT/COPY header before the first row.
456    pub max_header: usize,
457    /// Max bytes for a single INSERT tuple or COPY line.
458    pub max_row: usize,
459}
460
461impl Default for ParserLimits {
462    fn default() -> Self {
463        Self {
464            max_ddl: 256 * 1024 * 1024,
465            max_header: 64 * 1024 * 1024,
466            max_row: 256 * 1024 * 1024,
467        }
468    }
469}
470
471pub struct Parser<R: Read> {
472    reader: BufReader<R>,
473    dialect: SqlDialect,
474    /// For PostgreSQL: true when reading COPY data block
475    in_copy_data: bool,
476    /// Accumulated, not-yet-returned input. The scanners read whole `fill_buf`
477    /// chunks into `buf` and scan it with an index cursor, so a multi-byte
478    /// token (`--`, `/* */`, `$tag$`, `]]`) can never straddle an internal
479    /// buffer boundary. `buf_pos` is the start of the next statement to return;
480    /// bytes before it are already-returned and are dropped on the next refill
481    /// (never per-statement) so scanning stays O(n) rather than O(n²).
482    buf: Vec<u8>,
483    buf_pos: usize,
484    /// Number of bytes dropped off the front of `buf` so far, so an absolute
485    /// input offset can be reported in [`Parser::visit_events`] diagnostics.
486    base: u64,
487    /// High-water mark of `buf.len()`, so tests can assert the streaming walker
488    /// keeps its working set bounded.
489    peak_buffered: usize,
490    /// Safety caps for [`Parser::visit_events`].
491    limits: ParserLimits,
492}
493
494impl<R: Read> Parser<R> {
495    #[allow(dead_code)]
496    pub fn new(reader: R, buffer_size: usize) -> Self {
497        Self::with_dialect(reader, buffer_size, SqlDialect::default())
498    }
499
500    pub fn with_dialect(reader: R, buffer_size: usize, dialect: SqlDialect) -> Self {
501        Self {
502            reader: BufReader::with_capacity(buffer_size, reader),
503            dialect,
504            in_copy_data: false,
505            buf: Vec::new(),
506            buf_pos: 0,
507            base: 0,
508            peak_buffered: 0,
509            limits: ParserLimits::default(),
510        }
511    }
512
513    /// Override the [`ParserLimits`] used by [`Parser::visit_events`].
514    #[allow(dead_code)]
515    pub fn with_limits(mut self, limits: ParserLimits) -> Self {
516        self.limits = limits;
517        self
518    }
519
520    /// Total bytes currently buffered in memory. Used by tests to assert the
521    /// event walker keeps its working set bounded even for huge INSERT/COPY
522    /// blocks.
523    pub fn buffered_len(&self) -> usize {
524        self.buf.len()
525    }
526
527    /// High-water mark of buffered bytes over this parser's lifetime. Used by
528    /// tests to assert [`Parser::visit_events`] never buffers a whole multi-row
529    /// INSERT/COPY block.
530    pub fn peak_buffered(&self) -> usize {
531        self.peak_buffered
532    }
533
534    /// Drop the already-returned prefix `buf[..keep_from]` and append the next
535    /// `fill_buf` chunk. Returns `(bytes_removed_from_front, got_more_data)`.
536    /// Callers subtract `bytes_removed_from_front` from their scan indices.
537    #[inline]
538    fn grow_buffer(&mut self, keep_from: usize) -> std::io::Result<(usize, bool)> {
539        if keep_from > 0 {
540            self.buf.drain(..keep_from);
541            self.base += keep_from as u64;
542        }
543        let chunk = self.reader.fill_buf()?;
544        if chunk.is_empty() {
545            return Ok((keep_from, false));
546        }
547        self.buf.extend_from_slice(chunk);
548        let n = chunk.len();
549        self.reader.consume(n);
550        self.peak_buffered = self.peak_buffered.max(self.buf.len());
551        Ok((keep_from, true))
552    }
553
554    /// Classify the byte after `i` against the second byte of a two-byte
555    /// token. Centralizes the boundary handling shared by every such token in
556    /// [`read_statement`](Self::read_statement) and `read_statement_mssql`.
557    #[inline(always)]
558    fn peek2(&self, i: usize, expected: u8, at_eof: bool) -> Peek2 {
559        match self.buf.get(i + 1) {
560            Some(&c) if c == expected => Peek2::Hit,
561            Some(_) => Peek2::Miss,
562            None if at_eof => Peek2::Miss,
563            None => Peek2::NeedMore,
564        }
565    }
566
567    pub fn read_statement(&mut self) -> std::io::Result<Option<Vec<u8>>> {
568        // If we're in PostgreSQL COPY data mode, read until we see the terminator
569        if self.in_copy_data {
570            return self.read_copy_data();
571        }
572
573        // For MSSQL, use line-based parsing to handle GO batch separator
574        if self.dialect == SqlDialect::Mssql {
575            return self.read_statement_mssql();
576        }
577
578        let is_mysql = self.dialect == SqlDialect::MySql;
579        let is_postgres = self.dialect == SqlDialect::Postgres;
580
581        // Scan `self.buf` from the current statement start with an index cursor.
582        // More data is appended by `grow_buffer` (which also drops already-
583        // returned statements), so a multi-byte token (`--`, `/* */`, `$tag$`)
584        // never straddles a chunk boundary: the scan waits for more bytes with
585        // its state (`i`, quote/comment flags) intact.
586        let mut start = self.buf_pos;
587        let mut i = self.buf_pos;
588
589        let mut inside_single_quote = false;
590        let mut inside_double_quote = false;
591        let mut inside_backtick = false; // MySQL `identifier` quoting (bug #10)
592        let mut escaped = false;
593        let mut in_line_comment = false;
594        let mut in_block_comment = false; // /* ... */ (bug #5)
595        let mut in_dollar_quote = false;
596        let mut dollar_tag: Vec<u8> = Vec::new();
597        let mut at_eof = false;
598
599        // Lookup table of bytes that are significant outside strings/comments;
600        // everything else can be skipped in a tight loop.
601        let mut sig = [false; 256];
602        for &c in b";'\"-/" {
603            sig[c as usize] = true;
604        }
605        if is_mysql {
606            sig[b'`' as usize] = true;
607            sig[b'#' as usize] = true;
608        }
609        if is_postgres {
610            sig[b'$' as usize] = true;
611        }
612
613        loop {
614            'scan: while i < self.buf.len() {
615                let b = self.buf[i];
616
617                // Inside a /* */ block comment: only the closing */ ends it.
618                if in_block_comment {
619                    if b == b'*' {
620                        match self.peek2(i, b'/', at_eof) {
621                            Peek2::Hit => {
622                                in_block_comment = false;
623                                i += 2;
624                                continue;
625                            }
626                            Peek2::Miss => {
627                                i += 1;
628                                continue;
629                            }
630                            Peek2::NeedMore => break 'scan,
631                        }
632                    }
633                    i += 1;
634                    continue;
635                }
636
637                // Inside a -- or # line comment: consume until newline.
638                if in_line_comment {
639                    if b == b'\n' {
640                        in_line_comment = false;
641                    }
642                    i += 1;
643                    continue;
644                }
645
646                if escaped {
647                    escaped = false;
648                    i += 1;
649                    continue;
650                }
651
652                let inside_string = inside_single_quote
653                    || inside_double_quote
654                    || inside_backtick
655                    || in_dollar_quote;
656
657                // Fast path: inside a string/quoted region only the closing
658                // delimiter (and, for MySQL, a `\` escape) is significant, so
659                // memchr past the ordinary bytes. This is the hot loop for
660                // INSERT string data.
661                if inside_string {
662                    let rest = &self.buf[i..];
663                    let hit = if inside_single_quote {
664                        if is_mysql {
665                            memchr::memchr2(b'\'', b'\\', rest)
666                        } else {
667                            memchr::memchr(b'\'', rest)
668                        }
669                    } else if inside_double_quote {
670                        if is_mysql {
671                            memchr::memchr2(b'"', b'\\', rest)
672                        } else {
673                            memchr::memchr(b'"', rest)
674                        }
675                    } else if inside_backtick {
676                        memchr::memchr(b'`', rest)
677                    } else {
678                        // in_dollar_quote: only `$` can start the closing tag
679                        memchr::memchr(b'$', rest)
680                    };
681                    match hit {
682                        Some(0) => {} // significant byte at i
683                        Some(off) => {
684                            i += off;
685                            continue;
686                        }
687                        None if at_eof => {
688                            i = self.buf.len();
689                            continue;
690                        }
691                        None => break 'scan,
692                    }
693                }
694
695                // MySQL backslash escapes apply inside both '…' and "…" string
696                // literals (but not backtick identifiers or dollar quotes).
697                if b == b'\\' && (inside_single_quote || inside_double_quote) && is_mysql {
698                    escaped = true;
699                    i += 1;
700                    continue;
701                }
702
703                if !inside_string {
704                    // Fast path: skip runs of insignificant bytes outside any
705                    // string/comment with a tight table lookup.
706                    if !sig[b as usize] {
707                        let mut j = i + 1;
708                        while j < self.buf.len() && !sig[self.buf[j] as usize] {
709                            j += 1;
710                        }
711                        i = j;
712                        continue;
713                    }
714                    // -- line comment
715                    if b == b'-' {
716                        match self.peek2(i, b'-', at_eof) {
717                            Peek2::Hit => {
718                                // MySQL requires whitespace/EOL after `--` for it
719                                // to be a comment; `a--b` is arithmetic. Other
720                                // dialects always treat `--` as a comment.
721                                if is_mysql {
722                                    match self.buf.get(i + 2) {
723                                        Some(&c)
724                                            if c == b' '
725                                                || c == b'\t'
726                                                || c == b'\n'
727                                                || c == b'\r' =>
728                                        {
729                                            in_line_comment = true;
730                                            i += 2;
731                                            continue;
732                                        }
733                                        None if at_eof => {
734                                            in_line_comment = true;
735                                            i += 2;
736                                            continue;
737                                        }
738                                        None => break 'scan,
739                                        // `--x`: not a comment, just consume one `-`.
740                                        Some(_) => {
741                                            i += 1;
742                                            continue;
743                                        }
744                                    }
745                                }
746                                in_line_comment = true;
747                                i += 2;
748                                continue;
749                            }
750                            Peek2::Miss => {
751                                i += 1;
752                                continue;
753                            }
754                            Peek2::NeedMore => break 'scan,
755                        }
756                    }
757                    // MySQL # line comment
758                    if b == b'#' && is_mysql {
759                        in_line_comment = true;
760                        i += 1;
761                        continue;
762                    }
763                    // /* block comment
764                    if b == b'/' {
765                        match self.peek2(i, b'*', at_eof) {
766                            Peek2::Hit => {
767                                in_block_comment = true;
768                                i += 2;
769                                continue;
770                            }
771                            Peek2::Miss => {
772                                i += 1;
773                                continue;
774                            }
775                            Peek2::NeedMore => break 'scan,
776                        }
777                    }
778                }
779
780                // PostgreSQL dollar-quoting (outside other quotes).
781                if is_postgres && !inside_single_quote && !inside_double_quote && !inside_backtick {
782                    if b == b'$' && !in_dollar_quote {
783                        match self.buf[i + 1..].iter().position(|&c| c == b'$') {
784                            Some(end) => {
785                                let tag_bytes = &self.buf[i + 1..i + 1 + end];
786                                if is_valid_dollar_tag(tag_bytes) {
787                                    dollar_tag = tag_bytes.to_vec();
788                                    in_dollar_quote = true;
789                                    // Skip the whole opening $tag$ so its trailing
790                                    // $ is not re-read as a closer (bug #7).
791                                    i += end + 2;
792                                    continue;
793                                }
794                                // Not a valid tag: treat $ as an ordinary byte.
795                                i += 1;
796                                continue;
797                            }
798                            None if at_eof => {
799                                i += 1;
800                                continue;
801                            }
802                            // No closing $ yet — it may arrive in the next chunk.
803                            None => break 'scan,
804                        }
805                    } else if b == b'$' && in_dollar_quote {
806                        let tag_len = dollar_tag.len();
807                        if i + 1 + tag_len < self.buf.len() {
808                            if self.buf[i + 1..i + 1 + tag_len] == dollar_tag[..]
809                                && self.buf[i + 1 + tag_len] == b'$'
810                            {
811                                in_dollar_quote = false;
812                                dollar_tag.clear();
813                                i += tag_len + 2;
814                                continue;
815                            }
816                            i += 1;
817                            continue;
818                        } else if at_eof {
819                            i += 1;
820                            continue;
821                        } else {
822                            break 'scan;
823                        }
824                    }
825                }
826
827                if b == b'\'' && !inside_double_quote && !inside_backtick && !in_dollar_quote {
828                    inside_single_quote = !inside_single_quote;
829                } else if b == b'"' && !inside_single_quote && !inside_backtick && !in_dollar_quote
830                {
831                    inside_double_quote = !inside_double_quote;
832                } else if b == b'`'
833                    && is_mysql
834                    && !inside_single_quote
835                    && !inside_double_quote
836                    && !in_dollar_quote
837                {
838                    inside_backtick = !inside_backtick;
839                } else if b == b';' && !inside_string {
840                    // Statement terminator. The bytes after it stay in `buf` and
841                    // become the next statement (buf_pos advances, no shifting).
842                    let result = self.buf[start..=i].to_vec();
843                    self.buf_pos = i + 1;
844
845                    if is_postgres && self.is_copy_from_stdin(&result) {
846                        self.in_copy_data = true;
847                    }
848                    return Ok(Some(result));
849                }
850
851                i += 1;
852            }
853
854            if at_eof {
855                if start >= self.buf.len() {
856                    return Ok(None);
857                }
858                let result = self.buf[start..].to_vec();
859                self.buf_pos = self.buf.len();
860                return Ok(Some(result));
861            }
862
863            // Need more bytes. Drop already-returned statements before `start`.
864            let (removed, got_more) = self.grow_buffer(start)?;
865            start -= removed;
866            i -= removed;
867            if !got_more {
868                // Re-scan the remaining bytes once more with at_eof set so any
869                // incomplete token at the tail is treated literally.
870                at_eof = true;
871            }
872        }
873    }
874
875    /// Check if statement is a PostgreSQL COPY FROM stdin
876    fn is_copy_from_stdin(&self, stmt: &[u8]) -> bool {
877        // Strip leading comments (pg_dump adds -- comments before COPY statements)
878        let stmt = strip_leading_comments_and_whitespace(stmt);
879        if stmt.len() < 17 {
880            // Minimum: "COPY x FROM STDIN" = 17 chars
881            return false;
882        }
883
884        // Check prefix with stack-allocated buffer (avoid heap allocation)
885        let mut prefix = [0u8; 5];
886        for (i, &b) in stmt.iter().take(5).enumerate() {
887            prefix[i] = b.to_ascii_uppercase();
888        }
889        if &prefix != b"COPY " {
890            return false;
891        }
892
893        // Search for "FROM STDIN" case-insensitively without allocating
894        // Look within first 500 bytes (typical COPY statements are shorter)
895        let search_len = stmt.len().min(500);
896        if search_len >= 10 {
897            // Inclusive upper bound so a "FROM STDIN" ending exactly at the
898            // window edge isn't missed.
899            for i in 0..=(search_len - 10) {
900                if stmt[i..i + 10]
901                    .iter()
902                    .zip(b"FROM STDIN".iter())
903                    .all(|(&a, &b)| a.to_ascii_uppercase() == b)
904                {
905                    return true;
906                }
907            }
908        }
909        false
910    }
911
912    /// Read PostgreSQL COPY data block until we see the terminator line (\.).
913    /// The returned block includes everything up to and including the
914    /// terminator line; anything after it is carried in `pending`.
915    ///
916    /// Note: a COPY block is buffered whole in memory (like every other
917    /// statement here) — its size sets the memory floor for a pg_dump with one
918    /// very large table. This is intentional: downstream consumers (redact,
919    /// diff, sample) operate on a full block at a time.
920    fn read_copy_data(&mut self) -> std::io::Result<Option<Vec<u8>>> {
921        let mut start = self.buf_pos;
922        let mut scan = self.buf_pos;
923
924        loop {
925            // Scan completed lines for the terminator.
926            while let Some(rel) = memchr::memchr(b'\n', &self.buf[scan..]) {
927                let nl = scan + rel;
928                let line = &self.buf[scan..=nl];
929                if line == b"\\.\n" || line == b"\\.\r\n" {
930                    self.in_copy_data = false;
931                    let result = self.buf[start..=nl].to_vec();
932                    self.buf_pos = nl + 1;
933                    return Ok(Some(result));
934                }
935                scan = nl + 1;
936            }
937
938            let (removed, got_more) = self.grow_buffer(start)?;
939            start -= removed;
940            scan -= removed;
941            if !got_more {
942                self.in_copy_data = false;
943                if start >= self.buf.len() {
944                    return Ok(None);
945                }
946                let result = self.buf[start..].to_vec();
947                self.buf_pos = self.buf.len();
948                return Ok(Some(result));
949            }
950        }
951    }
952
953    /// Stream the input as [`ParserEvent`]s with bounded memory.
954    ///
955    /// Ordinary DDL/control statements are buffered whole (they are small) and
956    /// delivered as [`ParserEvent::Statement`]. A multi-row INSERT is delivered
957    /// as its header plus one [`ParserEvent::InsertRow`] per tuple, and a COPY
958    /// block as [`ParserEvent::CopyStart`] / [`ParserEvent::CopyRow`] per line /
959    /// [`ParserEvent::CopyEnd`] — the whole multi-row block is never buffered at
960    /// once. The callback must consume each borrowed slice before returning.
961    ///
962    /// Unlike [`read_statement`](Self::read_statement) (kept for compatibility),
963    /// data statements are not routed through it: their rows are streamed.
964    pub fn visit_events<F>(&mut self, mut on_event: F) -> anyhow::Result<()>
965    where
966        F: FnMut(ParserEvent<'_>) -> anyhow::Result<RowFlow>,
967    {
968        loop {
969            // Ensure at least one byte at/after buf_pos, or stop at EOF.
970            while self.buf_pos >= self.buf.len() {
971                let (removed, more) = self.grow_buffer(self.buf_pos)?;
972                self.buf_pos -= removed;
973                if !more {
974                    return Ok(());
975                }
976            }
977
978            if self.peek_is_insert()? {
979                if self.visit_insert_stmt(&mut on_event)? == RowFlow::Stop {
980                    return Ok(());
981                }
982                continue;
983            }
984
985            // Non-INSERT: reuse read_statement to consume one DDL/control or
986            // COPY header statement (small). COPY data blocks are then streamed
987            // line-by-line rather than buffered whole.
988            let stmt = match self.read_statement()? {
989                Some(s) => s,
990                None => return Ok(()),
991            };
992            if self.in_copy_data {
993                self.in_copy_data = false;
994                if on_event(ParserEvent::CopyStart(&stmt))? == RowFlow::Stop {
995                    return Ok(());
996                }
997                if self.visit_copy_data(&mut on_event)? == RowFlow::Stop {
998                    return Ok(());
999                }
1000            } else if on_event(ParserEvent::Statement(&stmt))? == RowFlow::Stop {
1001                return Ok(());
1002            }
1003        }
1004    }
1005
1006    /// Peek whether the next statement (after leading comments/whitespace) is an
1007    /// `INSERT INTO`/`INSERT ONLY`, growing the buffer just enough to decide.
1008    fn peek_is_insert(&mut self) -> anyhow::Result<bool> {
1009        loop {
1010            let stripped = strip_leading_comments_and_whitespace(&self.buf[self.buf_pos..]);
1011            if stripped.len() >= 11 {
1012                return Ok(starts_with_insert(stripped));
1013            }
1014            if self.buf.len() - self.buf_pos > self.limits.max_header {
1015                anyhow::bail!(
1016                    "statement header exceeds max_header ({} bytes) at input offset {}",
1017                    self.limits.max_header,
1018                    self.base + self.buf_pos as u64
1019                );
1020            }
1021            let (removed, more) = self.grow_buffer(self.buf_pos)?;
1022            self.buf_pos -= removed;
1023            if !more {
1024                let stripped = strip_leading_comments_and_whitespace(&self.buf[self.buf_pos..]);
1025                return Ok(starts_with_insert(stripped));
1026            }
1027        }
1028    }
1029
1030    /// Stream one INSERT statement's tuples as [`ParserEvent::InsertRow`]s.
1031    fn visit_insert_stmt<F>(&mut self, on_event: &mut F) -> anyhow::Result<RowFlow>
1032    where
1033        F: FnMut(ParserEvent<'_>) -> anyhow::Result<RowFlow>,
1034    {
1035        // Locate the VALUES keyword, buffering only the header (bounded).
1036        let (header, values_abs) = loop {
1037            let stripped_len =
1038                strip_leading_comments_and_whitespace(&self.buf[self.buf_pos..]).len();
1039            let start = self.buf.len() - stripped_len;
1040            if let Some(vp) = mysql_insert::find_values_keyword_pos(&self.buf[start..]) {
1041                let values_abs = start + vp;
1042                break (self.buf[start..values_abs].to_vec(), values_abs);
1043            }
1044            if self.buf.len() - self.buf_pos > self.limits.max_header {
1045                anyhow::bail!(
1046                    "INSERT header exceeds max_header ({} bytes) at input offset {}",
1047                    self.limits.max_header,
1048                    self.base + self.buf_pos as u64
1049                );
1050            }
1051            let (removed, more) = self.grow_buffer(self.buf_pos)?;
1052            self.buf_pos -= removed;
1053            if !more {
1054                // No VALUES keyword (truncated / not a value INSERT): emit the
1055                // remaining bytes as an opaque statement so nothing is lost.
1056                let flow = on_event(ParserEvent::Statement(&self.buf[self.buf_pos..]))?;
1057                self.buf_pos = self.buf.len();
1058                return Ok(flow);
1059            }
1060        };
1061
1062        let mut cur = values_abs;
1063        let mut first = true;
1064        let mut skipping = false;
1065
1066        loop {
1067            // Skip inter-tuple whitespace and commas.
1068            loop {
1069                while cur < self.buf.len()
1070                    && matches!(self.buf[cur], b' ' | b'\t' | b'\n' | b'\r' | b',')
1071                {
1072                    cur += 1;
1073                }
1074                if cur < self.buf.len() {
1075                    break;
1076                }
1077                let (removed, more) = self.grow_buffer(cur)?;
1078                cur -= removed;
1079                if !more {
1080                    break;
1081                }
1082            }
1083
1084            if cur >= self.buf.len() {
1085                self.buf_pos = self.buf.len();
1086                return Ok(RowFlow::Continue);
1087            }
1088            match self.buf[cur] {
1089                b';' => {
1090                    self.buf_pos = cur + 1;
1091                    return Ok(RowFlow::Continue);
1092                }
1093                b'(' => {}
1094                // Anything else (e.g. an MSSQL GO batch line) ends the INSERT;
1095                // leave it for the next statement.
1096                _ => {
1097                    self.buf_pos = cur;
1098                    return Ok(RowFlow::Continue);
1099                }
1100            }
1101
1102            // Scan exactly one tuple, growing until it is complete or EOF.
1103            let (tuple_end, complete) = loop {
1104                if self.buf.len() - cur > self.limits.max_row {
1105                    anyhow::bail!(
1106                        "INSERT row exceeds max_row ({} bytes) at input offset {}",
1107                        self.limits.max_row,
1108                        self.base + cur as u64
1109                    );
1110                }
1111                match mysql_insert::scan_insert_tuple(&self.buf[cur..], self.dialect) {
1112                    Some((len, true)) => break (cur + len, true),
1113                    Some(_) => {
1114                        let (removed, more) = self.grow_buffer(cur)?;
1115                        cur -= removed;
1116                        if !more {
1117                            break (self.buf.len(), false);
1118                        }
1119                    }
1120                    None => {
1121                        self.buf_pos = cur;
1122                        return Ok(RowFlow::Continue);
1123                    }
1124                }
1125            };
1126
1127            if skipping {
1128                cur = tuple_end;
1129            } else {
1130                let flow = on_event(ParserEvent::InsertRow {
1131                    header: &header,
1132                    row: &self.buf[cur..tuple_end],
1133                    first_in_statement: first,
1134                })?;
1135                first = false;
1136                match flow {
1137                    RowFlow::Continue => cur = tuple_end,
1138                    RowFlow::SkipStatement => {
1139                        skipping = true;
1140                        cur = tuple_end;
1141                    }
1142                    RowFlow::Stop => {
1143                        self.buf_pos = tuple_end;
1144                        return Ok(RowFlow::Stop);
1145                    }
1146                }
1147            }
1148
1149            if !complete {
1150                self.buf_pos = self.buf.len();
1151                return Ok(RowFlow::Continue);
1152            }
1153        }
1154    }
1155
1156    /// Stream a COPY data block (positioned just past the header's `;`) as
1157    /// [`ParserEvent::CopyRow`]s followed by [`ParserEvent::CopyEnd`].
1158    fn visit_copy_data<F>(&mut self, on_event: &mut F) -> anyhow::Result<RowFlow>
1159    where
1160        F: FnMut(ParserEvent<'_>) -> anyhow::Result<RowFlow>,
1161    {
1162        // Consume the line terminator that ends the `COPY ... FROM stdin;`
1163        // header line (read_statement stopped at the `;`), so the first emitted
1164        // CopyRow is a real data line rather than a phantom empty one.
1165        for &want in b"\r\n" {
1166            while self.buf_pos >= self.buf.len() {
1167                let (removed, more) = self.grow_buffer(self.buf_pos)?;
1168                self.buf_pos -= removed;
1169                if !more {
1170                    return Ok(RowFlow::Continue);
1171                }
1172            }
1173            if self.buf[self.buf_pos] == want {
1174                self.buf_pos += 1;
1175            }
1176        }
1177
1178        let mut ls = self.buf_pos;
1179        let mut skipping = false;
1180
1181        loop {
1182            let nl = loop {
1183                if let Some(rel) = memchr::memchr(b'\n', &self.buf[ls..]) {
1184                    break Some(ls + rel);
1185                }
1186                if self.buf.len() - ls > self.limits.max_row {
1187                    anyhow::bail!(
1188                        "COPY line exceeds max_row ({} bytes) at input offset {}",
1189                        self.limits.max_row,
1190                        self.base + ls as u64
1191                    );
1192                }
1193                let (removed, more) = self.grow_buffer(ls)?;
1194                ls -= removed;
1195                if !more {
1196                    break None;
1197                }
1198            };
1199
1200            if nl.is_none() && ls >= self.buf.len() {
1201                // EOF with no trailing data.
1202                self.buf_pos = self.buf.len();
1203                return Ok(RowFlow::Continue);
1204            }
1205
1206            let line_end = nl.unwrap_or(self.buf.len());
1207            let line = &self.buf[ls..line_end];
1208            let check: &[u8] = if line.last() == Some(&b'\r') {
1209                &line[..line.len() - 1]
1210            } else {
1211                line
1212            };
1213
1214            if check == b"\\." {
1215                let flow = on_event(ParserEvent::CopyEnd)?;
1216                self.buf_pos = nl.map(|n| n + 1).unwrap_or(self.buf.len());
1217                return Ok(flow);
1218            }
1219
1220            if !skipping {
1221                match on_event(ParserEvent::CopyRow(line))? {
1222                    RowFlow::Continue => {}
1223                    RowFlow::SkipStatement => skipping = true,
1224                    RowFlow::Stop => {
1225                        self.buf_pos = nl.map(|n| n + 1).unwrap_or(self.buf.len());
1226                        return Ok(RowFlow::Stop);
1227                    }
1228                }
1229            }
1230
1231            match nl {
1232                Some(n) => ls = n + 1,
1233                None => {
1234                    self.buf_pos = self.buf.len();
1235                    return Ok(RowFlow::Continue);
1236                }
1237            }
1238        }
1239    }
1240
1241    /// Read MSSQL statement with GO batch separator support.
1242    /// GO is a batch separator that appears on its own line; `;` also
1243    /// terminates. Uses the same `buf` + cursor model as [`read_statement`] so
1244    /// tokens can't straddle a chunk boundary and scanning stays O(n).
1245    fn read_statement_mssql(&mut self) -> std::io::Result<Option<Vec<u8>>> {
1246        let mut start = self.buf_pos;
1247        let mut i = self.buf_pos;
1248        let mut line_start = self.buf_pos;
1249
1250        let mut inside_single_quote = false;
1251        let mut inside_bracket_quote = false;
1252        let mut in_line_comment = false;
1253        let mut in_block_comment = false;
1254        let mut at_eof = false;
1255
1256        loop {
1257            'scan: while i < self.buf.len() {
1258                let b = self.buf[i];
1259
1260                if in_block_comment {
1261                    if b == b'*' {
1262                        match self.peek2(i, b'/', at_eof) {
1263                            Peek2::Hit => {
1264                                in_block_comment = false;
1265                                i += 2;
1266                                continue;
1267                            }
1268                            Peek2::Miss => {
1269                                i += 1;
1270                                continue;
1271                            }
1272                            Peek2::NeedMore => break 'scan,
1273                        }
1274                    }
1275                    i += 1;
1276                    continue;
1277                }
1278
1279                if in_line_comment {
1280                    if b == b'\n' {
1281                        in_line_comment = false;
1282                        line_start = i + 1;
1283                    }
1284                    i += 1;
1285                    continue;
1286                }
1287
1288                if inside_bracket_quote {
1289                    if b == b']' {
1290                        match self.peek2(i, b']', at_eof) {
1291                            // Escaped ]] stays inside the identifier (bug #8)
1292                            Peek2::Hit => {
1293                                i += 2;
1294                                continue;
1295                            }
1296                            Peek2::Miss => {
1297                                inside_bracket_quote = false;
1298                                i += 1;
1299                                continue;
1300                            }
1301                            Peek2::NeedMore => break 'scan,
1302                        }
1303                    }
1304                    i += 1;
1305                    continue;
1306                }
1307
1308                if inside_single_quote {
1309                    // Fast-skip to the closing quote (MSSQL has no `\` escapes).
1310                    match memchr::memchr(b'\'', &self.buf[i..]) {
1311                        Some(0) => inside_single_quote = false,
1312                        Some(off) => {
1313                            i += off;
1314                            continue;
1315                        }
1316                        None if at_eof => {
1317                            i = self.buf.len();
1318                            continue;
1319                        }
1320                        None => break 'scan,
1321                    }
1322                    i += 1;
1323                    continue;
1324                }
1325
1326                // Outside strings/comments.
1327                if b == b'-' {
1328                    match self.peek2(i, b'-', at_eof) {
1329                        Peek2::Hit => {
1330                            in_line_comment = true;
1331                            i += 2;
1332                            continue;
1333                        }
1334                        Peek2::Miss => {
1335                            i += 1;
1336                            continue;
1337                        }
1338                        Peek2::NeedMore => break 'scan,
1339                    }
1340                }
1341                if b == b'/' {
1342                    match self.peek2(i, b'*', at_eof) {
1343                        Peek2::Hit => {
1344                            in_block_comment = true;
1345                            i += 2;
1346                            continue;
1347                        }
1348                        Peek2::Miss => {
1349                            i += 1;
1350                            continue;
1351                        }
1352                        Peek2::NeedMore => break 'scan,
1353                    }
1354                }
1355                if b == b'\'' {
1356                    inside_single_quote = true;
1357                    i += 1;
1358                    continue;
1359                }
1360                if b == b'[' {
1361                    inside_bracket_quote = true;
1362                    i += 1;
1363                    continue;
1364                }
1365                if b == b';' {
1366                    let result = self.buf[start..=i].to_vec();
1367                    self.buf_pos = i + 1;
1368                    return Ok(Some(result));
1369                }
1370                if b == b'\n' {
1371                    if is_go_line(&self.buf[line_start..=i]) {
1372                        // Trim trailing whitespace before the GO line.
1373                        let mut stmt_end = line_start;
1374                        while stmt_end > start
1375                            && matches!(self.buf[stmt_end - 1], b'\n' | b'\r' | b' ' | b'\t')
1376                        {
1377                            stmt_end -= 1;
1378                        }
1379                        self.buf_pos = i + 1;
1380                        if stmt_end > start {
1381                            return Ok(Some(self.buf[start..stmt_end].to_vec()));
1382                        }
1383                        // Empty batch: start a new statement after the GO line.
1384                        start = i + 1;
1385                        line_start = i + 1;
1386                        i += 1;
1387                        continue;
1388                    }
1389                    line_start = i + 1;
1390                    i += 1;
1391                    continue;
1392                }
1393
1394                i += 1;
1395            }
1396
1397            if at_eof {
1398                if start >= self.buf.len() {
1399                    return Ok(None);
1400                }
1401                // Handle a trailing GO with no final newline (bug #12).
1402                if is_go_line(&self.buf[line_start..]) {
1403                    let mut stmt_end = line_start;
1404                    while stmt_end > start
1405                        && matches!(self.buf[stmt_end - 1], b'\n' | b'\r' | b' ' | b'\t')
1406                    {
1407                        stmt_end -= 1;
1408                    }
1409                    self.buf_pos = self.buf.len();
1410                    if stmt_end > start {
1411                        return Ok(Some(self.buf[start..stmt_end].to_vec()));
1412                    }
1413                    return Ok(None);
1414                }
1415                let result = self.buf[start..].to_vec();
1416                self.buf_pos = self.buf.len();
1417                return Ok(Some(result));
1418            }
1419
1420            let (removed, got_more) = self.grow_buffer(start)?;
1421            start -= removed;
1422            i -= removed;
1423            line_start -= removed;
1424            if !got_more {
1425                at_eof = true;
1426            }
1427        }
1428    }
1429
1430    #[allow(dead_code)]
1431    pub fn parse_statement(stmt: &[u8]) -> (StatementType, String) {
1432        Self::parse_statement_with_dialect(stmt, SqlDialect::MySql)
1433    }
1434
1435    /// Parse a statement with dialect-specific handling
1436    pub fn parse_statement_with_dialect(
1437        stmt: &[u8],
1438        dialect: SqlDialect,
1439    ) -> (StatementType, String) {
1440        // Strip leading comments (e.g., pg_dump adds -- comments before statements)
1441        let stmt = strip_leading_comments_and_whitespace(stmt);
1442
1443        if stmt.len() < 4 {
1444            return (StatementType::Unknown, String::new());
1445        }
1446
1447        // Use stack-allocated buffer to avoid heap allocation in hot path
1448        let mut upper_prefix = [0u8; 25];
1449        let prefix_len = stmt.len().min(25);
1450        for (i, &b) in stmt.iter().take(prefix_len).enumerate() {
1451            upper_prefix[i] = b.to_ascii_uppercase();
1452        }
1453        let upper_prefix = &upper_prefix[..prefix_len];
1454
1455        // PostgreSQL COPY statement
1456        if upper_prefix.starts_with(b"COPY ") {
1457            if let Some(caps) = COPY_RE.captures(stmt) {
1458                if let Some(m) = caps.get(1) {
1459                    let name = String::from_utf8_lossy(m.as_bytes()).into_owned();
1460                    // Handle schema.table - extract just the table name
1461                    let table_name = name.split('.').next_back().unwrap_or(&name).to_string();
1462                    return (StatementType::Copy, table_name);
1463                }
1464            }
1465        }
1466
1467        if upper_prefix.starts_with(b"CREATE TABLE") {
1468            // Try fast extraction first
1469            if let Some(name) = extract_table_name_flexible(stmt, 12, dialect) {
1470                return (StatementType::CreateTable, name);
1471            }
1472            // Fall back to flexible regex
1473            if let Some(caps) = CREATE_TABLE_FLEXIBLE_RE.captures(stmt) {
1474                if let Some(m) = caps.get(1) {
1475                    return (
1476                        StatementType::CreateTable,
1477                        String::from_utf8_lossy(m.as_bytes()).into_owned(),
1478                    );
1479                }
1480            }
1481        }
1482
1483        if upper_prefix.starts_with(b"INSERT INTO") || upper_prefix.starts_with(b"INSERT ONLY") {
1484            if let Some(name) = extract_table_name_flexible(stmt, 11, dialect) {
1485                return (StatementType::Insert, name);
1486            }
1487            if let Some(caps) = INSERT_FLEXIBLE_RE.captures(stmt) {
1488                if let Some(m) = caps.get(1) {
1489                    return (
1490                        StatementType::Insert,
1491                        String::from_utf8_lossy(m.as_bytes()).into_owned(),
1492                    );
1493                }
1494            }
1495        }
1496
1497        if upper_prefix.starts_with(b"CREATE INDEX")
1498            || upper_prefix.starts_with(b"CREATE UNIQUE")
1499            || upper_prefix.starts_with(b"CREATE CLUSTERED")
1500            || upper_prefix.starts_with(b"CREATE NONCLUSTER")
1501        {
1502            // For MSSQL, try the bracket-aware regex first
1503            if dialect == SqlDialect::Mssql {
1504                if let Some(caps) = CREATE_INDEX_MSSQL_RE.captures(stmt) {
1505                    if let Some(m) = caps.get(1) {
1506                        return (
1507                            StatementType::CreateIndex,
1508                            String::from_utf8_lossy(m.as_bytes()).into_owned(),
1509                        );
1510                    }
1511                }
1512            }
1513            // Fall back to generic regex for MySQL/PostgreSQL/SQLite
1514            if let Some(caps) = CREATE_INDEX_RE.captures(stmt) {
1515                if let Some(m) = caps.get(1) {
1516                    let name = String::from_utf8_lossy(m.as_bytes());
1517                    // Strip schema qualifier (public.users -> users) so indexes
1518                    // group under the same key as their CREATE TABLE, which also
1519                    // strips the schema.
1520                    let table_name = name.split('.').next_back().unwrap_or(&name).to_string();
1521                    return (StatementType::CreateIndex, table_name);
1522                }
1523            }
1524        }
1525
1526        if upper_prefix.starts_with(b"ALTER TABLE") {
1527            if let Some(name) = extract_table_name_flexible(stmt, 11, dialect) {
1528                return (StatementType::AlterTable, name);
1529            }
1530            if let Some(caps) = ALTER_TABLE_RE.captures(stmt) {
1531                if let Some(m) = caps.get(1) {
1532                    return (
1533                        StatementType::AlterTable,
1534                        String::from_utf8_lossy(m.as_bytes()).into_owned(),
1535                    );
1536                }
1537            }
1538        }
1539
1540        if upper_prefix.starts_with(b"DROP TABLE") {
1541            if let Some(name) = extract_table_name_flexible(stmt, 10, dialect) {
1542                return (StatementType::DropTable, name);
1543            }
1544            if let Some(caps) = DROP_TABLE_RE.captures(stmt) {
1545                if let Some(m) = caps.get(1) {
1546                    return (
1547                        StatementType::DropTable,
1548                        String::from_utf8_lossy(m.as_bytes()).into_owned(),
1549                    );
1550                }
1551            }
1552        }
1553
1554        // MSSQL BULK INSERT - treat as Insert statement type
1555        if upper_prefix.starts_with(b"BULK INSERT") {
1556            if let Some(name) = extract_table_name_flexible(stmt, 11, dialect) {
1557                return (StatementType::Insert, name);
1558            }
1559        }
1560
1561        (StatementType::Unknown, String::new())
1562    }
1563}
1564
1565#[inline]
1566fn trim_ascii_start(data: &[u8]) -> &[u8] {
1567    let start = data
1568        .iter()
1569        .position(|&b| !matches!(b, b' ' | b'\t' | b'\n' | b'\r'))
1570        .unwrap_or(data.len());
1571    &data[start..]
1572}
1573
1574/// Strip leading whitespace and SQL line comments (`-- ...`) from a statement.
1575/// This makes parsing robust to pg_dump-style comment blocks before statements.
1576pub(crate) fn strip_leading_comments_and_whitespace(mut data: &[u8]) -> &[u8] {
1577    loop {
1578        // First trim leading ASCII whitespace
1579        data = trim_ascii_start(data);
1580
1581        // Handle -- line comments
1582        if data.len() >= 2 && data[0] == b'-' && data[1] == b'-' {
1583            // Skip until end of line
1584            if let Some(pos) = data.iter().position(|&b| b == b'\n') {
1585                data = &data[pos + 1..];
1586                continue;
1587            } else {
1588                // Comment runs to EOF, nothing left
1589                return &[];
1590            }
1591        }
1592
1593        // Handle /* */ block comments (including MySQL conditional comments)
1594        if data.len() >= 2 && data[0] == b'/' && data[1] == b'*' {
1595            // Find the closing */
1596            let mut i = 2;
1597            let mut depth = 1;
1598            while i < data.len() - 1 && depth > 0 {
1599                if data[i] == b'*' && data[i + 1] == b'/' {
1600                    depth -= 1;
1601                    i += 2;
1602                } else if data[i] == b'/' && data[i + 1] == b'*' {
1603                    depth += 1;
1604                    i += 2;
1605                } else {
1606                    i += 1;
1607                }
1608            }
1609            if depth == 0 {
1610                data = &data[i..];
1611                continue;
1612            } else {
1613                // Unclosed comment runs to EOF
1614                return &[];
1615            }
1616        }
1617
1618        // Handle # line comments (MySQL)
1619        if !data.is_empty() && data[0] == b'#' {
1620            if let Some(pos) = data.iter().position(|&b| b == b'\n') {
1621                data = &data[pos + 1..];
1622                continue;
1623            } else {
1624                return &[];
1625            }
1626        }
1627
1628        break;
1629    }
1630
1631    data
1632}
1633
1634/// Extract table name with support for:
1635/// - IF NOT EXISTS
1636/// - ONLY (PostgreSQL)
1637/// - Schema-qualified names (schema.table)
1638/// - Both backtick and double-quote quoting
1639#[inline]
1640pub(crate) fn extract_table_name_flexible(
1641    stmt: &[u8],
1642    offset: usize,
1643    dialect: SqlDialect,
1644) -> Option<String> {
1645    let mut i = offset;
1646
1647    // Skip whitespace
1648    while i < stmt.len() && is_whitespace(stmt[i]) {
1649        i += 1;
1650    }
1651
1652    if i >= stmt.len() {
1653        return None;
1654    }
1655
1656    // Check for IF NOT EXISTS or IF EXISTS (stack-allocated to avoid heap allocation)
1657    let mut upper_check = [0u8; 20];
1658    let check_len = (stmt.len() - i).min(20);
1659    for (idx, &b) in stmt[i..].iter().take(check_len).enumerate() {
1660        upper_check[idx] = b.to_ascii_uppercase();
1661    }
1662    let upper_slice = &upper_check[..check_len];
1663    if upper_slice.starts_with(b"IF NOT EXISTS") {
1664        i += 13; // Skip "IF NOT EXISTS"
1665        while i < stmt.len() && is_whitespace(stmt[i]) {
1666            i += 1;
1667        }
1668    } else if upper_slice.starts_with(b"IF EXISTS") {
1669        i += 9; // Skip "IF EXISTS"
1670        while i < stmt.len() && is_whitespace(stmt[i]) {
1671            i += 1;
1672        }
1673    }
1674
1675    // Check for ONLY (PostgreSQL) - reuse first 10 bytes or re-check if position changed
1676    let only_check = if i < stmt.len() {
1677        let mut buf = [0u8; 10];
1678        let len = (stmt.len() - i).min(10);
1679        for (idx, &b) in stmt[i..].iter().take(len).enumerate() {
1680            buf[idx] = b.to_ascii_uppercase();
1681        }
1682        (buf, len)
1683    } else {
1684        ([0u8; 10], 0)
1685    };
1686    let only_slice = &only_check.0[..only_check.1];
1687    if only_slice.starts_with(b"ONLY ") || only_slice.starts_with(b"ONLY\t") {
1688        i += 4;
1689        while i < stmt.len() && is_whitespace(stmt[i]) {
1690            i += 1;
1691        }
1692    }
1693
1694    if i >= stmt.len() {
1695        return None;
1696    }
1697
1698    // Read identifier (potentially schema-qualified)
1699    let mut parts: Vec<String> = Vec::new();
1700
1701    loop {
1702        // Determine quote character based on dialect
1703        let (quote_char, close_char) = match stmt.get(i) {
1704            Some(b'`') if dialect == SqlDialect::MySql => {
1705                i += 1;
1706                (Some(b'`'), b'`')
1707            }
1708            // Double quotes are the standard identifier quote for
1709            // Postgres/SQLite/MSSQL, and accepted for MySQL too (less common).
1710            Some(b'"') => {
1711                i += 1;
1712                (Some(b'"'), b'"')
1713            }
1714            Some(b'[') if dialect == SqlDialect::Mssql => {
1715                // MSSQL square bracket quoting
1716                i += 1;
1717                (Some(b'['), b']')
1718            }
1719            _ => (None, 0),
1720        };
1721
1722        let start = i;
1723
1724        while i < stmt.len() {
1725            let b = stmt[i];
1726            if quote_char.is_some() {
1727                if b == close_char {
1728                    // For MSSQL, check for escaped ]]
1729                    if dialect == SqlDialect::Mssql
1730                        && close_char == b']'
1731                        && i + 1 < stmt.len()
1732                        && stmt[i + 1] == b']'
1733                    {
1734                        // Escaped bracket, skip both
1735                        i += 2;
1736                        continue;
1737                    }
1738                    let name = &stmt[start..i];
1739                    // For MSSQL, unescape ]] to ]
1740                    let name_str = if dialect == SqlDialect::Mssql {
1741                        String::from_utf8_lossy(name).replace("]]", "]")
1742                    } else {
1743                        String::from_utf8_lossy(name).into_owned()
1744                    };
1745                    parts.push(name_str);
1746                    i += 1; // Skip closing quote
1747                    break;
1748                }
1749            } else if is_whitespace(b) || b == b'(' || b == b';' || b == b',' || b == b'.' {
1750                if i > start {
1751                    let name = &stmt[start..i];
1752                    parts.push(String::from_utf8_lossy(name).into_owned());
1753                }
1754                break;
1755            }
1756            i += 1;
1757        }
1758
1759        // If at end of quoted name without finding close quote, bail
1760        if quote_char.is_some() && i <= start {
1761            break;
1762        }
1763
1764        // Check for schema separator (.)
1765        while i < stmt.len() && is_whitespace(stmt[i]) {
1766            i += 1;
1767        }
1768
1769        if i < stmt.len() && stmt[i] == b'.' {
1770            i += 1; // Skip the dot
1771            while i < stmt.len() && is_whitespace(stmt[i]) {
1772                i += 1;
1773            }
1774            // Continue to read the next identifier (table name)
1775        } else {
1776            break;
1777        }
1778    }
1779
1780    // Return the last part (table name), not the schema
1781    parts.pop()
1782}
1783
1784#[inline]
1785fn is_whitespace(b: u8) -> bool {
1786    matches!(b, b' ' | b'\t' | b'\n' | b'\r')
1787}
1788
1789/// True if `s` begins with an `INSERT INTO`/`INSERT ONLY` value statement (the
1790/// forms that carry a `VALUES` list). `BULK INSERT` and other keywords are
1791/// intentionally excluded so [`Parser::visit_events`] only enters tuple-
1792/// streaming mode for statements it can actually stream.
1793#[inline]
1794fn starts_with_insert(s: &[u8]) -> bool {
1795    s.len() >= 11
1796        && (s[..11].eq_ignore_ascii_case(b"INSERT INTO")
1797            || s[..11].eq_ignore_ascii_case(b"INSERT ONLY"))
1798}
1799
1800/// A dollar-quote tag is either empty (`$$`) or an identifier
1801/// (`[A-Za-z_][A-Za-z0-9_]*`), matching PostgreSQL's rules.
1802#[inline]
1803fn is_valid_dollar_tag(tag: &[u8]) -> bool {
1804    match tag.first() {
1805        None => true,
1806        Some(&first) if first.is_ascii_alphabetic() || first == b'_' => tag[1..]
1807            .iter()
1808            .all(|&c| c.is_ascii_alphanumeric() || c == b'_'),
1809        _ => false,
1810    }
1811}
1812
1813pub fn determine_buffer_size(file_size: u64) -> usize {
1814    if file_size > 1024 * 1024 * 1024 {
1815        MEDIUM_BUFFER_SIZE
1816    } else {
1817        SMALL_BUFFER_SIZE
1818    }
1819}