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, Hash, 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 complete table reference before `(`.
354static CREATE_INDEX_MSSQL_RE: Lazy<Regex> = Lazy::new(|| {
355    Regex::new(
356        r"(?i)ON\s+((?:(?:\[(?:[^\]]|\]\])*\]|[^\s.()]+)\s*\.\s*)*(?:\[(?:[^\]]|\]\])*\]|[^\s.()]+))",
357    )
358    .unwrap()
359});
360
361static ALTER_TABLE_RE: Lazy<Regex> =
362    Lazy::new(|| Regex::new(r"(?i)ALTER\s+TABLE\s+`?([^\s`;]+)`?").unwrap());
363
364static DROP_TABLE_RE: Lazy<Regex> = Lazy::new(|| {
365    Regex::new(r#"(?i)DROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?[`"]?([^\s`"`;]+)[`"]?"#).unwrap()
366});
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/// Result of probing for a MySQL `DELIMITER` client command at a statement
400/// boundary. See [`Parser::scan_delimiter_command`].
401enum DelimiterScan {
402    /// The bytes at the boundary are not a `DELIMITER` command.
403    NotDelimiter,
404    /// A complete `DELIMITER <token>` line: switch the terminator to
405    /// `new_delim` and resume scanning the real statement at `next`.
406    Consumed { new_delim: Vec<u8>, next: usize },
407    /// The line is not fully buffered yet: grow the buffer and retry.
408    NeedMore,
409}
410
411/// Control-flow signal returned by row/event visitors.
412///
413/// Lives in the parser layer (rather than a consumer module) so the streaming
414/// row visitors ([`crate::parser::mysql_insert::visit_insert_rows_with`],
415/// [`crate::parser::postgres_copy::visit_postgres_copy_rows_with`]) and
416/// [`Parser::visit_events`] can all speak the same vocabulary. Re-exported from
417/// `crate::transform_common` for the sample/shard consumers.
418#[derive(Debug, Clone, Copy, PartialEq, Eq)]
419pub enum RowFlow {
420    /// Keep iterating.
421    Continue,
422    /// Skip the remaining rows of the current INSERT/COPY statement, then
423    /// resume with the next statement.
424    SkipStatement,
425    /// Stop the walk entirely.
426    Stop,
427}
428
429/// A single streaming event emitted by [`Parser::visit_events`].
430///
431/// Data rows are treated as stream boundaries: a multi-row INSERT is delivered
432/// as its shared header plus one [`ParserEvent::InsertRow`] per tuple, and a
433/// COPY block as [`ParserEvent::CopyStart`] / one [`ParserEvent::CopyRow`] per
434/// line / [`ParserEvent::CopyEnd`] — never buffering the whole block. All byte
435/// slices borrow from the parser's internal buffer (or, for `InsertRow.header`,
436/// a small owned copy of the header) and are only valid until the callback
437/// returns.
438pub enum ParserEvent<'a> {
439    /// A complete non-data statement (DDL / control), including its terminator.
440    Statement(&'a [u8]),
441    /// One INSERT `(...)` value tuple. `header` is the statement text up to and
442    /// including the `VALUES` keyword (so the column list can be recovered);
443    /// `first_in_statement` is true for the first row of each INSERT so callers
444    /// can rebuild per-statement column context exactly once.
445    InsertRow {
446        header: &'a [u8],
447        row: &'a [u8],
448        first_in_statement: bool,
449    },
450    /// The `COPY ... FROM stdin;` header line that opens a COPY data block.
451    CopyStart(&'a [u8]),
452    /// One raw COPY data line (newline stripped; a trailing `\r`, if any, is
453    /// left for the consumer to strip so it matches the collecting parser).
454    CopyRow(&'a [u8]),
455    /// The `\.` terminator that closes a COPY data block.
456    CopyEnd,
457}
458
459/// Configurable safety caps on how much a single buffered unit may grow before
460/// [`Parser::visit_events`] reports an error (rather than silently truncating
461/// or buffering without bound). Defaults are generous; they exist to turn a
462/// pathological/corrupt input into a diagnosable error instead of an OOM.
463#[derive(Debug, Clone, Copy)]
464pub struct ParserLimits {
465    /// Max bytes for one non-data statement (DDL/control).
466    pub max_ddl: usize,
467    /// Max bytes for an INSERT/COPY header before the first row.
468    pub max_header: usize,
469    /// Max bytes for a single INSERT tuple or COPY line.
470    pub max_row: usize,
471}
472
473impl Default for ParserLimits {
474    fn default() -> Self {
475        Self {
476            max_ddl: 256 * 1024 * 1024,
477            max_header: 64 * 1024 * 1024,
478            max_row: 256 * 1024 * 1024,
479        }
480    }
481}
482
483/// Longest statement terminator a `DELIMITER` command may set, stored inline.
484/// Real delimiters are 1–2 bytes (`;`, `;;`, `//`, `$$`); a longer one is
485/// truncated to this cap, which no realistic dump reaches.
486const MAX_DELIMITER_LEN: usize = 8;
487
488pub struct Parser<R: Read> {
489    reader: BufReader<R>,
490    dialect: SqlDialect,
491    /// For PostgreSQL: true when reading COPY data block
492    in_copy_data: bool,
493    /// Accumulated, not-yet-returned input. The scanners read whole `fill_buf`
494    /// chunks into `buf` and scan it with an index cursor, so a multi-byte
495    /// token (`--`, `/* */`, `$tag$`, `]]`) can never straddle an internal
496    /// buffer boundary. `buf_pos` is the start of the next statement to return;
497    /// bytes before it are already-returned and are dropped on the next refill
498    /// (never per-statement) so scanning stays O(n) rather than O(n²).
499    buf: Vec<u8>,
500    buf_pos: usize,
501    /// Current statement terminator, stored inline so constructing a `Parser`
502    /// never heap-allocates for the common `;` case. Defaults to `;`, but a
503    /// MySQL `DELIMITER` client command (as emitted by `mysqldump --routines`
504    /// around stored procedure/function/trigger bodies) switches it to e.g.
505    /// `;;` so the `;`-terminated statements inside a `BEGIN … END` body are not
506    /// split apart. Persists across `read_statement` calls for the same stream.
507    /// The active delimiter is `current_delimiter[..current_delimiter_len]`.
508    current_delimiter: [u8; MAX_DELIMITER_LEN],
509    current_delimiter_len: usize,
510    /// Number of bytes dropped off the front of `buf` so far, so an absolute
511    /// input offset can be reported in [`Parser::visit_events`] diagnostics.
512    base: u64,
513    /// High-water mark of `buf.len()`, so tests can assert the streaming walker
514    /// keeps its working set bounded.
515    peak_buffered: usize,
516    /// Safety caps for [`Parser::visit_events`].
517    limits: ParserLimits,
518}
519
520impl<R: Read> Parser<R> {
521    #[allow(dead_code)]
522    pub fn new(reader: R, buffer_size: usize) -> Self {
523        Self::with_dialect(reader, buffer_size, SqlDialect::default())
524    }
525
526    pub fn with_dialect(reader: R, buffer_size: usize, dialect: SqlDialect) -> Self {
527        Self {
528            reader: BufReader::with_capacity(buffer_size, reader),
529            dialect,
530            in_copy_data: false,
531            buf: Vec::new(),
532            buf_pos: 0,
533            current_delimiter: {
534                let mut d = [0u8; MAX_DELIMITER_LEN];
535                d[0] = b';';
536                d
537            },
538            current_delimiter_len: 1,
539            base: 0,
540            peak_buffered: 0,
541            limits: ParserLimits::default(),
542        }
543    }
544
545    /// Override the [`ParserLimits`] used by [`Parser::visit_events`].
546    #[allow(dead_code)]
547    pub fn with_limits(mut self, limits: ParserLimits) -> Self {
548        self.limits = limits;
549        self
550    }
551
552    /// Total bytes currently buffered in memory. Used by tests to assert the
553    /// event walker keeps its working set bounded even for huge INSERT/COPY
554    /// blocks.
555    pub fn buffered_len(&self) -> usize {
556        self.buf.len()
557    }
558
559    /// High-water mark of buffered bytes over this parser's lifetime. Used by
560    /// tests to assert [`Parser::visit_events`] never buffers a whole multi-row
561    /// INSERT/COPY block.
562    pub fn peak_buffered(&self) -> usize {
563        self.peak_buffered
564    }
565
566    /// True when the statement just returned by [`read_statement`](Self::read_statement)
567    /// was a `COPY ... FROM stdin;` header, meaning the *next* call returns that
568    /// block's data rather than a statement. Lets a caller pair a header with its
569    /// data block off the parser's own state instead of re-deriving the rule and
570    /// risking a desync on edge cases like `FROM STDIN WITH (FORMAT csv)`.
571    pub fn in_copy_data(&self) -> bool {
572        self.in_copy_data
573    }
574
575    /// Drop the already-returned prefix `buf[..keep_from]` and append the next
576    /// `fill_buf` chunk. Returns `(bytes_removed_from_front, got_more_data)`.
577    /// Callers subtract `bytes_removed_from_front` from their scan indices.
578    #[inline]
579    fn grow_buffer(&mut self, keep_from: usize) -> std::io::Result<(usize, bool)> {
580        if keep_from > 0 {
581            self.buf.drain(..keep_from);
582            self.base += keep_from as u64;
583        }
584        let chunk = self.reader.fill_buf()?;
585        if chunk.is_empty() {
586            return Ok((keep_from, false));
587        }
588        self.buf.extend_from_slice(chunk);
589        let n = chunk.len();
590        self.reader.consume(n);
591        self.peak_buffered = self.peak_buffered.max(self.buf.len());
592        Ok((keep_from, true))
593    }
594
595    /// Classify the byte after `i` against the second byte of a two-byte
596    /// token. Centralizes the boundary handling shared by every such token in
597    /// [`read_statement`](Self::read_statement) and `read_statement_mssql`.
598    #[inline(always)]
599    fn peek2(&self, i: usize, expected: u8, at_eof: bool) -> Peek2 {
600        match self.buf.get(i + 1) {
601            Some(&c) if c == expected => Peek2::Hit,
602            Some(_) => Peek2::Miss,
603            None if at_eof => Peek2::Miss,
604            None => Peek2::NeedMore,
605        }
606    }
607
608    /// Cheap guard for the `DELIMITER` pre-scan: `true` when the next statement
609    /// could begin a `DELIMITER` command, i.e. the first non-whitespace byte at
610    /// `buf_pos` is `D`/`d`, or the buffer ran out before a non-whitespace byte
611    /// was found (so the full scan must grow it to decide). `false` — the common
612    /// case — lets `read_statement` skip the pre-scan loop entirely.
613    #[inline]
614    fn upcoming_maybe_delimiter(&self) -> bool {
615        let mut p = self.buf_pos;
616        while p < self.buf.len() {
617            match self.buf[p] {
618                b' ' | b'\t' | b'\r' | b'\n' => p += 1,
619                b'D' | b'd' => return true,
620                _ => return false,
621            }
622        }
623        // Ran out of buffered bytes without deciding: let the full scan grow it.
624        true
625    }
626
627    /// Detect a MySQL `DELIMITER <token>` client command starting at `from`
628    /// (after leading whitespace). The command is line-terminated (not
629    /// terminated by the current delimiter) and is a mysql-client directive
630    /// with no SQL meaning, so it is consumed and not emitted as a statement.
631    fn scan_delimiter_command(&self, from: usize, at_eof: bool) -> DelimiterScan {
632        const KW: &[u8] = b"DELIMITER";
633
634        let mut p = from;
635        while p < self.buf.len() && matches!(self.buf[p], b' ' | b'\t' | b'\r' | b'\n') {
636            p += 1;
637        }
638        if self.buf.len() - p < KW.len() {
639            return if at_eof {
640                DelimiterScan::NotDelimiter
641            } else {
642                DelimiterScan::NeedMore
643            };
644        }
645        for (k, &kw) in KW.iter().enumerate() {
646            if self.buf[p + k].to_ascii_uppercase() != kw {
647                return DelimiterScan::NotDelimiter;
648            }
649        }
650        let mut q = p + KW.len();
651        // The keyword must be followed by horizontal whitespace, else it is an
652        // identifier that merely starts with "DELIMITER" (e.g. `DELIMITERS`).
653        match self.buf.get(q) {
654            Some(&c) if c == b' ' || c == b'\t' => {}
655            Some(_) => return DelimiterScan::NotDelimiter,
656            None if at_eof => return DelimiterScan::NotDelimiter,
657            None => return DelimiterScan::NeedMore,
658        }
659        while q < self.buf.len() && matches!(self.buf[q], b' ' | b'\t') {
660            q += 1;
661        }
662        let line_end = match memchr::memchr(b'\n', &self.buf[q..]) {
663            Some(off) => q + off,
664            None if at_eof => self.buf.len(),
665            None => return DelimiterScan::NeedMore,
666        };
667        // Trim trailing horizontal whitespace / CR from the delimiter token.
668        let mut end = line_end;
669        while end > q && matches!(self.buf[end - 1], b' ' | b'\t' | b'\r') {
670            end -= 1;
671        }
672        if end == q {
673            // `DELIMITER` with no argument: malformed. Leave it to normal
674            // parsing rather than swallowing the line.
675            return DelimiterScan::NotDelimiter;
676        }
677        let new_delim = self.buf[q..end].to_vec();
678        let next = if line_end < self.buf.len() {
679            line_end + 1
680        } else {
681            line_end
682        };
683        DelimiterScan::Consumed { new_delim, next }
684    }
685
686    pub fn read_statement(&mut self) -> std::io::Result<Option<Vec<u8>>> {
687        // If we're in PostgreSQL COPY data mode, read until we see the terminator
688        if self.in_copy_data {
689            return self.read_copy_data();
690        }
691
692        // For MSSQL, use line-based parsing to handle GO batch separator
693        if self.dialect == SqlDialect::Mssql {
694            return self.read_statement_mssql();
695        }
696
697        let is_mysql = self.dialect == SqlDialect::MySql;
698        let is_postgres = self.dialect == SqlDialect::Postgres;
699
700        // Scan `self.buf` from the current statement start with an index cursor.
701        // More data is appended by `grow_buffer` (which also drops already-
702        // returned statements), so a multi-byte token (`--`, `/* */`, `$tag$`)
703        // never straddles a chunk boundary: the scan waits for more bytes with
704        // its state (`i`, quote/comment flags) intact.
705        let mut start = self.buf_pos;
706        let mut i = self.buf_pos;
707
708        let mut inside_single_quote = false;
709        // The current single-quoted string is a PostgreSQL escape string
710        // (`E'…'`), inside which backslash is an escape character — so a
711        // backslash-escaped quote (`E'a\'b'`) does not end the string.
712        let mut in_escape_string = false;
713        let mut inside_double_quote = false;
714        let mut inside_backtick = false; // MySQL `identifier` quoting (bug #10)
715        let mut escaped = false;
716        let mut in_line_comment = false;
717        let mut in_block_comment = false; // /* ... */ (bug #5)
718        let mut in_dollar_quote = false;
719        let mut dollar_tag: Vec<u8> = Vec::new();
720        let mut at_eof = false;
721
722        // Consume any leading MySQL `DELIMITER` client commands before scanning
723        // the next real statement, so `;`-terminated statements inside a stored
724        // routine body are kept whole under a `;;` (or other) delimiter.
725        //
726        // Fast path: a `DELIMITER` command begins with `D`/`d` after optional
727        // leading whitespace. When that first byte is already buffered and is
728        // not `D`/`d`, there is no command here, so skip the full scan entirely
729        // — this keeps the per-statement cost off the parser's hot loop for the
730        // overwhelmingly common non-`DELIMITER` statement.
731        if is_mysql && self.upcoming_maybe_delimiter() {
732            loop {
733                match self.scan_delimiter_command(self.buf_pos, at_eof) {
734                    DelimiterScan::NotDelimiter => break,
735                    DelimiterScan::Consumed { new_delim, next } => {
736                        let n = new_delim.len().min(MAX_DELIMITER_LEN);
737                        self.current_delimiter[..n].copy_from_slice(&new_delim[..n]);
738                        self.current_delimiter_len = n;
739                        self.buf_pos = next;
740                        start = self.buf_pos;
741                        i = self.buf_pos;
742                    }
743                    DelimiterScan::NeedMore => {
744                        let (removed, more) = self.grow_buffer(self.buf_pos)?;
745                        self.buf_pos -= removed;
746                        start = self.buf_pos;
747                        i = self.buf_pos;
748                        if !more {
749                            at_eof = true;
750                        }
751                    }
752                }
753            }
754        }
755
756        // Lookup table of bytes that are significant outside strings/comments;
757        // everything else can be skipped in a tight loop.
758        let mut sig = [false; 256];
759        for &c in b";'\"-/" {
760            sig[c as usize] = true;
761        }
762        if is_mysql {
763            sig[b'`' as usize] = true;
764            sig[b'#' as usize] = true;
765        }
766        if is_postgres {
767            sig[b'$' as usize] = true;
768        }
769        // A custom multi-byte delimiter (from `DELIMITER`) may start with a byte
770        // the default table does not flag; make sure the scan stops on it. The
771        // delimiter can't change during this scan (only the pre-scan above sets
772        // it), so cache it in locals to keep the hot loop off the struct fields.
773        let delim0 = self.current_delimiter[0];
774        let delim_len = self.current_delimiter_len;
775        sig[delim0 as usize] = true;
776
777        loop {
778            'scan: while i < self.buf.len() {
779                let b = self.buf[i];
780
781                // Inside a /* */ block comment: only the closing */ ends it.
782                if in_block_comment {
783                    if b == b'*' {
784                        match self.peek2(i, b'/', at_eof) {
785                            Peek2::Hit => {
786                                in_block_comment = false;
787                                i += 2;
788                                continue;
789                            }
790                            Peek2::Miss => {
791                                i += 1;
792                                continue;
793                            }
794                            Peek2::NeedMore => break 'scan,
795                        }
796                    }
797                    i += 1;
798                    continue;
799                }
800
801                // Inside a -- or # line comment: consume until newline.
802                if in_line_comment {
803                    if b == b'\n' {
804                        in_line_comment = false;
805                    }
806                    i += 1;
807                    continue;
808                }
809
810                if escaped {
811                    escaped = false;
812                    i += 1;
813                    continue;
814                }
815
816                let inside_string = inside_single_quote
817                    || inside_double_quote
818                    || inside_backtick
819                    || in_dollar_quote;
820
821                // Fast path: inside a string/quoted region only the closing
822                // delimiter (and, for MySQL, a `\` escape) is significant, so
823                // memchr past the ordinary bytes. This is the hot loop for
824                // INSERT string data.
825                if inside_string {
826                    let rest = &self.buf[i..];
827                    let hit = if inside_single_quote {
828                        if is_mysql || (is_postgres && in_escape_string) {
829                            memchr::memchr2(b'\'', b'\\', rest)
830                        } else {
831                            memchr::memchr(b'\'', rest)
832                        }
833                    } else if inside_double_quote {
834                        if is_mysql {
835                            memchr::memchr2(b'"', b'\\', rest)
836                        } else {
837                            memchr::memchr(b'"', rest)
838                        }
839                    } else if inside_backtick {
840                        memchr::memchr(b'`', rest)
841                    } else {
842                        // in_dollar_quote: only `$` can start the closing tag
843                        memchr::memchr(b'$', rest)
844                    };
845                    match hit {
846                        Some(0) => {} // significant byte at i
847                        Some(off) => {
848                            i += off;
849                            continue;
850                        }
851                        None if at_eof => {
852                            i = self.buf.len();
853                            continue;
854                        }
855                        None => break 'scan,
856                    }
857                }
858
859                // Backslash escapes apply inside MySQL '…'/"…" literals and
860                // inside a PostgreSQL E'…' escape string (but never inside
861                // backtick identifiers or dollar quotes).
862                if b == b'\\'
863                    && ((is_mysql && (inside_single_quote || inside_double_quote))
864                        || (is_postgres && inside_single_quote && in_escape_string))
865                {
866                    escaped = true;
867                    i += 1;
868                    continue;
869                }
870
871                if !inside_string {
872                    // Fast path: skip runs of insignificant bytes outside any
873                    // string/comment with a tight table lookup.
874                    if !sig[b as usize] {
875                        let mut j = i + 1;
876                        while j < self.buf.len() && !sig[self.buf[j] as usize] {
877                            j += 1;
878                        }
879                        i = j;
880                        continue;
881                    }
882                    // -- line comment
883                    if b == b'-' {
884                        match self.peek2(i, b'-', at_eof) {
885                            Peek2::Hit => {
886                                // MySQL requires whitespace/EOL after `--` for it
887                                // to be a comment; `a--b` is arithmetic. Other
888                                // dialects always treat `--` as a comment.
889                                if is_mysql {
890                                    match self.buf.get(i + 2) {
891                                        Some(&c)
892                                            if c == b' '
893                                                || c == b'\t'
894                                                || c == b'\n'
895                                                || c == b'\r' =>
896                                        {
897                                            in_line_comment = true;
898                                            i += 2;
899                                            continue;
900                                        }
901                                        None if at_eof => {
902                                            in_line_comment = true;
903                                            i += 2;
904                                            continue;
905                                        }
906                                        None => break 'scan,
907                                        // `--x`: not a comment, just consume one `-`.
908                                        Some(_) => {
909                                            i += 1;
910                                            continue;
911                                        }
912                                    }
913                                }
914                                in_line_comment = true;
915                                i += 2;
916                                continue;
917                            }
918                            Peek2::Miss => {
919                                i += 1;
920                                continue;
921                            }
922                            Peek2::NeedMore => break 'scan,
923                        }
924                    }
925                    // MySQL # line comment
926                    if b == b'#' && is_mysql {
927                        in_line_comment = true;
928                        i += 1;
929                        continue;
930                    }
931                    // /* block comment
932                    if b == b'/' {
933                        match self.peek2(i, b'*', at_eof) {
934                            Peek2::Hit => {
935                                in_block_comment = true;
936                                i += 2;
937                                continue;
938                            }
939                            Peek2::Miss => {
940                                i += 1;
941                                continue;
942                            }
943                            Peek2::NeedMore => break 'scan,
944                        }
945                    }
946                }
947
948                // PostgreSQL dollar-quoting (outside other quotes).
949                if is_postgres && !inside_single_quote && !inside_double_quote && !inside_backtick {
950                    if b == b'$' && !in_dollar_quote {
951                        match self.buf[i + 1..].iter().position(|&c| c == b'$') {
952                            Some(end) => {
953                                let tag_bytes = &self.buf[i + 1..i + 1 + end];
954                                if is_valid_dollar_tag(tag_bytes) {
955                                    dollar_tag = tag_bytes.to_vec();
956                                    in_dollar_quote = true;
957                                    // Skip the whole opening $tag$ so its trailing
958                                    // $ is not re-read as a closer (bug #7).
959                                    i += end + 2;
960                                    continue;
961                                }
962                                // Not a valid tag: treat $ as an ordinary byte.
963                                i += 1;
964                                continue;
965                            }
966                            None if at_eof => {
967                                i += 1;
968                                continue;
969                            }
970                            // No closing $ yet — it may arrive in the next chunk.
971                            None => break 'scan,
972                        }
973                    } else if b == b'$' && in_dollar_quote {
974                        let tag_len = dollar_tag.len();
975                        if i + 1 + tag_len < self.buf.len() {
976                            if self.buf[i + 1..i + 1 + tag_len] == dollar_tag[..]
977                                && self.buf[i + 1 + tag_len] == b'$'
978                            {
979                                in_dollar_quote = false;
980                                dollar_tag.clear();
981                                i += tag_len + 2;
982                                continue;
983                            }
984                            i += 1;
985                            continue;
986                        } else if at_eof {
987                            i += 1;
988                            continue;
989                        } else {
990                            break 'scan;
991                        }
992                    }
993                }
994
995                if b == b'\'' && !inside_double_quote && !inside_backtick && !in_dollar_quote {
996                    if inside_single_quote {
997                        inside_single_quote = false;
998                        in_escape_string = false;
999                    } else {
1000                        inside_single_quote = true;
1001                        // A PostgreSQL E'…' escape string: the quote is preceded
1002                        // by `E`/`e` at a word boundary (not part of an
1003                        // identifier ending in e).
1004                        in_escape_string = is_postgres
1005                            && i > 0
1006                            && matches!(self.buf[i - 1], b'E' | b'e')
1007                            && (i < 2 || !is_word_byte(self.buf[i - 2]));
1008                    }
1009                } else if b == b'"' && !inside_single_quote && !inside_backtick && !in_dollar_quote
1010                {
1011                    inside_double_quote = !inside_double_quote;
1012                } else if b == b'`'
1013                    && is_mysql
1014                    && !inside_single_quote
1015                    && !inside_double_quote
1016                    && !in_dollar_quote
1017                {
1018                    inside_backtick = !inside_backtick;
1019                } else if b == delim0 && !inside_string {
1020                    // Statement terminator. The bytes after it stay in `buf` and
1021                    // become the next statement (buf_pos advances, no shifting).
1022                    let dl = delim_len;
1023                    if dl == 1 {
1024                        let result = self.buf[start..=i].to_vec();
1025                        self.buf_pos = i + 1;
1026
1027                        if is_postgres && self.is_copy_from_stdin(&result) {
1028                            self.in_copy_data = true;
1029                        }
1030                        return Ok(Some(result));
1031                    }
1032                    // Multi-byte delimiter (e.g. `;;`): the full token must match
1033                    // starting at `i`. A lone first byte (a `;` inside a routine
1034                    // body under a `;;` delimiter) is just an ordinary byte.
1035                    if i + dl <= self.buf.len() {
1036                        if self.buf[i..i + dl] == self.current_delimiter[..dl] {
1037                            let result = self.buf[start..i + dl].to_vec();
1038                            self.buf_pos = i + dl;
1039                            return Ok(Some(result));
1040                        }
1041                        i += 1;
1042                        continue;
1043                    } else if at_eof {
1044                        i += 1;
1045                        continue;
1046                    } else {
1047                        break 'scan;
1048                    }
1049                }
1050
1051                i += 1;
1052            }
1053
1054            if at_eof {
1055                if start >= self.buf.len() {
1056                    return Ok(None);
1057                }
1058                let result = self.buf[start..].to_vec();
1059                self.buf_pos = self.buf.len();
1060                return Ok(Some(result));
1061            }
1062
1063            // Need more bytes. Drop already-returned statements before `start`.
1064            let (removed, got_more) = self.grow_buffer(start)?;
1065            start -= removed;
1066            i -= removed;
1067            if !got_more {
1068                // Re-scan the remaining bytes once more with at_eof set so any
1069                // incomplete token at the tail is treated literally.
1070                at_eof = true;
1071            }
1072        }
1073    }
1074
1075    /// Check if statement is a PostgreSQL COPY FROM stdin
1076    fn is_copy_from_stdin(&self, stmt: &[u8]) -> bool {
1077        has_postgres_copy_stdin_source(stmt)
1078    }
1079
1080    /// Read PostgreSQL COPY data block until we see the terminator line (\.).
1081    /// The returned block includes everything up to and including the
1082    /// terminator line; anything after it is carried in `pending`.
1083    ///
1084    /// Note: a COPY block is buffered whole in memory (like every other
1085    /// statement here) — its size sets the memory floor for a pg_dump with one
1086    /// very large table. This is intentional: downstream consumers (redact,
1087    /// diff, sample) operate on a full block at a time.
1088    fn read_copy_data(&mut self) -> std::io::Result<Option<Vec<u8>>> {
1089        let mut start = self.buf_pos;
1090        let mut scan = self.buf_pos;
1091
1092        loop {
1093            // Scan completed lines for the terminator.
1094            while let Some(rel) = memchr::memchr(b'\n', &self.buf[scan..]) {
1095                let nl = scan + rel;
1096                let line = &self.buf[scan..=nl];
1097                if line == b"\\.\n" || line == b"\\.\r\n" {
1098                    self.in_copy_data = false;
1099                    let result = self.buf[start..=nl].to_vec();
1100                    self.buf_pos = nl + 1;
1101                    return Ok(Some(result));
1102                }
1103                scan = nl + 1;
1104            }
1105
1106            let (removed, got_more) = self.grow_buffer(start)?;
1107            start -= removed;
1108            scan -= removed;
1109            if !got_more {
1110                self.in_copy_data = false;
1111                if start >= self.buf.len() {
1112                    return Ok(None);
1113                }
1114                let result = self.buf[start..].to_vec();
1115                self.buf_pos = self.buf.len();
1116                return Ok(Some(result));
1117            }
1118        }
1119    }
1120
1121    /// Stream the input as [`ParserEvent`]s with bounded memory.
1122    ///
1123    /// Ordinary DDL/control statements are buffered whole (they are small) and
1124    /// delivered as [`ParserEvent::Statement`]. A multi-row INSERT is delivered
1125    /// as its header plus one [`ParserEvent::InsertRow`] per tuple, and a COPY
1126    /// block as [`ParserEvent::CopyStart`] / [`ParserEvent::CopyRow`] per line /
1127    /// [`ParserEvent::CopyEnd`] — the whole multi-row block is never buffered at
1128    /// once. The callback must consume each borrowed slice before returning.
1129    ///
1130    /// Unlike [`read_statement`](Self::read_statement) (kept for compatibility),
1131    /// data statements are not routed through it: their rows are streamed.
1132    pub fn visit_events<F>(&mut self, mut on_event: F) -> anyhow::Result<()>
1133    where
1134        F: FnMut(ParserEvent<'_>) -> anyhow::Result<RowFlow>,
1135    {
1136        loop {
1137            // Ensure at least one byte at/after buf_pos, or stop at EOF.
1138            while self.buf_pos >= self.buf.len() {
1139                let (removed, more) = self.grow_buffer(self.buf_pos)?;
1140                self.buf_pos -= removed;
1141                if !more {
1142                    return Ok(());
1143                }
1144            }
1145
1146            if self.peek_is_insert()? {
1147                if self.visit_insert_stmt(&mut on_event)? == RowFlow::Stop {
1148                    return Ok(());
1149                }
1150                continue;
1151            }
1152
1153            // Non-INSERT: reuse read_statement to consume one DDL/control or
1154            // COPY header statement (small). COPY data blocks are then streamed
1155            // line-by-line rather than buffered whole.
1156            let stmt = match self.read_statement()? {
1157                Some(s) => s,
1158                None => return Ok(()),
1159            };
1160            if self.in_copy_data {
1161                self.in_copy_data = false;
1162                let skip_rows = match on_event(ParserEvent::CopyStart(&stmt))? {
1163                    RowFlow::Continue => false,
1164                    RowFlow::SkipStatement => true,
1165                    RowFlow::Stop => return Ok(()),
1166                };
1167                if self.visit_copy_data(&mut on_event, skip_rows)? == RowFlow::Stop {
1168                    return Ok(());
1169                }
1170            } else if on_event(ParserEvent::Statement(&stmt))? == RowFlow::Stop {
1171                return Ok(());
1172            }
1173        }
1174    }
1175
1176    /// Peek whether the next statement (after leading comments/whitespace) is an
1177    /// `INSERT INTO`/`INSERT ONLY`, growing the buffer just enough to decide.
1178    fn peek_is_insert(&mut self) -> anyhow::Result<bool> {
1179        loop {
1180            let stripped = strip_leading_comments_and_whitespace(&self.buf[self.buf_pos..]);
1181            if stripped.len() >= 11 {
1182                return Ok(starts_with_insert(stripped));
1183            }
1184            if self.buf.len() - self.buf_pos > self.limits.max_header {
1185                anyhow::bail!(
1186                    "statement header exceeds max_header ({} bytes) at input offset {}",
1187                    self.limits.max_header,
1188                    self.base + self.buf_pos as u64
1189                );
1190            }
1191            let (removed, more) = self.grow_buffer(self.buf_pos)?;
1192            self.buf_pos -= removed;
1193            if !more {
1194                let stripped = strip_leading_comments_and_whitespace(&self.buf[self.buf_pos..]);
1195                return Ok(starts_with_insert(stripped));
1196            }
1197        }
1198    }
1199
1200    /// Stream one INSERT statement's tuples as [`ParserEvent::InsertRow`]s.
1201    fn visit_insert_stmt<F>(&mut self, on_event: &mut F) -> anyhow::Result<RowFlow>
1202    where
1203        F: FnMut(ParserEvent<'_>) -> anyhow::Result<RowFlow>,
1204    {
1205        // Locate the VALUES keyword, buffering only the header (bounded). The
1206        // scan stops at the statement's own `;`, so a VALUES-less INSERT
1207        // (INSERT … SELECT / SET) is emitted whole rather than absorbing later
1208        // statements while hunting for a VALUES that belongs to one of them.
1209        let (header, values_abs) = loop {
1210            let stripped_len =
1211                strip_leading_comments_and_whitespace(&self.buf[self.buf_pos..]).len();
1212            let start = self.buf.len() - stripped_len;
1213            match mysql_insert::scan_insert_header(&self.buf[start..], self.dialect) {
1214                mysql_insert::HeaderScan::Values(vp) => {
1215                    let values_abs = start + vp;
1216                    break (self.buf[start..values_abs].to_vec(), values_abs);
1217                }
1218                mysql_insert::HeaderScan::NoValues(end_off) => {
1219                    // Emit the whole statement (up to and including its `;`) as
1220                    // an opaque Statement; there are no rows to stream.
1221                    let stmt_end = start + end_off;
1222                    let flow = on_event(ParserEvent::Statement(&self.buf[self.buf_pos..stmt_end]))?;
1223                    self.buf_pos = stmt_end;
1224                    return Ok(flow);
1225                }
1226                mysql_insert::HeaderScan::Incomplete => {
1227                    if self.buf.len() - self.buf_pos > self.limits.max_header {
1228                        anyhow::bail!(
1229                            "INSERT header exceeds max_header ({} bytes) at input offset {}",
1230                            self.limits.max_header,
1231                            self.base + self.buf_pos as u64
1232                        );
1233                    }
1234                    let (removed, more) = self.grow_buffer(self.buf_pos)?;
1235                    self.buf_pos -= removed;
1236                    if !more {
1237                        // Truncated header at EOF: emit the remaining bytes as an
1238                        // opaque statement so nothing is lost.
1239                        let flow = on_event(ParserEvent::Statement(&self.buf[self.buf_pos..]))?;
1240                        self.buf_pos = self.buf.len();
1241                        return Ok(flow);
1242                    }
1243                }
1244            }
1245        };
1246
1247        let mut cur = values_abs;
1248        let mut first = true;
1249        let mut skipping = false;
1250
1251        loop {
1252            // Skip inter-tuple whitespace and commas.
1253            loop {
1254                while cur < self.buf.len()
1255                    && matches!(self.buf[cur], b' ' | b'\t' | b'\n' | b'\r' | b',')
1256                {
1257                    cur += 1;
1258                }
1259                if cur < self.buf.len() {
1260                    break;
1261                }
1262                let (removed, more) = self.grow_buffer(cur)?;
1263                cur -= removed;
1264                if !more {
1265                    break;
1266                }
1267            }
1268
1269            if cur >= self.buf.len() {
1270                self.buf_pos = self.buf.len();
1271                return Ok(RowFlow::Continue);
1272            }
1273            match self.buf[cur] {
1274                b';' => {
1275                    self.buf_pos = cur + 1;
1276                    return Ok(RowFlow::Continue);
1277                }
1278                b'(' => {}
1279                // Anything else (e.g. an MSSQL GO batch line) ends the INSERT;
1280                // leave it for the next statement.
1281                _ => {
1282                    self.buf_pos = cur;
1283                    return Ok(RowFlow::Continue);
1284                }
1285            }
1286
1287            // Scan exactly one tuple, growing until it is complete or EOF.
1288            let (tuple_end, complete) = loop {
1289                if self.buf.len() - cur > self.limits.max_row {
1290                    anyhow::bail!(
1291                        "INSERT row exceeds max_row ({} bytes) at input offset {}",
1292                        self.limits.max_row,
1293                        self.base + cur as u64
1294                    );
1295                }
1296                match mysql_insert::scan_insert_tuple(&self.buf[cur..], self.dialect) {
1297                    Some((len, true)) => break (cur + len, true),
1298                    Some(_) => {
1299                        let (removed, more) = self.grow_buffer(cur)?;
1300                        cur -= removed;
1301                        if !more {
1302                            break (self.buf.len(), false);
1303                        }
1304                    }
1305                    None => {
1306                        self.buf_pos = cur;
1307                        return Ok(RowFlow::Continue);
1308                    }
1309                }
1310            };
1311
1312            if skipping {
1313                cur = tuple_end;
1314            } else {
1315                let flow = on_event(ParserEvent::InsertRow {
1316                    header: &header,
1317                    row: &self.buf[cur..tuple_end],
1318                    first_in_statement: first,
1319                })?;
1320                first = false;
1321                match flow {
1322                    RowFlow::Continue => cur = tuple_end,
1323                    RowFlow::SkipStatement => {
1324                        skipping = true;
1325                        cur = tuple_end;
1326                    }
1327                    RowFlow::Stop => {
1328                        self.buf_pos = tuple_end;
1329                        return Ok(RowFlow::Stop);
1330                    }
1331                }
1332            }
1333
1334            if !complete {
1335                self.buf_pos = self.buf.len();
1336                return Ok(RowFlow::Continue);
1337            }
1338        }
1339    }
1340
1341    /// Stream a COPY data block (positioned just past the header's `;`) as
1342    /// [`ParserEvent::CopyRow`]s followed by [`ParserEvent::CopyEnd`].
1343    fn visit_copy_data<F>(
1344        &mut self,
1345        on_event: &mut F,
1346        initially_skipping: bool,
1347    ) -> anyhow::Result<RowFlow>
1348    where
1349        F: FnMut(ParserEvent<'_>) -> anyhow::Result<RowFlow>,
1350    {
1351        // Consume the line terminator that ends the `COPY ... FROM stdin;`
1352        // header line (read_statement stopped at the `;`), so the first emitted
1353        // CopyRow is a real data line rather than a phantom empty one.
1354        for &want in b"\r\n" {
1355            while self.buf_pos >= self.buf.len() {
1356                let (removed, more) = self.grow_buffer(self.buf_pos)?;
1357                self.buf_pos -= removed;
1358                if !more {
1359                    return Ok(RowFlow::Continue);
1360                }
1361            }
1362            if self.buf[self.buf_pos] == want {
1363                self.buf_pos += 1;
1364            }
1365        }
1366
1367        let mut ls = self.buf_pos;
1368        let mut skipping = initially_skipping;
1369
1370        loop {
1371            let nl = loop {
1372                if let Some(rel) = memchr::memchr(b'\n', &self.buf[ls..]) {
1373                    break Some(ls + rel);
1374                }
1375                if self.buf.len() - ls > self.limits.max_row {
1376                    anyhow::bail!(
1377                        "COPY line exceeds max_row ({} bytes) at input offset {}",
1378                        self.limits.max_row,
1379                        self.base + ls as u64
1380                    );
1381                }
1382                let (removed, more) = self.grow_buffer(ls)?;
1383                ls -= removed;
1384                if !more {
1385                    break None;
1386                }
1387            };
1388
1389            if nl.is_none() && ls >= self.buf.len() {
1390                // EOF with no trailing data.
1391                self.buf_pos = self.buf.len();
1392                return Ok(RowFlow::Continue);
1393            }
1394
1395            let line_end = nl.unwrap_or(self.buf.len());
1396            let line = &self.buf[ls..line_end];
1397            let check: &[u8] = if line.last() == Some(&b'\r') {
1398                &line[..line.len() - 1]
1399            } else {
1400                line
1401            };
1402
1403            if check == b"\\." {
1404                let flow = on_event(ParserEvent::CopyEnd)?;
1405                self.buf_pos = nl.map(|n| n + 1).unwrap_or(self.buf.len());
1406                return Ok(flow);
1407            }
1408
1409            if !skipping {
1410                match on_event(ParserEvent::CopyRow(line))? {
1411                    RowFlow::Continue => {}
1412                    RowFlow::SkipStatement => skipping = true,
1413                    RowFlow::Stop => {
1414                        self.buf_pos = nl.map(|n| n + 1).unwrap_or(self.buf.len());
1415                        return Ok(RowFlow::Stop);
1416                    }
1417                }
1418            }
1419
1420            match nl {
1421                Some(n) => ls = n + 1,
1422                None => {
1423                    self.buf_pos = self.buf.len();
1424                    return Ok(RowFlow::Continue);
1425                }
1426            }
1427        }
1428    }
1429
1430    /// Read MSSQL statement with GO batch separator support.
1431    /// GO is a batch separator that appears on its own line; `;` also
1432    /// terminates. Uses the same `buf` + cursor model as [`read_statement`] so
1433    /// tokens can't straddle a chunk boundary and scanning stays O(n).
1434    fn read_statement_mssql(&mut self) -> std::io::Result<Option<Vec<u8>>> {
1435        let mut start = self.buf_pos;
1436        let mut i = self.buf_pos;
1437        let mut line_start = self.buf_pos;
1438
1439        let mut inside_single_quote = false;
1440        let mut inside_bracket_quote = false;
1441        let mut in_line_comment = false;
1442        let mut in_block_comment = false;
1443        let mut at_eof = false;
1444
1445        loop {
1446            'scan: while i < self.buf.len() {
1447                let b = self.buf[i];
1448
1449                if in_block_comment {
1450                    if b == b'*' {
1451                        match self.peek2(i, b'/', at_eof) {
1452                            Peek2::Hit => {
1453                                in_block_comment = false;
1454                                i += 2;
1455                                continue;
1456                            }
1457                            Peek2::Miss => {
1458                                i += 1;
1459                                continue;
1460                            }
1461                            Peek2::NeedMore => break 'scan,
1462                        }
1463                    }
1464                    i += 1;
1465                    continue;
1466                }
1467
1468                if in_line_comment {
1469                    if b == b'\n' {
1470                        in_line_comment = false;
1471                        line_start = i + 1;
1472                    }
1473                    i += 1;
1474                    continue;
1475                }
1476
1477                if inside_bracket_quote {
1478                    if b == b']' {
1479                        match self.peek2(i, b']', at_eof) {
1480                            // Escaped ]] stays inside the identifier (bug #8)
1481                            Peek2::Hit => {
1482                                i += 2;
1483                                continue;
1484                            }
1485                            Peek2::Miss => {
1486                                inside_bracket_quote = false;
1487                                i += 1;
1488                                continue;
1489                            }
1490                            Peek2::NeedMore => break 'scan,
1491                        }
1492                    }
1493                    i += 1;
1494                    continue;
1495                }
1496
1497                if inside_single_quote {
1498                    // Fast-skip to the closing quote (MSSQL has no `\` escapes).
1499                    match memchr::memchr(b'\'', &self.buf[i..]) {
1500                        Some(0) => inside_single_quote = false,
1501                        Some(off) => {
1502                            i += off;
1503                            continue;
1504                        }
1505                        None if at_eof => {
1506                            i = self.buf.len();
1507                            continue;
1508                        }
1509                        None => break 'scan,
1510                    }
1511                    i += 1;
1512                    continue;
1513                }
1514
1515                // Outside strings/comments.
1516                if b == b'-' {
1517                    match self.peek2(i, b'-', at_eof) {
1518                        Peek2::Hit => {
1519                            in_line_comment = true;
1520                            i += 2;
1521                            continue;
1522                        }
1523                        Peek2::Miss => {
1524                            i += 1;
1525                            continue;
1526                        }
1527                        Peek2::NeedMore => break 'scan,
1528                    }
1529                }
1530                if b == b'/' {
1531                    match self.peek2(i, b'*', at_eof) {
1532                        Peek2::Hit => {
1533                            in_block_comment = true;
1534                            i += 2;
1535                            continue;
1536                        }
1537                        Peek2::Miss => {
1538                            i += 1;
1539                            continue;
1540                        }
1541                        Peek2::NeedMore => break 'scan,
1542                    }
1543                }
1544                if b == b'\'' {
1545                    inside_single_quote = true;
1546                    i += 1;
1547                    continue;
1548                }
1549                if b == b'[' {
1550                    inside_bracket_quote = true;
1551                    i += 1;
1552                    continue;
1553                }
1554                if b == b';' {
1555                    let result = self.buf[start..=i].to_vec();
1556                    self.buf_pos = i + 1;
1557                    return Ok(Some(result));
1558                }
1559                if b == b'\n' {
1560                    if is_go_line(&self.buf[line_start..=i]) {
1561                        // Trim trailing whitespace before the GO line.
1562                        let mut stmt_end = line_start;
1563                        while stmt_end > start
1564                            && matches!(self.buf[stmt_end - 1], b'\n' | b'\r' | b' ' | b'\t')
1565                        {
1566                            stmt_end -= 1;
1567                        }
1568                        self.buf_pos = i + 1;
1569                        if stmt_end > start {
1570                            return Ok(Some(self.buf[start..stmt_end].to_vec()));
1571                        }
1572                        // Empty batch: start a new statement after the GO line.
1573                        start = i + 1;
1574                        line_start = i + 1;
1575                        i += 1;
1576                        continue;
1577                    }
1578                    line_start = i + 1;
1579                    i += 1;
1580                    continue;
1581                }
1582
1583                i += 1;
1584            }
1585
1586            if at_eof {
1587                if start >= self.buf.len() {
1588                    return Ok(None);
1589                }
1590                // Handle a trailing GO with no final newline (bug #12).
1591                if is_go_line(&self.buf[line_start..]) {
1592                    let mut stmt_end = line_start;
1593                    while stmt_end > start
1594                        && matches!(self.buf[stmt_end - 1], b'\n' | b'\r' | b' ' | b'\t')
1595                    {
1596                        stmt_end -= 1;
1597                    }
1598                    self.buf_pos = self.buf.len();
1599                    if stmt_end > start {
1600                        return Ok(Some(self.buf[start..stmt_end].to_vec()));
1601                    }
1602                    return Ok(None);
1603                }
1604                let result = self.buf[start..].to_vec();
1605                self.buf_pos = self.buf.len();
1606                return Ok(Some(result));
1607            }
1608
1609            let (removed, got_more) = self.grow_buffer(start)?;
1610            start -= removed;
1611            i -= removed;
1612            line_start -= removed;
1613            if !got_more {
1614                at_eof = true;
1615            }
1616        }
1617    }
1618
1619    #[allow(dead_code)]
1620    pub fn parse_statement(stmt: &[u8]) -> (StatementType, String) {
1621        Self::parse_statement_with_dialect(stmt, SqlDialect::MySql)
1622    }
1623
1624    /// Parse a statement with dialect-specific handling
1625    pub fn parse_statement_with_dialect(
1626        stmt: &[u8],
1627        dialect: SqlDialect,
1628    ) -> (StatementType, String) {
1629        // Strip leading comments (e.g., pg_dump adds -- comments before statements)
1630        let stmt = strip_leading_comments_and_whitespace(stmt);
1631
1632        if stmt.len() < 4 {
1633            return (StatementType::Unknown, String::new());
1634        }
1635
1636        // Use stack-allocated buffer to avoid heap allocation in hot path
1637        let mut upper_prefix = [0u8; 25];
1638        let prefix_len = stmt.len().min(25);
1639        for (i, &b) in stmt.iter().take(prefix_len).enumerate() {
1640            upper_prefix[i] = b.to_ascii_uppercase();
1641        }
1642        let upper_prefix = &upper_prefix[..prefix_len];
1643
1644        // PostgreSQL COPY statement
1645        if upper_prefix.starts_with(b"COPY ") {
1646            if let Some(name) = extract_table_name_flexible(stmt, 4, dialect) {
1647                return (StatementType::Copy, name);
1648            }
1649        }
1650
1651        if upper_prefix.starts_with(b"CREATE TABLE") {
1652            // Try fast extraction first
1653            if let Some(name) = extract_table_name_flexible(stmt, 12, dialect) {
1654                return (StatementType::CreateTable, name);
1655            }
1656            // Fall back to flexible regex
1657            if let Some(caps) = CREATE_TABLE_FLEXIBLE_RE.captures(stmt) {
1658                if let Some(m) = caps.get(1) {
1659                    return (
1660                        StatementType::CreateTable,
1661                        String::from_utf8_lossy(m.as_bytes()).into_owned(),
1662                    );
1663                }
1664            }
1665        }
1666
1667        if upper_prefix.starts_with(b"INSERT INTO") || upper_prefix.starts_with(b"INSERT ONLY") {
1668            if let Some(name) = extract_table_name_flexible(stmt, 11, dialect) {
1669                return (StatementType::Insert, name);
1670            }
1671            if let Some(caps) = INSERT_FLEXIBLE_RE.captures(stmt) {
1672                if let Some(m) = caps.get(1) {
1673                    return (
1674                        StatementType::Insert,
1675                        String::from_utf8_lossy(m.as_bytes()).into_owned(),
1676                    );
1677                }
1678            }
1679        }
1680
1681        if upper_prefix.starts_with(b"CREATE INDEX")
1682            || upper_prefix.starts_with(b"CREATE UNIQUE")
1683            || upper_prefix.starts_with(b"CREATE CLUSTERED")
1684            || upper_prefix.starts_with(b"CREATE NONCLUSTER")
1685        {
1686            // For MSSQL, try the bracket-aware regex first
1687            if dialect == SqlDialect::Mssql {
1688                if let Some(caps) = CREATE_INDEX_MSSQL_RE.captures(stmt) {
1689                    if let Some(m) = caps.get(1) {
1690                        if let Some(name) = extract_table_name_flexible(m.as_bytes(), 0, dialect) {
1691                            return (StatementType::CreateIndex, name);
1692                        }
1693                    }
1694                }
1695            }
1696            // Fall back to generic regex for MySQL/PostgreSQL/SQLite
1697            if let Some(caps) = CREATE_INDEX_RE.captures(stmt) {
1698                if let Some(m) = caps.get(1) {
1699                    if let Some(name) = extract_table_name_flexible(m.as_bytes(), 0, dialect) {
1700                        return (StatementType::CreateIndex, name);
1701                    }
1702                }
1703            }
1704        }
1705
1706        if upper_prefix.starts_with(b"ALTER TABLE") {
1707            if let Some(name) = extract_table_name_flexible(stmt, 11, dialect) {
1708                return (StatementType::AlterTable, name);
1709            }
1710            if let Some(caps) = ALTER_TABLE_RE.captures(stmt) {
1711                if let Some(m) = caps.get(1) {
1712                    return (
1713                        StatementType::AlterTable,
1714                        String::from_utf8_lossy(m.as_bytes()).into_owned(),
1715                    );
1716                }
1717            }
1718        }
1719
1720        if upper_prefix.starts_with(b"DROP TABLE") {
1721            if let Some(name) = extract_table_name_flexible(stmt, 10, dialect) {
1722                return (StatementType::DropTable, name);
1723            }
1724            if let Some(caps) = DROP_TABLE_RE.captures(stmt) {
1725                if let Some(m) = caps.get(1) {
1726                    return (
1727                        StatementType::DropTable,
1728                        String::from_utf8_lossy(m.as_bytes()).into_owned(),
1729                    );
1730                }
1731            }
1732        }
1733
1734        // MSSQL BULK INSERT - treat as Insert statement type
1735        if upper_prefix.starts_with(b"BULK INSERT") {
1736            if let Some(name) = extract_table_name_flexible(stmt, 11, dialect) {
1737                return (StatementType::Insert, name);
1738            }
1739        }
1740
1741        (StatementType::Unknown, String::new())
1742    }
1743}
1744
1745#[inline]
1746fn trim_ascii_start(data: &[u8]) -> &[u8] {
1747    let start = data
1748        .iter()
1749        .position(|&b| !matches!(b, b' ' | b'\t' | b'\n' | b'\r'))
1750        .unwrap_or(data.len());
1751    &data[start..]
1752}
1753
1754/// Strip leading whitespace and SQL line comments (`-- ...`) from a statement.
1755/// This makes parsing robust to pg_dump-style comment blocks before statements.
1756pub(crate) fn strip_leading_comments_and_whitespace(mut data: &[u8]) -> &[u8] {
1757    loop {
1758        // First trim leading ASCII whitespace
1759        data = trim_ascii_start(data);
1760
1761        // Strip a leading UTF-8 BOM (EF BB BF). Without this the first statement
1762        // in a BOM-prefixed dump classifies as Unknown and split drops it.
1763        if data.starts_with(&[0xEF, 0xBB, 0xBF]) {
1764            data = &data[3..];
1765            continue;
1766        }
1767
1768        // Handle -- line comments
1769        if data.len() >= 2 && data[0] == b'-' && data[1] == b'-' {
1770            // Skip until end of line
1771            if let Some(pos) = data.iter().position(|&b| b == b'\n') {
1772                data = &data[pos + 1..];
1773                continue;
1774            } else {
1775                // Comment runs to EOF, nothing left
1776                return &[];
1777            }
1778        }
1779
1780        // Handle /* */ block comments (including MySQL conditional comments)
1781        if data.len() >= 2 && data[0] == b'/' && data[1] == b'*' {
1782            // Find the closing */
1783            let mut i = 2;
1784            let mut depth = 1;
1785            while i < data.len() - 1 && depth > 0 {
1786                if data[i] == b'*' && data[i + 1] == b'/' {
1787                    depth -= 1;
1788                    i += 2;
1789                } else if data[i] == b'/' && data[i + 1] == b'*' {
1790                    depth += 1;
1791                    i += 2;
1792                } else {
1793                    i += 1;
1794                }
1795            }
1796            if depth == 0 {
1797                data = &data[i..];
1798                continue;
1799            } else {
1800                // Unclosed comment runs to EOF
1801                return &[];
1802            }
1803        }
1804
1805        // Handle # line comments (MySQL)
1806        if !data.is_empty() && data[0] == b'#' {
1807            if let Some(pos) = data.iter().position(|&b| b == b'\n') {
1808                data = &data[pos + 1..];
1809                continue;
1810            } else {
1811                return &[];
1812            }
1813        }
1814
1815        break;
1816    }
1817
1818    data
1819}
1820
1821/// Return whether `stmt` is a PostgreSQL `COPY ... FROM STDIN` command.
1822///
1823/// This deliberately recognizes source tokens rather than searching bytes. A
1824/// quoted identifier, a string literal, a comment, or a parenthesized COPY
1825/// query can contain `FROM STDIN` without opening a data block.
1826fn has_postgres_copy_stdin_source(stmt: &[u8]) -> bool {
1827    let stmt = strip_leading_comments_and_whitespace(stmt);
1828    let mut i = 0;
1829    let mut paren_depth = 0u32;
1830    let mut saw_copy = false;
1831    let mut expecting_stdin = false;
1832
1833    while i < stmt.len() {
1834        let byte = stmt[i];
1835
1836        if is_whitespace(byte) {
1837            i += 1;
1838            continue;
1839        }
1840
1841        if byte == b'-' && stmt.get(i + 1) == Some(&b'-') {
1842            i += 2;
1843            while i < stmt.len() && stmt[i] != b'\n' {
1844                i += 1;
1845            }
1846            continue;
1847        }
1848
1849        if byte == b'/' && stmt.get(i + 1) == Some(&b'*') {
1850            i += 2;
1851            let mut comment_depth = 1u32;
1852            while i < stmt.len() && comment_depth > 0 {
1853                match (stmt[i], stmt.get(i + 1)) {
1854                    (b'/', Some(b'*')) => {
1855                        comment_depth += 1;
1856                        i += 2;
1857                    }
1858                    (b'*', Some(b'/')) => {
1859                        comment_depth -= 1;
1860                        i += 2;
1861                    }
1862                    _ => i += 1,
1863                }
1864            }
1865            continue;
1866        }
1867
1868        if matches!(byte, b'\'' | b'\"' | b'`' | b'[') {
1869            let close = if byte == b'[' { b']' } else { byte };
1870            i += 1;
1871            while i < stmt.len() {
1872                if stmt[i] == b'\\' && close == b'\'' && i + 1 < stmt.len() {
1873                    i += 2;
1874                    continue;
1875                }
1876                if stmt[i] == close {
1877                    if stmt.get(i + 1) == Some(&close) {
1878                        i += 2;
1879                        continue;
1880                    }
1881                    i += 1;
1882                    break;
1883                }
1884                i += 1;
1885            }
1886            expecting_stdin = false;
1887            continue;
1888        }
1889
1890        match byte {
1891            b'(' => {
1892                paren_depth = paren_depth.saturating_add(1);
1893                expecting_stdin = false;
1894                i += 1;
1895                continue;
1896            }
1897            b')' => {
1898                paren_depth = paren_depth.saturating_sub(1);
1899                expecting_stdin = false;
1900                i += 1;
1901                continue;
1902            }
1903            b';' => return false,
1904            _ => {}
1905        }
1906
1907        if byte.is_ascii_alphabetic() || byte == b'_' {
1908            let start = i;
1909            i += 1;
1910            while i < stmt.len() && is_word_byte(stmt[i]) {
1911                i += 1;
1912            }
1913            let word = &stmt[start..i];
1914
1915            if !saw_copy {
1916                if !word.eq_ignore_ascii_case(b"COPY") {
1917                    return false;
1918                }
1919                saw_copy = true;
1920                continue;
1921            }
1922
1923            if paren_depth == 0 {
1924                if expecting_stdin {
1925                    return word.eq_ignore_ascii_case(b"STDIN");
1926                }
1927                expecting_stdin = word.eq_ignore_ascii_case(b"FROM");
1928            }
1929            continue;
1930        }
1931
1932        expecting_stdin = false;
1933        i += 1;
1934    }
1935
1936    false
1937}
1938
1939/// Extract table name with support for:
1940/// - IF NOT EXISTS
1941/// - ONLY (PostgreSQL)
1942/// - Schema-qualified names (`schema.table` is retained)
1943/// - Both backtick and double-quote quoting
1944#[inline]
1945pub(crate) fn extract_table_name_flexible(
1946    stmt: &[u8],
1947    offset: usize,
1948    dialect: SqlDialect,
1949) -> Option<String> {
1950    let mut i = offset;
1951
1952    // Skip whitespace
1953    while i < stmt.len() && is_whitespace(stmt[i]) {
1954        i += 1;
1955    }
1956
1957    if i >= stmt.len() {
1958        return None;
1959    }
1960
1961    // Check for IF NOT EXISTS or IF EXISTS (stack-allocated to avoid heap allocation)
1962    let mut upper_check = [0u8; 20];
1963    let check_len = (stmt.len() - i).min(20);
1964    for (idx, &b) in stmt[i..].iter().take(check_len).enumerate() {
1965        upper_check[idx] = b.to_ascii_uppercase();
1966    }
1967    let upper_slice = &upper_check[..check_len];
1968    if upper_slice.starts_with(b"IF NOT EXISTS") {
1969        i += 13; // Skip "IF NOT EXISTS"
1970        while i < stmt.len() && is_whitespace(stmt[i]) {
1971            i += 1;
1972        }
1973    } else if upper_slice.starts_with(b"IF EXISTS") {
1974        i += 9; // Skip "IF EXISTS"
1975        while i < stmt.len() && is_whitespace(stmt[i]) {
1976            i += 1;
1977        }
1978    }
1979
1980    // Check for ONLY (PostgreSQL) - reuse first 10 bytes or re-check if position changed
1981    let only_check = if i < stmt.len() {
1982        let mut buf = [0u8; 10];
1983        let len = (stmt.len() - i).min(10);
1984        for (idx, &b) in stmt[i..].iter().take(len).enumerate() {
1985            buf[idx] = b.to_ascii_uppercase();
1986        }
1987        (buf, len)
1988    } else {
1989        ([0u8; 10], 0)
1990    };
1991    let only_slice = &only_check.0[..only_check.1];
1992    if only_slice.starts_with(b"ONLY ") || only_slice.starts_with(b"ONLY\t") {
1993        i += 4;
1994        while i < stmt.len() && is_whitespace(stmt[i]) {
1995            i += 1;
1996        }
1997    }
1998
1999    if i >= stmt.len() {
2000        return None;
2001    }
2002
2003    // Read identifier (potentially schema-qualified)
2004    let mut parts: Vec<String> = Vec::new();
2005
2006    loop {
2007        // Determine quote character based on dialect
2008        let (quote_char, close_char) = match stmt.get(i) {
2009            Some(b'`') if dialect == SqlDialect::MySql => {
2010                i += 1;
2011                (Some(b'`'), b'`')
2012            }
2013            // Double quotes are the standard identifier quote for
2014            // Postgres/SQLite/MSSQL, and accepted for MySQL too (less common).
2015            Some(b'"') => {
2016                i += 1;
2017                (Some(b'"'), b'"')
2018            }
2019            Some(b'[') if dialect == SqlDialect::Mssql => {
2020                // MSSQL square bracket quoting
2021                i += 1;
2022                (Some(b'['), b']')
2023            }
2024            _ => (None, 0),
2025        };
2026
2027        let start = i;
2028
2029        while i < stmt.len() {
2030            let b = stmt[i];
2031            if quote_char.is_some() {
2032                if b == close_char {
2033                    // For MSSQL, check for escaped ]]
2034                    if dialect == SqlDialect::Mssql
2035                        && close_char == b']'
2036                        && i + 1 < stmt.len()
2037                        && stmt[i + 1] == b']'
2038                    {
2039                        // Escaped bracket, skip both
2040                        i += 2;
2041                        continue;
2042                    }
2043                    let name = &stmt[start..i];
2044                    // For MSSQL, unescape ]] to ]
2045                    let name_str = match quote_char {
2046                        Some(b'[') if dialect == SqlDialect::Mssql => {
2047                            String::from_utf8_lossy(name).replace("]]", "]")
2048                        }
2049                        Some(b'"') => String::from_utf8_lossy(name).replace("\"\"", "\""),
2050                        Some(b'`') => String::from_utf8_lossy(name).replace("``", "`"),
2051                        _ => String::from_utf8_lossy(name).into_owned(),
2052                    };
2053                    parts.push(canonicalize_qualified_part(name_str, quote_char.is_some()));
2054                    i += 1; // Skip closing quote
2055                    break;
2056                }
2057            } else if is_whitespace(b) || b == b'(' || b == b';' || b == b',' || b == b'.' {
2058                if i > start {
2059                    let name = &stmt[start..i];
2060                    parts.push(String::from_utf8_lossy(name).into_owned());
2061                }
2062                break;
2063            }
2064            i += 1;
2065        }
2066
2067        // An unquoted terminal component can run to the end of a captured
2068        // table reference (for example `dbo.users` extracted from CREATE
2069        // INDEX), where the delimiter branch above never gets a chance to
2070        // push it.
2071        if quote_char.is_none() && i == stmt.len() && i > start {
2072            parts.push(String::from_utf8_lossy(&stmt[start..i]).into_owned());
2073        }
2074
2075        // If at end of quoted name without finding close quote, bail
2076        if quote_char.is_some() && i <= start {
2077            break;
2078        }
2079
2080        // Check for schema separator (.)
2081        while i < stmt.len() && is_whitespace(stmt[i]) {
2082            i += 1;
2083        }
2084
2085        if i < stmt.len() && stmt[i] == b'.' {
2086            i += 1; // Skip the dot
2087            while i < stmt.len() && is_whitespace(stmt[i]) {
2088                i += 1;
2089            }
2090            // Continue to read the next identifier (table name)
2091        } else {
2092            break;
2093        }
2094    }
2095
2096    if parts.is_empty() {
2097        None
2098    } else {
2099        Some(parts.join("."))
2100    }
2101}
2102
2103#[inline]
2104fn is_whitespace(b: u8) -> bool {
2105    matches!(b, b' ' | b'\t' | b'\n' | b'\r')
2106}
2107
2108/// Preserve a quoted identifier component that contains a dot. The schema and
2109/// output layers use dots as table-reference separators, so retaining quote
2110/// boundaries prevents `public."user.log"` from becoming three components.
2111fn canonicalize_qualified_part(part: String, was_quoted: bool) -> String {
2112    if was_quoted && part.contains('.') {
2113        format!("\"{}\"", part.replace('"', "\"\""))
2114    } else {
2115        part
2116    }
2117}
2118
2119/// True if `b` can be part of a SQL identifier (letters, digits, `_`). Used to
2120/// tell a PostgreSQL `E'…'` escape-string prefix from an identifier that merely
2121/// ends in `e` (e.g. `type`).
2122#[inline]
2123fn is_word_byte(b: u8) -> bool {
2124    b.is_ascii_alphanumeric() || b == b'_'
2125}
2126
2127/// True if `s` begins with an `INSERT INTO`/`INSERT ONLY` value statement (the
2128/// forms that carry a `VALUES` list). `BULK INSERT` and other keywords are
2129/// intentionally excluded so [`Parser::visit_events`] only enters tuple-
2130/// streaming mode for statements it can actually stream.
2131#[inline]
2132fn starts_with_insert(s: &[u8]) -> bool {
2133    s.len() >= 11
2134        && (s[..11].eq_ignore_ascii_case(b"INSERT INTO")
2135            || s[..11].eq_ignore_ascii_case(b"INSERT ONLY"))
2136}
2137
2138/// A dollar-quote tag is either empty (`$$`) or an identifier
2139/// (`[A-Za-z_][A-Za-z0-9_]*`), matching PostgreSQL's rules.
2140#[inline]
2141fn is_valid_dollar_tag(tag: &[u8]) -> bool {
2142    match tag.first() {
2143        None => true,
2144        Some(&first) if first.is_ascii_alphabetic() || first == b'_' => tag[1..]
2145            .iter()
2146            .all(|&c| c.is_ascii_alphanumeric() || c == b'_'),
2147        _ => false,
2148    }
2149}
2150
2151pub fn determine_buffer_size(file_size: u64) -> usize {
2152    if file_size > 1024 * 1024 * 1024 {
2153        MEDIUM_BUFFER_SIZE
2154    } else {
2155        SMALL_BUFFER_SIZE
2156    }
2157}
2158
2159#[cfg(test)]
2160mod tests {
2161    use super::*;
2162
2163    #[test]
2164    fn copy_source_detection_ignores_quoted_and_literal_text() {
2165        for stmt in [
2166            b"COPY \"FROM STDIN\" TO STDOUT;".as_slice(),
2167            b"COPY report TO 'FROM STDIN';".as_slice(),
2168            b"COPY (SELECT 'FROM STDIN') TO STDOUT;".as_slice(),
2169            b"COPY report /* FROM STDIN */ TO STDOUT;".as_slice(),
2170        ] {
2171            assert!(
2172                !has_postgres_copy_stdin_source(stmt),
2173                "unexpected COPY data mode for {stmt:?}"
2174            );
2175        }
2176    }
2177
2178    #[test]
2179    fn copy_source_detection_accepts_comments_between_source_tokens() {
2180        let stmt = b"COPY report (id) /* source */ FROM /* terminal */ STDIN;";
2181        assert!(has_postgres_copy_stdin_source(stmt));
2182    }
2183
2184    #[test]
2185    fn copy_start_skip_statement_skips_rows_and_reaches_following_statement() {
2186        let sql = b"COPY report (id) FROM STDIN;\n1\n2\n\\.\nSELECT 42;";
2187        let mut parser = Parser::with_dialect(&sql[..], 8, SqlDialect::Postgres);
2188        let mut events = Vec::new();
2189
2190        parser
2191            .visit_events(|event| match event {
2192                ParserEvent::CopyStart(_) => {
2193                    events.push("start");
2194                    Ok(RowFlow::SkipStatement)
2195                }
2196                ParserEvent::CopyRow(_) => {
2197                    events.push("row");
2198                    Ok(RowFlow::Continue)
2199                }
2200                ParserEvent::CopyEnd => {
2201                    events.push("end");
2202                    Ok(RowFlow::Continue)
2203                }
2204                ParserEvent::Statement(stmt) => {
2205                    assert_eq!(stmt, b"SELECT 42;");
2206                    events.push("statement");
2207                    Ok(RowFlow::Continue)
2208                }
2209                ParserEvent::InsertRow { .. } => unreachable!("unexpected INSERT event"),
2210            })
2211            .unwrap();
2212
2213        assert_eq!(events, ["start", "end", "statement"]);
2214    }
2215
2216    #[test]
2217    fn parser_retains_qualified_copy_names() {
2218        let cases = [
2219            (
2220                b"COPY public.users (id) FROM STDIN;".as_slice(),
2221                "public.users",
2222            ),
2223            (
2224                b"COPY \"tenant_a\".\"users\" (id) FROM STDIN;".as_slice(),
2225                "tenant_a.users",
2226            ),
2227            (
2228                b"COPY public.\"user.log\" (id) FROM STDIN;".as_slice(),
2229                "public.\"user.log\"",
2230            ),
2231        ];
2232
2233        for (stmt, expected) in cases {
2234            let (kind, name) =
2235                Parser::<&[u8]>::parse_statement_with_dialect(stmt, SqlDialect::Postgres);
2236            assert_eq!(kind, StatementType::Copy);
2237            assert_eq!(name, expected);
2238        }
2239    }
2240
2241    #[test]
2242    fn parser_retains_qualified_mssql_index_names() {
2243        for stmt in [
2244            b"CREATE INDEX users_email_idx ON [dbo].[users] ([email]);".as_slice(),
2245            b"CREATE INDEX users_email_idx ON dbo.users (email);".as_slice(),
2246        ] {
2247            let (kind, name) =
2248                Parser::<&[u8]>::parse_statement_with_dialect(stmt, SqlDialect::Mssql);
2249            assert_eq!(kind, StatementType::CreateIndex);
2250            assert_eq!(name, "dbo.users");
2251        }
2252    }
2253
2254    #[test]
2255    fn parser_normalizes_quoted_qualified_generic_index_names() {
2256        let (kind, name) = Parser::<&[u8]>::parse_statement_with_dialect(
2257            b"CREATE INDEX users_email_idx ON \"tenant_a\".\"users\" (email);",
2258            SqlDialect::Postgres,
2259        );
2260        assert_eq!(kind, StatementType::CreateIndex);
2261        assert_eq!(name, "tenant_a.users");
2262    }
2263
2264    #[test]
2265    fn parser_streams_mssql_temporary_table_insert_rows() {
2266        let sql = b"INSERT INTO #daily_users (id) VALUES (1), (2);";
2267        let mut parser = Parser::with_dialect(&sql[..], 8, SqlDialect::Mssql);
2268        let mut rows = 0;
2269
2270        parser
2271            .visit_events(|event| match event {
2272                ParserEvent::InsertRow { .. } => {
2273                    rows += 1;
2274                    Ok(RowFlow::Continue)
2275                }
2276                ParserEvent::Statement(_) | ParserEvent::CopyStart(_) | ParserEvent::CopyEnd => {
2277                    Ok(RowFlow::Continue)
2278                }
2279                ParserEvent::CopyRow(_) => unreachable!("unexpected COPY row"),
2280            })
2281            .unwrap();
2282
2283        assert_eq!(rows, 2);
2284    }
2285}