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