sql_splitter/parser/mod.rs
1pub mod mysql_insert;
2pub mod postgres_copy;
3
4// Re-export types for bulk loading (consumed by the duckdb loader and by
5// library users; the bin target without duckdb-query doesn't use them)
6#[cfg_attr(not(feature = "duckdb-query"), allow(unused_imports))]
7pub use mysql_insert::{parse_insert_for_bulk, ParsedValue};
8
9use once_cell::sync::Lazy;
10use regex::bytes::Regex;
11use std::io::{BufRead, BufReader, Read};
12
13pub const SMALL_BUFFER_SIZE: usize = 64 * 1024;
14pub const MEDIUM_BUFFER_SIZE: usize = 256 * 1024;
15
16/// SQL dialect for parser behavior
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
18pub enum SqlDialect {
19 /// MySQL/MariaDB mysqldump format (backtick quoting, backslash escapes)
20 #[default]
21 MySql,
22 /// PostgreSQL pg_dump format (double-quote identifiers, COPY FROM stdin, dollar-quoting)
23 Postgres,
24 /// SQLite .dump format (double-quote identifiers, '' escapes)
25 Sqlite,
26 /// Microsoft SQL Server / T-SQL (square bracket identifiers, GO batches, N'unicode' strings)
27 Mssql,
28}
29
30impl std::str::FromStr for SqlDialect {
31 type Err = String;
32
33 fn from_str(s: &str) -> Result<Self, Self::Err> {
34 match s.to_lowercase().as_str() {
35 "mysql" | "mariadb" => Ok(SqlDialect::MySql),
36 "postgres" | "postgresql" | "pg" => Ok(SqlDialect::Postgres),
37 "sqlite" | "sqlite3" => Ok(SqlDialect::Sqlite),
38 "mssql" | "sqlserver" | "sql_server" | "tsql" => Ok(SqlDialect::Mssql),
39 _ => Err(format!(
40 "Unknown dialect: {}. Valid options: mysql, postgres, sqlite, mssql",
41 s
42 )),
43 }
44 }
45}
46
47impl std::fmt::Display for SqlDialect {
48 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
49 match self {
50 SqlDialect::MySql => write!(f, "mysql"),
51 SqlDialect::Postgres => write!(f, "postgres"),
52 SqlDialect::Sqlite => write!(f, "sqlite"),
53 SqlDialect::Mssql => write!(f, "mssql"),
54 }
55 }
56}
57
58/// Result of dialect auto-detection
59#[derive(Debug, Clone)]
60pub struct DialectDetectionResult {
61 pub dialect: SqlDialect,
62 pub confidence: DialectConfidence,
63}
64
65/// Confidence level of dialect detection
66#[derive(Debug, Clone, Copy, PartialEq, Eq)]
67pub enum DialectConfidence {
68 /// High confidence - found definitive markers (e.g., "pg_dump", "MySQL dump")
69 High,
70 /// Medium confidence - found likely markers
71 Medium,
72 /// Low confidence - defaulting to MySQL
73 Low,
74}
75
76#[derive(Default)]
77struct DialectScore {
78 mysql: u32,
79 postgres: u32,
80 sqlite: u32,
81 mssql: u32,
82}
83
84/// Detect SQL dialect from file header content.
85/// Reads up to 8KB and looks for dialect-specific markers.
86pub fn detect_dialect(header: &[u8]) -> DialectDetectionResult {
87 let mut score = DialectScore::default();
88
89 // Simple "substring present => add weight to a dialect" markers. Confidence
90 // is encoded by the weight: 20/10 = high, 5 = medium, 2 = low.
91 const MARKERS: &[(&[u8], SqlDialect, u32)] = &[
92 (b"pg_dump", SqlDialect::Postgres, 10),
93 (b"PostgreSQL database dump", SqlDialect::Postgres, 10),
94 (b"MySQL dump", SqlDialect::MySql, 10),
95 (b"MariaDB dump", SqlDialect::MySql, 10),
96 (b"SQLite", SqlDialect::Sqlite, 10),
97 (b"search_path", SqlDialect::Postgres, 5),
98 (b"LOCK TABLES", SqlDialect::MySql, 5),
99 (b"PRAGMA", SqlDialect::Sqlite, 5),
100 (b"CREATE EXTENSION", SqlDialect::Postgres, 2),
101 // BEGIN TRANSACTION is generic ANSI SQL, only slightly suggests SQLite
102 (b"BEGIN TRANSACTION", SqlDialect::Sqlite, 2),
103 (b"SET ANSI_NULLS", SqlDialect::Mssql, 20),
104 (b"SET QUOTED_IDENTIFIER", SqlDialect::Mssql, 20),
105 (b"IDENTITY(", SqlDialect::Mssql, 10),
106 (b"ON [PRIMARY]", SqlDialect::Mssql, 10),
107 (b"NVARCHAR", SqlDialect::Mssql, 5),
108 (b"CLUSTERED", SqlDialect::Mssql, 5),
109 (b"SET NOCOUNT", SqlDialect::Mssql, 5),
110 ];
111 for &(needle, dialect, weight) in MARKERS {
112 if contains_bytes(header, needle) {
113 match dialect {
114 SqlDialect::MySql => score.mysql += weight,
115 SqlDialect::Postgres => score.postgres += weight,
116 SqlDialect::Sqlite => score.sqlite += weight,
117 SqlDialect::Mssql => score.mssql += weight,
118 }
119 }
120 }
121
122 // Compound / structural markers that don't fit the simple table.
123 if contains_bytes(header, b"COPY ") && contains_bytes(header, b"FROM stdin") {
124 score.postgres += 5;
125 }
126 if contains_bytes(header, b"/*!40") || contains_bytes(header, b"/*!50") {
127 score.mysql += 5;
128 }
129 if contains_bytes(header, b"$$") {
130 score.postgres += 2;
131 }
132 // Backticks suggest MySQL (could also appear in data/comments)
133 if header.contains(&b'`') {
134 score.mysql += 2;
135 }
136 // GO as batch separator on its own line (check for common patterns)
137 if contains_bytes(header, b"\nGO\n") || contains_bytes(header, b"\nGO\r\n") {
138 score.mssql += 15;
139 }
140 // Square-bracket identifiers, but distinguish them from PostgreSQL array
141 // types: `[id]`/`[dbo]` (identifier-shaped) => MSSQL; `integer[]` (empty)
142 // or `[5]` (non-identifier) => not MSSQL (bug #9).
143 {
144 let mut mssql_bracket_ident = false;
145 let mut pg_array_brackets = false;
146 let mut k = 0;
147 while k < header.len() {
148 if header[k] == b'[' {
149 if let Some(rel) = header[k + 1..].iter().position(|&c| c == b']') {
150 let inner = &header[k + 1..k + 1 + rel];
151 let ident_shaped = inner
152 .first()
153 .is_some_and(|&c| c.is_ascii_alphabetic() || c == b'_')
154 && inner
155 .iter()
156 .all(|&c| c.is_ascii_alphanumeric() || c == b'_' || c == b' ');
157 if inner.is_empty() {
158 pg_array_brackets = true;
159 } else if ident_shaped {
160 mssql_bracket_ident = true;
161 }
162 k += rel + 2;
163 continue;
164 }
165 }
166 k += 1;
167 }
168 if mssql_bracket_ident {
169 score.mssql += 10;
170 }
171 if pg_array_brackets {
172 score.postgres += 2;
173 }
174 }
175
176 // N'unicode' literal — require a non-word char before N so ordinary data
177 // ending in N before a quote (e.g. ...JOHN') doesn't score MSSQL (bug #9).
178 {
179 let mut k = 0;
180 while k + 1 < header.len() {
181 if header[k] == b'N' && header[k + 1] == b'\'' {
182 let before_ok =
183 k == 0 || !(header[k - 1].is_ascii_alphanumeric() || header[k - 1] == b'_');
184 if before_ok {
185 score.mssql += 5;
186 break;
187 }
188 }
189 k += 1;
190 }
191 }
192
193 // Determine winner and confidence
194 let max_score = score
195 .mysql
196 .max(score.postgres)
197 .max(score.sqlite)
198 .max(score.mssql);
199
200 if max_score == 0 {
201 return DialectDetectionResult {
202 dialect: SqlDialect::MySql,
203 confidence: DialectConfidence::Low,
204 };
205 }
206
207 // Find the dialect with the highest score
208 let (dialect, winning_score) = if score.mssql > score.mysql
209 && score.mssql > score.postgres
210 && score.mssql > score.sqlite
211 {
212 (SqlDialect::Mssql, score.mssql)
213 } else if score.postgres > score.mysql && score.postgres > score.sqlite {
214 (SqlDialect::Postgres, score.postgres)
215 } else if score.sqlite > score.mysql {
216 (SqlDialect::Sqlite, score.sqlite)
217 } else {
218 (SqlDialect::MySql, score.mysql)
219 };
220
221 // Determine confidence based on winning score
222 let confidence = if winning_score >= 10 {
223 DialectConfidence::High
224 } else if winning_score >= 5 {
225 DialectConfidence::Medium
226 } else {
227 DialectConfidence::Low
228 };
229
230 DialectDetectionResult {
231 dialect,
232 confidence,
233 }
234}
235
236/// Detect dialect from a file, reading its first 8KB. Goes through
237/// [`crate::splitter::open_input`] so compressed and zipped inputs are
238/// transparently decoded before sniffing — without that, detection would
239/// see raw compressed bytes instead of SQL text.
240pub fn detect_dialect_from_file(path: &std::path::Path) -> anyhow::Result<DialectDetectionResult> {
241 use std::io::Read;
242
243 let mut reader = crate::splitter::open_input(path)?;
244 let mut buf = [0u8; 8192];
245 let n = reader.read(&mut buf)?;
246 Ok(detect_dialect(&buf[..n]))
247}
248
249#[inline]
250fn contains_bytes(haystack: &[u8], needle: &[u8]) -> bool {
251 memchr::memmem::find(haystack, needle).is_some()
252}
253
254/// Check if a line is a MSSQL GO batch separator
255/// GO must be on its own line (with optional whitespace and optional repeat count)
256/// Examples: "GO\n", " GO \n", "GO 100\n", "go\r\n"
257fn is_go_line(line: &[u8]) -> bool {
258 // Trim leading whitespace
259 let mut start = 0;
260 while start < line.len()
261 && (line[start] == b' ' || line[start] == b'\t' || line[start] == b'\r')
262 {
263 start += 1;
264 }
265
266 // Trim trailing whitespace and newlines
267 let mut end = line.len();
268 while end > start
269 && (line[end - 1] == b' '
270 || line[end - 1] == b'\t'
271 || line[end - 1] == b'\r'
272 || line[end - 1] == b'\n')
273 {
274 end -= 1;
275 }
276
277 let trimmed = &line[start..end];
278
279 if trimmed.len() < 2 {
280 return false;
281 }
282
283 // Check for "GO" (case-insensitive)
284 if trimmed.len() == 2 {
285 return (trimmed[0] == b'G' || trimmed[0] == b'g')
286 && (trimmed[1] == b'O' || trimmed[1] == b'o');
287 }
288
289 // Check for "GO <number>" pattern
290 if (trimmed[0] == b'G' || trimmed[0] == b'g')
291 && (trimmed[1] == b'O' || trimmed[1] == b'o')
292 && (trimmed[2] == b' ' || trimmed[2] == b'\t')
293 {
294 // Rest should be whitespace and digits (allocation-free scan)
295 return trimmed[3..]
296 .iter()
297 .skip_while(|&&b| b == b' ' || b == b'\t')
298 .all(|&b| b.is_ascii_digit());
299 }
300
301 false
302}
303
304#[derive(Debug, Clone, Copy, PartialEq, Eq)]
305pub enum StatementType {
306 Unknown,
307 CreateTable,
308 Insert,
309 CreateIndex,
310 AlterTable,
311 DropTable,
312 /// PostgreSQL COPY FROM stdin
313 Copy,
314}
315
316impl StatementType {
317 /// Returns true if this is a schema-related statement (DDL)
318 pub fn is_schema(&self) -> bool {
319 matches!(
320 self,
321 StatementType::CreateTable
322 | StatementType::CreateIndex
323 | StatementType::AlterTable
324 | StatementType::DropTable
325 )
326 }
327
328 /// Returns true if this is a data-related statement (DML)
329 pub fn is_data(&self) -> bool {
330 matches!(self, StatementType::Insert | StatementType::Copy)
331 }
332}
333
334/// Content filter mode for splitting
335#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
336pub enum ContentFilter {
337 /// Include both schema and data statements (default)
338 #[default]
339 All,
340 /// Only schema statements (CREATE TABLE, CREATE INDEX, ALTER TABLE, DROP TABLE)
341 SchemaOnly,
342 /// Only data statements (INSERT, COPY)
343 DataOnly,
344}
345
346// Word boundary before ON so index names ending in "on" (idx_position,
347// idx_created_on, ...) don't match the "on" inside the identifier.
348static CREATE_INDEX_RE: Lazy<Regex> =
349 Lazy::new(|| Regex::new(r"(?i)\bON\s+`?([^\s`(;]+)`?").unwrap());
350
351// MSSQL CREATE INDEX: extracts table from ON [schema].[table] or ON [table]
352// Matches: ON [table], ON [dbo].[table], ON [db].[dbo].[table]
353// Captures the last bracketed or unbracketed identifier before (
354static CREATE_INDEX_MSSQL_RE: Lazy<Regex> =
355 Lazy::new(|| Regex::new(r"(?i)ON\s+(?:\[?[^\[\]\s]+\]?\s*\.\s*)*\[([^\[\]]+)\]").unwrap());
356
357static ALTER_TABLE_RE: Lazy<Regex> =
358 Lazy::new(|| Regex::new(r"(?i)ALTER\s+TABLE\s+`?([^\s`;]+)`?").unwrap());
359
360static DROP_TABLE_RE: Lazy<Regex> = Lazy::new(|| {
361 Regex::new(r#"(?i)DROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?[`"]?([^\s`"`;]+)[`"]?"#).unwrap()
362});
363
364// PostgreSQL COPY statement regex
365static COPY_RE: Lazy<Regex> =
366 Lazy::new(|| Regex::new(r#"(?i)^\s*COPY\s+(?:ONLY\s+)?[`"]?([^\s`"(]+)[`"]?"#).unwrap());
367
368// More flexible table name regex that handles:
369// - Backticks: `table`
370// - Double quotes: "table"
371// - Schema qualified: schema.table, `schema`.`table`, "schema"."table"
372// - IF NOT EXISTS
373static CREATE_TABLE_FLEXIBLE_RE: Lazy<Regex> = Lazy::new(|| {
374 Regex::new(r#"(?i)^\s*CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(?:[`"]?[\w]+[`"]?\s*\.\s*)?[`"]?([\w]+)[`"]?"#).unwrap()
375});
376
377static INSERT_FLEXIBLE_RE: Lazy<Regex> = Lazy::new(|| {
378 Regex::new(
379 r#"(?i)^\s*INSERT\s+INTO\s+(?:ONLY\s+)?(?:[`"]?[\w]+[`"]?\s*\.\s*)?[`"]?([\w]+)[`"]?"#,
380 )
381 .unwrap()
382});
383
384/// Result of peeking at the byte after position `i` for a two-byte token
385/// (`--`, `/*`, `*/`, `]]`). See [`Parser::peek2`].
386#[derive(Clone, Copy, PartialEq, Eq)]
387enum Peek2 {
388 /// The next byte is present and matches: the token is complete.
389 Hit,
390 /// The next byte differs, or input ended at EOF (a dangling first byte at
391 /// the tail is treated as a literal byte).
392 Miss,
393 /// The buffer ends here but more input may arrive: the caller must pause
394 /// the scan (`break 'scan`) with its state intact so the token can never
395 /// straddle a refill (see the `buf` field docs).
396 NeedMore,
397}
398
399/// 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 // Strip leading comments (pg_dump adds -- comments before COPY statements)
1069 let stmt = strip_leading_comments_and_whitespace(stmt);
1070 if stmt.len() < 17 {
1071 // Minimum: "COPY x FROM STDIN" = 17 chars
1072 return false;
1073 }
1074
1075 // Check prefix with stack-allocated buffer (avoid heap allocation)
1076 let mut prefix = [0u8; 5];
1077 for (i, &b) in stmt.iter().take(5).enumerate() {
1078 prefix[i] = b.to_ascii_uppercase();
1079 }
1080 if &prefix != b"COPY " {
1081 return false;
1082 }
1083
1084 // Search for "FROM STDIN" case-insensitively without allocating
1085 // Look within first 500 bytes (typical COPY statements are shorter)
1086 let search_len = stmt.len().min(500);
1087 if search_len >= 10 {
1088 // Inclusive upper bound so a "FROM STDIN" ending exactly at the
1089 // window edge isn't missed.
1090 for i in 0..=(search_len - 10) {
1091 if stmt[i..i + 10]
1092 .iter()
1093 .zip(b"FROM STDIN".iter())
1094 .all(|(&a, &b)| a.to_ascii_uppercase() == b)
1095 {
1096 return true;
1097 }
1098 }
1099 }
1100 false
1101 }
1102
1103 /// Read PostgreSQL COPY data block until we see the terminator line (\.).
1104 /// The returned block includes everything up to and including the
1105 /// terminator line; anything after it is carried in `pending`.
1106 ///
1107 /// Note: a COPY block is buffered whole in memory (like every other
1108 /// statement here) — its size sets the memory floor for a pg_dump with one
1109 /// very large table. This is intentional: downstream consumers (redact,
1110 /// diff, sample) operate on a full block at a time.
1111 fn read_copy_data(&mut self) -> std::io::Result<Option<Vec<u8>>> {
1112 let mut start = self.buf_pos;
1113 let mut scan = self.buf_pos;
1114
1115 loop {
1116 // Scan completed lines for the terminator.
1117 while let Some(rel) = memchr::memchr(b'\n', &self.buf[scan..]) {
1118 let nl = scan + rel;
1119 let line = &self.buf[scan..=nl];
1120 if line == b"\\.\n" || line == b"\\.\r\n" {
1121 self.in_copy_data = false;
1122 let result = self.buf[start..=nl].to_vec();
1123 self.buf_pos = nl + 1;
1124 return Ok(Some(result));
1125 }
1126 scan = nl + 1;
1127 }
1128
1129 let (removed, got_more) = self.grow_buffer(start)?;
1130 start -= removed;
1131 scan -= removed;
1132 if !got_more {
1133 self.in_copy_data = false;
1134 if start >= self.buf.len() {
1135 return Ok(None);
1136 }
1137 let result = self.buf[start..].to_vec();
1138 self.buf_pos = self.buf.len();
1139 return Ok(Some(result));
1140 }
1141 }
1142 }
1143
1144 /// Stream the input as [`ParserEvent`]s with bounded memory.
1145 ///
1146 /// Ordinary DDL/control statements are buffered whole (they are small) and
1147 /// delivered as [`ParserEvent::Statement`]. A multi-row INSERT is delivered
1148 /// as its header plus one [`ParserEvent::InsertRow`] per tuple, and a COPY
1149 /// block as [`ParserEvent::CopyStart`] / [`ParserEvent::CopyRow`] per line /
1150 /// [`ParserEvent::CopyEnd`] — the whole multi-row block is never buffered at
1151 /// once. The callback must consume each borrowed slice before returning.
1152 ///
1153 /// Unlike [`read_statement`](Self::read_statement) (kept for compatibility),
1154 /// data statements are not routed through it: their rows are streamed.
1155 pub fn visit_events<F>(&mut self, mut on_event: F) -> anyhow::Result<()>
1156 where
1157 F: FnMut(ParserEvent<'_>) -> anyhow::Result<RowFlow>,
1158 {
1159 loop {
1160 // Ensure at least one byte at/after buf_pos, or stop at EOF.
1161 while self.buf_pos >= self.buf.len() {
1162 let (removed, more) = self.grow_buffer(self.buf_pos)?;
1163 self.buf_pos -= removed;
1164 if !more {
1165 return Ok(());
1166 }
1167 }
1168
1169 if self.peek_is_insert()? {
1170 if self.visit_insert_stmt(&mut on_event)? == RowFlow::Stop {
1171 return Ok(());
1172 }
1173 continue;
1174 }
1175
1176 // Non-INSERT: reuse read_statement to consume one DDL/control or
1177 // COPY header statement (small). COPY data blocks are then streamed
1178 // line-by-line rather than buffered whole.
1179 let stmt = match self.read_statement()? {
1180 Some(s) => s,
1181 None => return Ok(()),
1182 };
1183 if self.in_copy_data {
1184 self.in_copy_data = false;
1185 if on_event(ParserEvent::CopyStart(&stmt))? == RowFlow::Stop {
1186 return Ok(());
1187 }
1188 if self.visit_copy_data(&mut on_event)? == RowFlow::Stop {
1189 return Ok(());
1190 }
1191 } else if on_event(ParserEvent::Statement(&stmt))? == RowFlow::Stop {
1192 return Ok(());
1193 }
1194 }
1195 }
1196
1197 /// Peek whether the next statement (after leading comments/whitespace) is an
1198 /// `INSERT INTO`/`INSERT ONLY`, growing the buffer just enough to decide.
1199 fn peek_is_insert(&mut self) -> anyhow::Result<bool> {
1200 loop {
1201 let stripped = strip_leading_comments_and_whitespace(&self.buf[self.buf_pos..]);
1202 if stripped.len() >= 11 {
1203 return Ok(starts_with_insert(stripped));
1204 }
1205 if self.buf.len() - self.buf_pos > self.limits.max_header {
1206 anyhow::bail!(
1207 "statement header exceeds max_header ({} bytes) at input offset {}",
1208 self.limits.max_header,
1209 self.base + self.buf_pos as u64
1210 );
1211 }
1212 let (removed, more) = self.grow_buffer(self.buf_pos)?;
1213 self.buf_pos -= removed;
1214 if !more {
1215 let stripped = strip_leading_comments_and_whitespace(&self.buf[self.buf_pos..]);
1216 return Ok(starts_with_insert(stripped));
1217 }
1218 }
1219 }
1220
1221 /// Stream one INSERT statement's tuples as [`ParserEvent::InsertRow`]s.
1222 fn visit_insert_stmt<F>(&mut self, on_event: &mut F) -> anyhow::Result<RowFlow>
1223 where
1224 F: FnMut(ParserEvent<'_>) -> anyhow::Result<RowFlow>,
1225 {
1226 // Locate the VALUES keyword, buffering only the header (bounded). The
1227 // scan stops at the statement's own `;`, so a VALUES-less INSERT
1228 // (INSERT … SELECT / SET) is emitted whole rather than absorbing later
1229 // statements while hunting for a VALUES that belongs to one of them.
1230 let (header, values_abs) = loop {
1231 let stripped_len =
1232 strip_leading_comments_and_whitespace(&self.buf[self.buf_pos..]).len();
1233 let start = self.buf.len() - stripped_len;
1234 match mysql_insert::scan_insert_header(&self.buf[start..]) {
1235 mysql_insert::HeaderScan::Values(vp) => {
1236 let values_abs = start + vp;
1237 break (self.buf[start..values_abs].to_vec(), values_abs);
1238 }
1239 mysql_insert::HeaderScan::NoValues(end_off) => {
1240 // Emit the whole statement (up to and including its `;`) as
1241 // an opaque Statement; there are no rows to stream.
1242 let stmt_end = start + end_off;
1243 let flow = on_event(ParserEvent::Statement(&self.buf[self.buf_pos..stmt_end]))?;
1244 self.buf_pos = stmt_end;
1245 return Ok(flow);
1246 }
1247 mysql_insert::HeaderScan::Incomplete => {
1248 if self.buf.len() - self.buf_pos > self.limits.max_header {
1249 anyhow::bail!(
1250 "INSERT header exceeds max_header ({} bytes) at input offset {}",
1251 self.limits.max_header,
1252 self.base + self.buf_pos as u64
1253 );
1254 }
1255 let (removed, more) = self.grow_buffer(self.buf_pos)?;
1256 self.buf_pos -= removed;
1257 if !more {
1258 // Truncated header at EOF: emit the remaining bytes as an
1259 // opaque statement so nothing is lost.
1260 let flow = on_event(ParserEvent::Statement(&self.buf[self.buf_pos..]))?;
1261 self.buf_pos = self.buf.len();
1262 return Ok(flow);
1263 }
1264 }
1265 }
1266 };
1267
1268 let mut cur = values_abs;
1269 let mut first = true;
1270 let mut skipping = false;
1271
1272 loop {
1273 // Skip inter-tuple whitespace and commas.
1274 loop {
1275 while cur < self.buf.len()
1276 && matches!(self.buf[cur], b' ' | b'\t' | b'\n' | b'\r' | b',')
1277 {
1278 cur += 1;
1279 }
1280 if cur < self.buf.len() {
1281 break;
1282 }
1283 let (removed, more) = self.grow_buffer(cur)?;
1284 cur -= removed;
1285 if !more {
1286 break;
1287 }
1288 }
1289
1290 if cur >= self.buf.len() {
1291 self.buf_pos = self.buf.len();
1292 return Ok(RowFlow::Continue);
1293 }
1294 match self.buf[cur] {
1295 b';' => {
1296 self.buf_pos = cur + 1;
1297 return Ok(RowFlow::Continue);
1298 }
1299 b'(' => {}
1300 // Anything else (e.g. an MSSQL GO batch line) ends the INSERT;
1301 // leave it for the next statement.
1302 _ => {
1303 self.buf_pos = cur;
1304 return Ok(RowFlow::Continue);
1305 }
1306 }
1307
1308 // Scan exactly one tuple, growing until it is complete or EOF.
1309 let (tuple_end, complete) = loop {
1310 if self.buf.len() - cur > self.limits.max_row {
1311 anyhow::bail!(
1312 "INSERT row exceeds max_row ({} bytes) at input offset {}",
1313 self.limits.max_row,
1314 self.base + cur as u64
1315 );
1316 }
1317 match mysql_insert::scan_insert_tuple(&self.buf[cur..], self.dialect) {
1318 Some((len, true)) => break (cur + len, true),
1319 Some(_) => {
1320 let (removed, more) = self.grow_buffer(cur)?;
1321 cur -= removed;
1322 if !more {
1323 break (self.buf.len(), false);
1324 }
1325 }
1326 None => {
1327 self.buf_pos = cur;
1328 return Ok(RowFlow::Continue);
1329 }
1330 }
1331 };
1332
1333 if skipping {
1334 cur = tuple_end;
1335 } else {
1336 let flow = on_event(ParserEvent::InsertRow {
1337 header: &header,
1338 row: &self.buf[cur..tuple_end],
1339 first_in_statement: first,
1340 })?;
1341 first = false;
1342 match flow {
1343 RowFlow::Continue => cur = tuple_end,
1344 RowFlow::SkipStatement => {
1345 skipping = true;
1346 cur = tuple_end;
1347 }
1348 RowFlow::Stop => {
1349 self.buf_pos = tuple_end;
1350 return Ok(RowFlow::Stop);
1351 }
1352 }
1353 }
1354
1355 if !complete {
1356 self.buf_pos = self.buf.len();
1357 return Ok(RowFlow::Continue);
1358 }
1359 }
1360 }
1361
1362 /// Stream a COPY data block (positioned just past the header's `;`) as
1363 /// [`ParserEvent::CopyRow`]s followed by [`ParserEvent::CopyEnd`].
1364 fn visit_copy_data<F>(&mut self, on_event: &mut F) -> anyhow::Result<RowFlow>
1365 where
1366 F: FnMut(ParserEvent<'_>) -> anyhow::Result<RowFlow>,
1367 {
1368 // Consume the line terminator that ends the `COPY ... FROM stdin;`
1369 // header line (read_statement stopped at the `;`), so the first emitted
1370 // CopyRow is a real data line rather than a phantom empty one.
1371 for &want in b"\r\n" {
1372 while self.buf_pos >= self.buf.len() {
1373 let (removed, more) = self.grow_buffer(self.buf_pos)?;
1374 self.buf_pos -= removed;
1375 if !more {
1376 return Ok(RowFlow::Continue);
1377 }
1378 }
1379 if self.buf[self.buf_pos] == want {
1380 self.buf_pos += 1;
1381 }
1382 }
1383
1384 let mut ls = self.buf_pos;
1385 let mut skipping = false;
1386
1387 loop {
1388 let nl = loop {
1389 if let Some(rel) = memchr::memchr(b'\n', &self.buf[ls..]) {
1390 break Some(ls + rel);
1391 }
1392 if self.buf.len() - ls > self.limits.max_row {
1393 anyhow::bail!(
1394 "COPY line exceeds max_row ({} bytes) at input offset {}",
1395 self.limits.max_row,
1396 self.base + ls as u64
1397 );
1398 }
1399 let (removed, more) = self.grow_buffer(ls)?;
1400 ls -= removed;
1401 if !more {
1402 break None;
1403 }
1404 };
1405
1406 if nl.is_none() && ls >= self.buf.len() {
1407 // EOF with no trailing data.
1408 self.buf_pos = self.buf.len();
1409 return Ok(RowFlow::Continue);
1410 }
1411
1412 let line_end = nl.unwrap_or(self.buf.len());
1413 let line = &self.buf[ls..line_end];
1414 let check: &[u8] = if line.last() == Some(&b'\r') {
1415 &line[..line.len() - 1]
1416 } else {
1417 line
1418 };
1419
1420 if check == b"\\." {
1421 let flow = on_event(ParserEvent::CopyEnd)?;
1422 self.buf_pos = nl.map(|n| n + 1).unwrap_or(self.buf.len());
1423 return Ok(flow);
1424 }
1425
1426 if !skipping {
1427 match on_event(ParserEvent::CopyRow(line))? {
1428 RowFlow::Continue => {}
1429 RowFlow::SkipStatement => skipping = true,
1430 RowFlow::Stop => {
1431 self.buf_pos = nl.map(|n| n + 1).unwrap_or(self.buf.len());
1432 return Ok(RowFlow::Stop);
1433 }
1434 }
1435 }
1436
1437 match nl {
1438 Some(n) => ls = n + 1,
1439 None => {
1440 self.buf_pos = self.buf.len();
1441 return Ok(RowFlow::Continue);
1442 }
1443 }
1444 }
1445 }
1446
1447 /// Read MSSQL statement with GO batch separator support.
1448 /// GO is a batch separator that appears on its own line; `;` also
1449 /// terminates. Uses the same `buf` + cursor model as [`read_statement`] so
1450 /// tokens can't straddle a chunk boundary and scanning stays O(n).
1451 fn read_statement_mssql(&mut self) -> std::io::Result<Option<Vec<u8>>> {
1452 let mut start = self.buf_pos;
1453 let mut i = self.buf_pos;
1454 let mut line_start = self.buf_pos;
1455
1456 let mut inside_single_quote = false;
1457 let mut inside_bracket_quote = false;
1458 let mut in_line_comment = false;
1459 let mut in_block_comment = false;
1460 let mut at_eof = false;
1461
1462 loop {
1463 'scan: while i < self.buf.len() {
1464 let b = self.buf[i];
1465
1466 if in_block_comment {
1467 if b == b'*' {
1468 match self.peek2(i, b'/', at_eof) {
1469 Peek2::Hit => {
1470 in_block_comment = false;
1471 i += 2;
1472 continue;
1473 }
1474 Peek2::Miss => {
1475 i += 1;
1476 continue;
1477 }
1478 Peek2::NeedMore => break 'scan,
1479 }
1480 }
1481 i += 1;
1482 continue;
1483 }
1484
1485 if in_line_comment {
1486 if b == b'\n' {
1487 in_line_comment = false;
1488 line_start = i + 1;
1489 }
1490 i += 1;
1491 continue;
1492 }
1493
1494 if inside_bracket_quote {
1495 if b == b']' {
1496 match self.peek2(i, b']', at_eof) {
1497 // Escaped ]] stays inside the identifier (bug #8)
1498 Peek2::Hit => {
1499 i += 2;
1500 continue;
1501 }
1502 Peek2::Miss => {
1503 inside_bracket_quote = false;
1504 i += 1;
1505 continue;
1506 }
1507 Peek2::NeedMore => break 'scan,
1508 }
1509 }
1510 i += 1;
1511 continue;
1512 }
1513
1514 if inside_single_quote {
1515 // Fast-skip to the closing quote (MSSQL has no `\` escapes).
1516 match memchr::memchr(b'\'', &self.buf[i..]) {
1517 Some(0) => inside_single_quote = false,
1518 Some(off) => {
1519 i += off;
1520 continue;
1521 }
1522 None if at_eof => {
1523 i = self.buf.len();
1524 continue;
1525 }
1526 None => break 'scan,
1527 }
1528 i += 1;
1529 continue;
1530 }
1531
1532 // Outside strings/comments.
1533 if b == b'-' {
1534 match self.peek2(i, b'-', at_eof) {
1535 Peek2::Hit => {
1536 in_line_comment = true;
1537 i += 2;
1538 continue;
1539 }
1540 Peek2::Miss => {
1541 i += 1;
1542 continue;
1543 }
1544 Peek2::NeedMore => break 'scan,
1545 }
1546 }
1547 if b == b'/' {
1548 match self.peek2(i, b'*', at_eof) {
1549 Peek2::Hit => {
1550 in_block_comment = true;
1551 i += 2;
1552 continue;
1553 }
1554 Peek2::Miss => {
1555 i += 1;
1556 continue;
1557 }
1558 Peek2::NeedMore => break 'scan,
1559 }
1560 }
1561 if b == b'\'' {
1562 inside_single_quote = true;
1563 i += 1;
1564 continue;
1565 }
1566 if b == b'[' {
1567 inside_bracket_quote = true;
1568 i += 1;
1569 continue;
1570 }
1571 if b == b';' {
1572 let result = self.buf[start..=i].to_vec();
1573 self.buf_pos = i + 1;
1574 return Ok(Some(result));
1575 }
1576 if b == b'\n' {
1577 if is_go_line(&self.buf[line_start..=i]) {
1578 // Trim trailing whitespace before the GO line.
1579 let mut stmt_end = line_start;
1580 while stmt_end > start
1581 && matches!(self.buf[stmt_end - 1], b'\n' | b'\r' | b' ' | b'\t')
1582 {
1583 stmt_end -= 1;
1584 }
1585 self.buf_pos = i + 1;
1586 if stmt_end > start {
1587 return Ok(Some(self.buf[start..stmt_end].to_vec()));
1588 }
1589 // Empty batch: start a new statement after the GO line.
1590 start = i + 1;
1591 line_start = i + 1;
1592 i += 1;
1593 continue;
1594 }
1595 line_start = i + 1;
1596 i += 1;
1597 continue;
1598 }
1599
1600 i += 1;
1601 }
1602
1603 if at_eof {
1604 if start >= self.buf.len() {
1605 return Ok(None);
1606 }
1607 // Handle a trailing GO with no final newline (bug #12).
1608 if is_go_line(&self.buf[line_start..]) {
1609 let mut stmt_end = line_start;
1610 while stmt_end > start
1611 && matches!(self.buf[stmt_end - 1], b'\n' | b'\r' | b' ' | b'\t')
1612 {
1613 stmt_end -= 1;
1614 }
1615 self.buf_pos = self.buf.len();
1616 if stmt_end > start {
1617 return Ok(Some(self.buf[start..stmt_end].to_vec()));
1618 }
1619 return Ok(None);
1620 }
1621 let result = self.buf[start..].to_vec();
1622 self.buf_pos = self.buf.len();
1623 return Ok(Some(result));
1624 }
1625
1626 let (removed, got_more) = self.grow_buffer(start)?;
1627 start -= removed;
1628 i -= removed;
1629 line_start -= removed;
1630 if !got_more {
1631 at_eof = true;
1632 }
1633 }
1634 }
1635
1636 #[allow(dead_code)]
1637 pub fn parse_statement(stmt: &[u8]) -> (StatementType, String) {
1638 Self::parse_statement_with_dialect(stmt, SqlDialect::MySql)
1639 }
1640
1641 /// Parse a statement with dialect-specific handling
1642 pub fn parse_statement_with_dialect(
1643 stmt: &[u8],
1644 dialect: SqlDialect,
1645 ) -> (StatementType, String) {
1646 // Strip leading comments (e.g., pg_dump adds -- comments before statements)
1647 let stmt = strip_leading_comments_and_whitespace(stmt);
1648
1649 if stmt.len() < 4 {
1650 return (StatementType::Unknown, String::new());
1651 }
1652
1653 // Use stack-allocated buffer to avoid heap allocation in hot path
1654 let mut upper_prefix = [0u8; 25];
1655 let prefix_len = stmt.len().min(25);
1656 for (i, &b) in stmt.iter().take(prefix_len).enumerate() {
1657 upper_prefix[i] = b.to_ascii_uppercase();
1658 }
1659 let upper_prefix = &upper_prefix[..prefix_len];
1660
1661 // PostgreSQL COPY statement
1662 if upper_prefix.starts_with(b"COPY ") {
1663 if let Some(caps) = COPY_RE.captures(stmt) {
1664 if let Some(m) = caps.get(1) {
1665 let name = String::from_utf8_lossy(m.as_bytes()).into_owned();
1666 // Handle schema.table - extract just the table name
1667 let table_name = name.split('.').next_back().unwrap_or(&name).to_string();
1668 return (StatementType::Copy, table_name);
1669 }
1670 }
1671 }
1672
1673 if upper_prefix.starts_with(b"CREATE TABLE") {
1674 // Try fast extraction first
1675 if let Some(name) = extract_table_name_flexible(stmt, 12, dialect) {
1676 return (StatementType::CreateTable, name);
1677 }
1678 // Fall back to flexible regex
1679 if let Some(caps) = CREATE_TABLE_FLEXIBLE_RE.captures(stmt) {
1680 if let Some(m) = caps.get(1) {
1681 return (
1682 StatementType::CreateTable,
1683 String::from_utf8_lossy(m.as_bytes()).into_owned(),
1684 );
1685 }
1686 }
1687 }
1688
1689 if upper_prefix.starts_with(b"INSERT INTO") || upper_prefix.starts_with(b"INSERT ONLY") {
1690 if let Some(name) = extract_table_name_flexible(stmt, 11, dialect) {
1691 return (StatementType::Insert, name);
1692 }
1693 if let Some(caps) = INSERT_FLEXIBLE_RE.captures(stmt) {
1694 if let Some(m) = caps.get(1) {
1695 return (
1696 StatementType::Insert,
1697 String::from_utf8_lossy(m.as_bytes()).into_owned(),
1698 );
1699 }
1700 }
1701 }
1702
1703 if upper_prefix.starts_with(b"CREATE INDEX")
1704 || upper_prefix.starts_with(b"CREATE UNIQUE")
1705 || upper_prefix.starts_with(b"CREATE CLUSTERED")
1706 || upper_prefix.starts_with(b"CREATE NONCLUSTER")
1707 {
1708 // For MSSQL, try the bracket-aware regex first
1709 if dialect == SqlDialect::Mssql {
1710 if let Some(caps) = CREATE_INDEX_MSSQL_RE.captures(stmt) {
1711 if let Some(m) = caps.get(1) {
1712 return (
1713 StatementType::CreateIndex,
1714 String::from_utf8_lossy(m.as_bytes()).into_owned(),
1715 );
1716 }
1717 }
1718 }
1719 // Fall back to generic regex for MySQL/PostgreSQL/SQLite
1720 if let Some(caps) = CREATE_INDEX_RE.captures(stmt) {
1721 if let Some(m) = caps.get(1) {
1722 let name = String::from_utf8_lossy(m.as_bytes());
1723 // Strip schema qualifier (public.users -> users) so indexes
1724 // group under the same key as their CREATE TABLE, which also
1725 // strips the schema.
1726 let table_name = name.split('.').next_back().unwrap_or(&name).to_string();
1727 return (StatementType::CreateIndex, table_name);
1728 }
1729 }
1730 }
1731
1732 if upper_prefix.starts_with(b"ALTER TABLE") {
1733 if let Some(name) = extract_table_name_flexible(stmt, 11, dialect) {
1734 return (StatementType::AlterTable, name);
1735 }
1736 if let Some(caps) = ALTER_TABLE_RE.captures(stmt) {
1737 if let Some(m) = caps.get(1) {
1738 return (
1739 StatementType::AlterTable,
1740 String::from_utf8_lossy(m.as_bytes()).into_owned(),
1741 );
1742 }
1743 }
1744 }
1745
1746 if upper_prefix.starts_with(b"DROP TABLE") {
1747 if let Some(name) = extract_table_name_flexible(stmt, 10, dialect) {
1748 return (StatementType::DropTable, name);
1749 }
1750 if let Some(caps) = DROP_TABLE_RE.captures(stmt) {
1751 if let Some(m) = caps.get(1) {
1752 return (
1753 StatementType::DropTable,
1754 String::from_utf8_lossy(m.as_bytes()).into_owned(),
1755 );
1756 }
1757 }
1758 }
1759
1760 // MSSQL BULK INSERT - treat as Insert statement type
1761 if upper_prefix.starts_with(b"BULK INSERT") {
1762 if let Some(name) = extract_table_name_flexible(stmt, 11, dialect) {
1763 return (StatementType::Insert, name);
1764 }
1765 }
1766
1767 (StatementType::Unknown, String::new())
1768 }
1769}
1770
1771#[inline]
1772fn trim_ascii_start(data: &[u8]) -> &[u8] {
1773 let start = data
1774 .iter()
1775 .position(|&b| !matches!(b, b' ' | b'\t' | b'\n' | b'\r'))
1776 .unwrap_or(data.len());
1777 &data[start..]
1778}
1779
1780/// Strip leading whitespace and SQL line comments (`-- ...`) from a statement.
1781/// This makes parsing robust to pg_dump-style comment blocks before statements.
1782pub(crate) fn strip_leading_comments_and_whitespace(mut data: &[u8]) -> &[u8] {
1783 loop {
1784 // First trim leading ASCII whitespace
1785 data = trim_ascii_start(data);
1786
1787 // Strip a leading UTF-8 BOM (EF BB BF). Without this the first statement
1788 // in a BOM-prefixed dump classifies as Unknown and split drops it.
1789 if data.starts_with(&[0xEF, 0xBB, 0xBF]) {
1790 data = &data[3..];
1791 continue;
1792 }
1793
1794 // Handle -- line comments
1795 if data.len() >= 2 && data[0] == b'-' && data[1] == b'-' {
1796 // Skip until end of line
1797 if let Some(pos) = data.iter().position(|&b| b == b'\n') {
1798 data = &data[pos + 1..];
1799 continue;
1800 } else {
1801 // Comment runs to EOF, nothing left
1802 return &[];
1803 }
1804 }
1805
1806 // Handle /* */ block comments (including MySQL conditional comments)
1807 if data.len() >= 2 && data[0] == b'/' && data[1] == b'*' {
1808 // Find the closing */
1809 let mut i = 2;
1810 let mut depth = 1;
1811 while i < data.len() - 1 && depth > 0 {
1812 if data[i] == b'*' && data[i + 1] == b'/' {
1813 depth -= 1;
1814 i += 2;
1815 } else if data[i] == b'/' && data[i + 1] == b'*' {
1816 depth += 1;
1817 i += 2;
1818 } else {
1819 i += 1;
1820 }
1821 }
1822 if depth == 0 {
1823 data = &data[i..];
1824 continue;
1825 } else {
1826 // Unclosed comment runs to EOF
1827 return &[];
1828 }
1829 }
1830
1831 // Handle # line comments (MySQL)
1832 if !data.is_empty() && data[0] == b'#' {
1833 if let Some(pos) = data.iter().position(|&b| b == b'\n') {
1834 data = &data[pos + 1..];
1835 continue;
1836 } else {
1837 return &[];
1838 }
1839 }
1840
1841 break;
1842 }
1843
1844 data
1845}
1846
1847/// Extract table name with support for:
1848/// - IF NOT EXISTS
1849/// - ONLY (PostgreSQL)
1850/// - Schema-qualified names (schema.table)
1851/// - Both backtick and double-quote quoting
1852#[inline]
1853pub(crate) fn extract_table_name_flexible(
1854 stmt: &[u8],
1855 offset: usize,
1856 dialect: SqlDialect,
1857) -> Option<String> {
1858 let mut i = offset;
1859
1860 // Skip whitespace
1861 while i < stmt.len() && is_whitespace(stmt[i]) {
1862 i += 1;
1863 }
1864
1865 if i >= stmt.len() {
1866 return None;
1867 }
1868
1869 // Check for IF NOT EXISTS or IF EXISTS (stack-allocated to avoid heap allocation)
1870 let mut upper_check = [0u8; 20];
1871 let check_len = (stmt.len() - i).min(20);
1872 for (idx, &b) in stmt[i..].iter().take(check_len).enumerate() {
1873 upper_check[idx] = b.to_ascii_uppercase();
1874 }
1875 let upper_slice = &upper_check[..check_len];
1876 if upper_slice.starts_with(b"IF NOT EXISTS") {
1877 i += 13; // Skip "IF NOT EXISTS"
1878 while i < stmt.len() && is_whitespace(stmt[i]) {
1879 i += 1;
1880 }
1881 } else if upper_slice.starts_with(b"IF EXISTS") {
1882 i += 9; // Skip "IF EXISTS"
1883 while i < stmt.len() && is_whitespace(stmt[i]) {
1884 i += 1;
1885 }
1886 }
1887
1888 // Check for ONLY (PostgreSQL) - reuse first 10 bytes or re-check if position changed
1889 let only_check = if i < stmt.len() {
1890 let mut buf = [0u8; 10];
1891 let len = (stmt.len() - i).min(10);
1892 for (idx, &b) in stmt[i..].iter().take(len).enumerate() {
1893 buf[idx] = b.to_ascii_uppercase();
1894 }
1895 (buf, len)
1896 } else {
1897 ([0u8; 10], 0)
1898 };
1899 let only_slice = &only_check.0[..only_check.1];
1900 if only_slice.starts_with(b"ONLY ") || only_slice.starts_with(b"ONLY\t") {
1901 i += 4;
1902 while i < stmt.len() && is_whitespace(stmt[i]) {
1903 i += 1;
1904 }
1905 }
1906
1907 if i >= stmt.len() {
1908 return None;
1909 }
1910
1911 // Read identifier (potentially schema-qualified)
1912 let mut parts: Vec<String> = Vec::new();
1913
1914 loop {
1915 // Determine quote character based on dialect
1916 let (quote_char, close_char) = match stmt.get(i) {
1917 Some(b'`') if dialect == SqlDialect::MySql => {
1918 i += 1;
1919 (Some(b'`'), b'`')
1920 }
1921 // Double quotes are the standard identifier quote for
1922 // Postgres/SQLite/MSSQL, and accepted for MySQL too (less common).
1923 Some(b'"') => {
1924 i += 1;
1925 (Some(b'"'), b'"')
1926 }
1927 Some(b'[') if dialect == SqlDialect::Mssql => {
1928 // MSSQL square bracket quoting
1929 i += 1;
1930 (Some(b'['), b']')
1931 }
1932 _ => (None, 0),
1933 };
1934
1935 let start = i;
1936
1937 while i < stmt.len() {
1938 let b = stmt[i];
1939 if quote_char.is_some() {
1940 if b == close_char {
1941 // For MSSQL, check for escaped ]]
1942 if dialect == SqlDialect::Mssql
1943 && close_char == b']'
1944 && i + 1 < stmt.len()
1945 && stmt[i + 1] == b']'
1946 {
1947 // Escaped bracket, skip both
1948 i += 2;
1949 continue;
1950 }
1951 let name = &stmt[start..i];
1952 // For MSSQL, unescape ]] to ]
1953 let name_str = if dialect == SqlDialect::Mssql {
1954 String::from_utf8_lossy(name).replace("]]", "]")
1955 } else {
1956 String::from_utf8_lossy(name).into_owned()
1957 };
1958 parts.push(name_str);
1959 i += 1; // Skip closing quote
1960 break;
1961 }
1962 } else if is_whitespace(b) || b == b'(' || b == b';' || b == b',' || b == b'.' {
1963 if i > start {
1964 let name = &stmt[start..i];
1965 parts.push(String::from_utf8_lossy(name).into_owned());
1966 }
1967 break;
1968 }
1969 i += 1;
1970 }
1971
1972 // If at end of quoted name without finding close quote, bail
1973 if quote_char.is_some() && i <= start {
1974 break;
1975 }
1976
1977 // Check for schema separator (.)
1978 while i < stmt.len() && is_whitespace(stmt[i]) {
1979 i += 1;
1980 }
1981
1982 if i < stmt.len() && stmt[i] == b'.' {
1983 i += 1; // Skip the dot
1984 while i < stmt.len() && is_whitespace(stmt[i]) {
1985 i += 1;
1986 }
1987 // Continue to read the next identifier (table name)
1988 } else {
1989 break;
1990 }
1991 }
1992
1993 // Return the last part (table name), not the schema
1994 parts.pop()
1995}
1996
1997#[inline]
1998fn is_whitespace(b: u8) -> bool {
1999 matches!(b, b' ' | b'\t' | b'\n' | b'\r')
2000}
2001
2002/// True if `b` can be part of a SQL identifier (letters, digits, `_`). Used to
2003/// tell a PostgreSQL `E'…'` escape-string prefix from an identifier that merely
2004/// ends in `e` (e.g. `type`).
2005#[inline]
2006fn is_word_byte(b: u8) -> bool {
2007 b.is_ascii_alphanumeric() || b == b'_'
2008}
2009
2010/// True if `s` begins with an `INSERT INTO`/`INSERT ONLY` value statement (the
2011/// forms that carry a `VALUES` list). `BULK INSERT` and other keywords are
2012/// intentionally excluded so [`Parser::visit_events`] only enters tuple-
2013/// streaming mode for statements it can actually stream.
2014#[inline]
2015fn starts_with_insert(s: &[u8]) -> bool {
2016 s.len() >= 11
2017 && (s[..11].eq_ignore_ascii_case(b"INSERT INTO")
2018 || s[..11].eq_ignore_ascii_case(b"INSERT ONLY"))
2019}
2020
2021/// A dollar-quote tag is either empty (`$$`) or an identifier
2022/// (`[A-Za-z_][A-Za-z0-9_]*`), matching PostgreSQL's rules.
2023#[inline]
2024fn is_valid_dollar_tag(tag: &[u8]) -> bool {
2025 match tag.first() {
2026 None => true,
2027 Some(&first) if first.is_ascii_alphabetic() || first == b'_' => tag[1..]
2028 .iter()
2029 .all(|&c| c.is_ascii_alphanumeric() || c == b'_'),
2030 _ => false,
2031 }
2032}
2033
2034pub fn determine_buffer_size(file_size: u64) -> usize {
2035 if file_size > 1024 * 1024 * 1024 {
2036 MEDIUM_BUFFER_SIZE
2037 } else {
2038 SMALL_BUFFER_SIZE
2039 }
2040}