Skip to main content

sql_splitter/parser/
mysql_insert.rs

1//! MySQL INSERT statement row parser.
2//!
3//! Parses INSERT INTO ... VALUES statements to extract individual rows
4//! and optionally extract PK/FK column values for dependency tracking.
5
6use crate::parser::{RowFlow, SqlDialect};
7use crate::schema::{ColumnId, ColumnType, TableSchema};
8use ahash::AHashSet;
9use smallvec::SmallVec;
10use std::sync::Arc;
11
12/// How much derived data to compute per parsed row.
13///
14/// PK/FK extraction and especially `all_values` (one `PkValue` — often a
15/// `String` allocation — per column per row) dominate row-parsing cost, so
16/// consumers that don't need them should opt out.
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
18pub enum RowExtraction {
19    /// Only `raw` and `values` — no PK/FK/all_values work (e.g. redact).
20    ValuesOnly,
21    /// `pk` and `fk_values`, skipping `all_values` (e.g. sample, validate).
22    PkFk,
23    /// Everything, including `all_values` for full-row comparison
24    /// (e.g. diff, shard).
25    #[default]
26    Full,
27}
28
29/// Primary key value representation supporting common types
30#[derive(Debug, Clone, PartialEq, Eq, Hash)]
31pub enum PkValue {
32    /// Integer value (covers most PKs)
33    Int(i64),
34    /// Big integer value
35    BigInt(i128),
36    /// Text/string value
37    Text(Box<str>),
38    /// NULL value (typically means "no dependency" for FKs)
39    Null,
40}
41
42impl PkValue {
43    /// Check if this is a NULL value
44    pub fn is_null(&self) -> bool {
45        matches!(self, PkValue::Null)
46    }
47}
48
49/// Tuple of PK values for composite primary keys
50pub type PkTuple = SmallVec<[PkValue; 2]>;
51
52/// Set of primary key values for a table (stores full tuples)
53pub type PkSet = AHashSet<PkTuple>;
54
55/// Compact hash-based set of primary keys for memory efficiency.
56/// Uses 64-bit hashes instead of full values - suitable for large datasets
57/// where collision risk is acceptable (sampling, validation).
58pub type PkHashSet = AHashSet<u64>;
59
60/// Hash a PK tuple into a compact 64-bit hash for memory-efficient storage.
61/// Uses AHash for fast, high-quality hashing.
62pub fn hash_pk_tuple(pk: &PkTuple) -> u64 {
63    use std::hash::{Hash, Hasher};
64    let mut hasher = ahash::AHasher::default();
65
66    // Include arity (number of columns) in the hash
67    (pk.len() as u8).hash(&mut hasher);
68
69    for v in pk {
70        match v {
71            // Int and BigInt of the same integer must hash identically: a value
72            // dumped unquoted (Int) and the same value dumped quoted in a wider
73            // column (BigInt) are the same key for hash-based FK/PK matching.
74            // Normalize both to a common tag and width.
75            PkValue::Int(i) => {
76                0u8.hash(&mut hasher);
77                i128::from(*i).hash(&mut hasher);
78            }
79            PkValue::BigInt(i) => {
80                0u8.hash(&mut hasher);
81                i.hash(&mut hasher);
82            }
83            PkValue::Text(s) => {
84                2u8.hash(&mut hasher);
85                s.hash(&mut hasher);
86            }
87            PkValue::Null => {
88                3u8.hash(&mut hasher);
89            }
90        }
91    }
92
93    hasher.finish()
94}
95
96/// Reference to a specific foreign key in a table
97#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
98pub struct FkRef {
99    /// Table containing the FK
100    pub table_id: u32,
101    /// Index of the FK within the table's foreign_keys vector
102    pub fk_index: u16,
103}
104
105/// A parsed row from an INSERT statement
106#[derive(Debug, Clone)]
107pub struct ParsedRow {
108    /// Raw bytes of the row value list: "(val1, val2, ...)"
109    pub raw: Vec<u8>,
110    /// Parsed values for each column (for bulk loading)
111    pub values: Vec<ParsedValue>,
112    /// Extracted primary key values (if table has PK and values are non-NULL)
113    pub pk: Option<PkTuple>,
114    /// Extracted foreign key values with their references
115    /// Only includes FKs where all columns are non-NULL
116    pub fk_values: Vec<(FkRef, PkTuple)>,
117    /// All column values (for data diff comparison).
118    /// Empty unless parsed with [`RowExtraction::Full`].
119    pub all_values: Vec<PkValue>,
120    /// Mapping from schema column index to value index (for finding specific columns).
121    /// If column_map[schema_col_idx] == Some(val_idx), then all_values[val_idx] is the value.
122    /// Shared across all rows of a statement (computed once).
123    pub column_map: Arc<[Option<usize>]>,
124}
125
126impl ParsedRow {
127    /// Get the value for a specific schema column index
128    pub fn get_column_value(&self, schema_col_index: usize) -> Option<&PkValue> {
129        self.column_map
130            .get(schema_col_index)
131            .and_then(|v| *v)
132            .and_then(|val_idx| self.all_values.get(val_idx))
133    }
134}
135
136#[inline]
137fn is_ident_byte(b: u8) -> bool {
138    b.is_ascii_alphanumeric() || b == b'_'
139}
140
141/// Copy bytes into a `String`, validating UTF-8 once and falling back to a
142/// lossy re-encode only for invalid input. Unlike `from_utf8_lossy(..).into_owned()`,
143/// the valid path is a straight validate + copy with no chunk iteration.
144#[inline]
145pub(crate) fn bytes_to_string(bytes: &[u8]) -> String {
146    match std::str::from_utf8(bytes) {
147        Ok(s) => s.to_owned(),
148        Err(_) => String::from_utf8_lossy(bytes).into_owned(),
149    }
150}
151
152/// Outcome of scanning an INSERT statement's header for its `VALUES` keyword.
153pub(crate) enum HeaderScan {
154    /// `VALUES` found: byte offset just past the keyword.
155    Values(usize),
156    /// The statement's top-level `;` was reached before any `VALUES` keyword
157    /// (an `INSERT … SELECT` / `INSERT … SET`): byte offset just past the `;`.
158    NoValues(usize),
159    /// The slice ended with neither: the caller must buffer more input.
160    Incomplete,
161}
162
163/// Scan an INSERT statement's header, stopping at whichever comes first: the
164/// `VALUES` keyword or the statement's top-level `;`. Bounding the search to
165/// the current statement stops a VALUES-less INSERT from locking onto a later
166/// statement's `VALUES` and swallowing everything in between.
167///
168/// `VALUES` is matched as a keyword (word-boundaried, not inside a quoted
169/// identifier or string literal), so tables like `product_values` or
170/// `` `order values` `` are not mistaken for the clause (bug #2).
171pub(crate) fn scan_insert_header(stmt: &[u8]) -> HeaderScan {
172    let mut in_single = false;
173    let mut in_double = false;
174    let mut in_backtick = false;
175    let mut in_bracket = false;
176    let mut i = 0;
177
178    while i < stmt.len() {
179        let b = stmt[i];
180
181        if in_single {
182            // Only need to find the end of the string; treat '' as an escaped
183            // quote so we don't exit early. Backslash handling is irrelevant
184            // here because string literals only ever follow VALUES.
185            if b == b'\'' {
186                if stmt.get(i + 1) == Some(&b'\'') {
187                    i += 2;
188                    continue;
189                }
190                in_single = false;
191            }
192            i += 1;
193            continue;
194        }
195        if in_double {
196            if b == b'"' {
197                in_double = false;
198            }
199            i += 1;
200            continue;
201        }
202        if in_backtick {
203            if b == b'`' {
204                in_backtick = false;
205            }
206            i += 1;
207            continue;
208        }
209        if in_bracket {
210            if b == b']' {
211                in_bracket = false;
212            }
213            i += 1;
214            continue;
215        }
216
217        match b {
218            b'\'' => {
219                in_single = true;
220                i += 1;
221                continue;
222            }
223            b'"' => {
224                in_double = true;
225                i += 1;
226                continue;
227            }
228            b'`' => {
229                in_backtick = true;
230                i += 1;
231                continue;
232            }
233            b'[' => {
234                in_bracket = true;
235                i += 1;
236                continue;
237            }
238            // Top-level statement terminator reached before any VALUES clause.
239            b';' => return HeaderScan::NoValues(i + 1),
240            _ => {}
241        }
242
243        if (b == b'V' || b == b'v')
244            && i + 6 <= stmt.len()
245            && stmt[i..i + 6].eq_ignore_ascii_case(b"VALUES")
246        {
247            let before_ok = i == 0 || !is_ident_byte(stmt[i - 1]);
248            let after_ok = stmt.get(i + 6).is_none_or(|&c| !is_ident_byte(c));
249            if before_ok && after_ok {
250                return HeaderScan::Values(i + 6);
251            }
252        }
253
254        i += 1;
255    }
256
257    HeaderScan::Incomplete
258}
259
260/// Byte offset just past the `VALUES` keyword within a single INSERT statement,
261/// or `None` for a VALUES-less INSERT. Thin wrapper over [`scan_insert_header`]
262/// for callers that already hold one complete statement.
263pub(crate) fn find_values_keyword_pos(stmt: &[u8]) -> Option<usize> {
264    match scan_insert_header(stmt) {
265        HeaderScan::Values(pos) => Some(pos),
266        HeaderScan::NoValues(_) | HeaderScan::Incomplete => None,
267    }
268}
269
270/// Extract a column list `(a, b, c)` appearing immediately before the VALUES
271/// keyword, given the byte offset just past VALUES. Shared by
272/// [`InsertParser::parse_column_list`] and [`parse_insert_for_bulk`] (bug #2).
273pub(crate) fn extract_column_list_before(stmt: &[u8], values_pos: usize) -> Option<Vec<String>> {
274    let before = &stmt[..values_pos.saturating_sub(6)];
275    let s = String::from_utf8_lossy(before);
276
277    let close = s.rfind(')')?;
278    let open = s[..close].rfind('(')?;
279    let col_list = &s[open + 1..close];
280
281    let upper = col_list.to_uppercase();
282    if col_list.trim().is_empty() || upper.contains("SELECT") {
283        return None;
284    }
285
286    let columns: Vec<String> = col_list
287        .split(',')
288        .map(|c| {
289            c.trim()
290                .trim_matches('`')
291                .trim_matches('"')
292                .trim_matches('[')
293                .trim_matches(']')
294                .to_string()
295        })
296        .collect();
297
298    if columns.is_empty() {
299        None
300    } else {
301        Some(columns)
302    }
303}
304
305/// Build the reverse column map (schema column ordinal -> value index) for a
306/// statement/block, shared with every row via `Arc` instead of cloned per row.
307/// Used by both the INSERT and COPY parsers.
308pub(crate) fn build_col_to_value(
309    column_order: &[Option<ColumnId>],
310    n_columns: usize,
311) -> Arc<[Option<usize>]> {
312    let mut map = vec![None; n_columns];
313    for (val_idx, col_id_opt) in column_order.iter().enumerate() {
314        if let Some(col_id) = col_id_opt {
315            let ord = col_id.0 as usize;
316            if ord < map.len() {
317                map[ord] = Some(val_idx);
318            }
319        }
320    }
321    map.into()
322}
323
324/// Coerce a textual value to an integer [`PkValue`] when the schema column is
325/// `Int`/`BigInt` (integer PKs are often dumped as quoted strings). Shared by
326/// the INSERT and COPY `value_to_pk` paths so the coercion rules can't drift
327/// between MySQL and Postgres dumps.
328pub(crate) fn coerce_text_pk(s: &str, col: Option<&crate::schema::Column>) -> Option<PkValue> {
329    match col?.col_type {
330        ColumnType::Int => s.parse::<i64>().ok().map(PkValue::Int),
331        ColumnType::BigInt => s.parse::<i128>().ok().map(PkValue::BigInt),
332        _ => None,
333    }
334}
335
336/// Extract PK tuple, FK tuples and all column values from one parsed row,
337/// shared by the INSERT and COPY parsers. `to_pk` converts a dialect-specific
338/// value into a [`PkValue`]; `column_order` maps value index -> column, and
339/// `col_to_value` is its precomputed inverse (schema ordinal -> value index).
340/// `all_values` (a `PkValue` per column, often a `String` allocation) is only
341/// built when `include_all_values` is set — see [`RowExtraction`].
342#[allow(clippy::type_complexity)]
343pub(crate) fn extract_pk_fk_generic<V>(
344    values: &[V],
345    schema: &TableSchema,
346    column_order: &[Option<ColumnId>],
347    col_to_value: &[Option<usize>],
348    include_all_values: bool,
349    to_pk: impl Fn(&V, Option<&crate::schema::Column>) -> PkValue,
350) -> (Option<PkTuple>, Vec<(FkRef, PkTuple)>, Vec<PkValue>) {
351    // All column values, in value order.
352    let all_values: Vec<PkValue> = if include_all_values {
353        values
354            .iter()
355            .enumerate()
356            .map(|(idx, v)| {
357                let col = column_order
358                    .get(idx)
359                    .and_then(|c| *c)
360                    .and_then(|id| schema.column(id));
361                to_pk(v, col)
362            })
363            .collect()
364    } else {
365        Vec::new()
366    };
367
368    // PK from columns marked primary key.
369    let mut pk_values = PkTuple::new();
370    for (idx, col_id_opt) in column_order.iter().enumerate() {
371        if let Some(col_id) = col_id_opt {
372            if schema.is_pk_column(*col_id) {
373                if let Some(value) = values.get(idx) {
374                    pk_values.push(to_pk(value, schema.column(*col_id)));
375                }
376            }
377        }
378    }
379
380    // FK tuples (only when every FK column is non-NULL).
381    let mut fk_values = Vec::new();
382    for (fk_idx, fk) in schema.foreign_keys.iter().enumerate() {
383        if fk.referenced_table_id.is_none() {
384            continue;
385        }
386        let mut fk_tuple = PkTuple::new();
387        let mut all_non_null = true;
388        for &col_id in &fk.columns {
389            if let Some(idx) = col_to_value.get(col_id.0 as usize).copied().flatten() {
390                if let Some(value) = values.get(idx) {
391                    let pk_val = to_pk(value, schema.column(col_id));
392                    if pk_val.is_null() {
393                        all_non_null = false;
394                        break;
395                    }
396                    fk_tuple.push(pk_val);
397                }
398            }
399        }
400        if all_non_null && !fk_tuple.is_empty() {
401            fk_values.push((
402                FkRef {
403                    table_id: schema.id.0,
404                    fk_index: fk_idx as u16,
405                },
406                fk_tuple,
407            ));
408        }
409    }
410
411    let pk = if pk_values.is_empty() || pk_values.iter().any(|v| v.is_null()) {
412        None
413    } else {
414        Some(pk_values)
415    };
416
417    (pk, fk_values, all_values)
418}
419
420/// Parser for MySQL INSERT statements
421pub struct InsertParser<'a> {
422    stmt: &'a [u8],
423    pos: usize,
424    table_schema: Option<&'a TableSchema>,
425    /// Column order in the INSERT (maps value index -> column ID)
426    column_order: Vec<Option<ColumnId>>,
427    /// Reverse of `column_order` (schema column ordinal -> value index),
428    /// computed once per statement and shared with every row via `Arc`.
429    col_to_value: Arc<[Option<usize>]>,
430    /// Dialect governs string escaping. Only MySQL treats `\` as an escape
431    /// character; Postgres/SQLite/MSSQL treat it as a literal byte.
432    dialect: SqlDialect,
433    /// How much derived data to compute per row.
434    extraction: RowExtraction,
435    /// Set by [`InsertParser::parse_row`]: whether the last tuple closed its
436    /// parenthesis within the available bytes (`true`) or ran out mid-tuple
437    /// (`false`). Consumed by [`scan_insert_tuple`] for incremental streaming.
438    last_complete: bool,
439}
440
441impl<'a> InsertParser<'a> {
442    /// Create a new parser for an INSERT statement (defaults to MySQL escaping)
443    pub fn new(stmt: &'a [u8]) -> Self {
444        Self {
445            stmt,
446            pos: 0,
447            table_schema: None,
448            column_order: Vec::new(),
449            col_to_value: Arc::from(Vec::new()),
450            dialect: SqlDialect::MySql,
451            extraction: RowExtraction::Full,
452            last_complete: true,
453        }
454    }
455
456    /// Set the table schema for PK/FK extraction
457    pub fn with_schema(mut self, schema: &'a TableSchema) -> Self {
458        self.table_schema = Some(schema);
459        self
460    }
461
462    /// Set the dialect so string values are unescaped correctly (bug #3).
463    pub fn with_dialect(mut self, dialect: SqlDialect) -> Self {
464        self.dialect = dialect;
465        self
466    }
467
468    /// Choose how much per-row derived data to compute (default: [`RowExtraction::Full`]).
469    pub fn with_extraction(mut self, extraction: RowExtraction) -> Self {
470        self.extraction = extraction;
471        self
472    }
473
474    /// Parse all rows from the INSERT statement, collecting them into a `Vec`.
475    ///
476    /// A thin collecting adapter over [`InsertParser::parse_rows_visit`].
477    pub fn parse_rows(&mut self) -> anyhow::Result<Vec<ParsedRow>> {
478        let mut rows = Vec::new();
479        self.parse_rows_visit(|row| {
480            rows.push(row);
481            Ok(RowFlow::Continue)
482        })?;
483        Ok(rows)
484    }
485
486    /// Stream each parsed row to `f` without collecting a statement-sized `Vec`.
487    ///
488    /// Only the current row is materialized at a time. `f` returns a
489    /// [`RowFlow`]: `SkipStatement`/`Stop` both stop this statement's rows.
490    pub fn parse_rows_visit<F>(&mut self, mut f: F) -> anyhow::Result<()>
491    where
492        F: FnMut(ParsedRow) -> anyhow::Result<RowFlow>,
493    {
494        // Find the VALUES keyword
495        let values_pos = self.find_values_keyword()?;
496        self.pos = values_pos;
497
498        // Parse column list if present
499        self.parse_column_list();
500
501        // Precompute the reverse column map once for the whole statement.
502        if let Some(schema) = self.table_schema {
503            self.col_to_value = build_col_to_value(&self.column_order, schema.columns.len());
504        }
505
506        // Parse each row
507        while self.pos < self.stmt.len() {
508            self.skip_whitespace();
509
510            if self.pos >= self.stmt.len() {
511                break;
512            }
513
514            if self.stmt[self.pos] == b'(' {
515                if let Some(row) = self.parse_row() {
516                    match f(row)? {
517                        RowFlow::Continue => {}
518                        RowFlow::SkipStatement | RowFlow::Stop => break,
519                    }
520                }
521            } else if self.stmt[self.pos] == b',' {
522                self.pos += 1;
523            } else {
524                // The VALUES tuple list is `(row)(, row)*`; any other token
525                // (`;`, or a trailing clause like `ON DUPLICATE KEY UPDATE
526                // col = VALUES(col)`) ends it. Stopping here prevents a
527                // `VALUES(col)` reference from being parsed as a phantom row.
528                break;
529            }
530        }
531
532        Ok(())
533    }
534
535    /// Find the VALUES keyword and return position after it
536    fn find_values_keyword(&self) -> anyhow::Result<usize> {
537        find_values_keyword_pos(self.stmt)
538            .ok_or_else(|| anyhow::anyhow!("INSERT statement missing VALUES keyword"))
539    }
540
541    /// Parse optional column list after INSERT INTO table_name
542    fn parse_column_list(&mut self) {
543        if self.table_schema.is_none() {
544            return;
545        }
546
547        let schema = self.table_schema.unwrap();
548
549        // self.pos is just past VALUES; look for a column list immediately
550        // before it (shared with the bulk-loader path).
551        if let Some(cols) = extract_column_list_before(self.stmt, self.pos) {
552            self.column_order = cols.iter().map(|name| schema.get_column_id(name)).collect();
553            return;
554        }
555
556        // No explicit column list - use natural order
557        self.column_order = schema.columns.iter().map(|c| Some(c.ordinal)).collect();
558    }
559
560    /// Parse a single row "(val1, val2, ...)". Infallible: malformed input
561    /// degrades to best-effort values rather than an error (see `parse_value`).
562    fn parse_row(&mut self) -> Option<ParsedRow> {
563        self.skip_whitespace();
564
565        if self.pos >= self.stmt.len() || self.stmt[self.pos] != b'(' {
566            return None;
567        }
568
569        let start = self.pos;
570        self.pos += 1; // Skip '('
571
572        let mut values: Vec<ParsedValue> = Vec::new();
573        let mut depth = 1;
574
575        while self.pos < self.stmt.len() && depth > 0 {
576            self.skip_whitespace();
577
578            if self.pos >= self.stmt.len() {
579                break;
580            }
581
582            match self.stmt[self.pos] {
583                b'(' => {
584                    depth += 1;
585                    self.pos += 1;
586                }
587                b')' => {
588                    depth -= 1;
589                    self.pos += 1;
590                }
591                b',' if depth == 1 => {
592                    self.pos += 1;
593                }
594                _ if depth == 1 => {
595                    values.push(self.parse_value());
596                }
597                // depth > 1 (inside a nested parenthesized expression): consume
598                // string literals whole so a quoted ')' or ',' cannot corrupt
599                // the parenthesis balance and truncate the tuple early.
600                b'\'' => {
601                    let _ = self.parse_string_value();
602                }
603                _ => {
604                    self.pos += 1;
605                }
606            }
607        }
608
609        // depth == 0 means we consumed the matching ')'; depth > 0 means the
610        // slice ended mid-tuple (used by the incremental streaming scanner).
611        self.last_complete = depth == 0;
612
613        let end = self.pos;
614        let raw = self.stmt[start..end].to_vec();
615
616        // Extract PK, FK, and (for Full extraction) all values if we have a schema
617        let (pk, fk_values, all_values) = match (self.table_schema, self.extraction) {
618            (Some(schema), RowExtraction::PkFk | RowExtraction::Full) => {
619                self.extract_pk_fk(&values, schema)
620            }
621            _ => (None, Vec::new(), Vec::new()),
622        };
623
624        Some(ParsedRow {
625            raw,
626            values,
627            pk,
628            fk_values,
629            all_values,
630            column_map: Arc::clone(&self.col_to_value),
631        })
632    }
633
634    /// Parse a single value (string, number, NULL, etc.)
635    fn parse_value(&mut self) -> ParsedValue {
636        self.skip_whitespace();
637
638        if self.pos >= self.stmt.len() {
639            return ParsedValue::Null;
640        }
641
642        let b = self.stmt[self.pos];
643
644        // NULL
645        if self.pos + 4 <= self.stmt.len() {
646            let word = &self.stmt[self.pos..self.pos + 4];
647            if word.eq_ignore_ascii_case(b"NULL") {
648                self.pos += 4;
649                return ParsedValue::Null;
650            }
651        }
652
653        // String literal (including MSSQL N'...' Unicode prefix)
654        if b == b'\'' {
655            return self.parse_string_value();
656        }
657
658        // MSSQL N'...' Unicode string literal
659        if (b == b'N' || b == b'n')
660            && self.pos + 1 < self.stmt.len()
661            && self.stmt[self.pos + 1] == b'\''
662        {
663            self.pos += 1; // Skip the N prefix
664            return self.parse_string_value();
665        }
666
667        // Hex literal (0x...)
668        if b == b'0' && self.pos + 1 < self.stmt.len() {
669            let next = self.stmt[self.pos + 1];
670            if next == b'x' || next == b'X' {
671                return self.parse_hex_value();
672            }
673        }
674
675        // Number or expression
676        self.parse_number_value()
677    }
678
679    /// Parse a string literal 'value'
680    fn parse_string_value(&mut self) -> ParsedValue {
681        self.pos += 1; // Skip opening quote
682
683        // Backslash is only an escape character in MySQL. Postgres (standard
684        // strings), SQLite and MSSQL treat it as a literal byte, so applying
685        // MySQL unescaping there corrupts Windows paths, regexes, JSON, etc.
686        let honor_backslash = self.dialect == SqlDialect::MySql;
687
688        // memchr from one significant byte (quote/backslash) to the next and
689        // bulk-copy the plain bytes in between. `owned` stays empty on the
690        // fast path (no escapes at all), where the literal is a single slice.
691        let mut owned: Vec<u8> = Vec::new();
692        let mut chunk_start = self.pos;
693
694        let content_end = loop {
695            let rest = &self.stmt[self.pos..];
696            let hit = if honor_backslash {
697                memchr::memchr2(b'\'', b'\\', rest)
698            } else {
699                memchr::memchr(b'\'', rest)
700            };
701            let Some(off) = hit else {
702                // Unterminated literal: take everything to the end.
703                self.pos = self.stmt.len();
704                break self.pos;
705            };
706            self.pos += off;
707
708            if self.stmt[self.pos] == b'\\' {
709                owned.extend_from_slice(&self.stmt[chunk_start..self.pos]);
710                match self.stmt.get(self.pos + 1) {
711                    Some(&c) => {
712                        // MySQL escape sequences
713                        let escaped = match c {
714                            b'n' => b'\n',
715                            b'r' => b'\r',
716                            b't' => b'\t',
717                            b'0' => 0,
718                            _ => c, // \', \\, etc.
719                        };
720                        owned.push(escaped);
721                        self.pos += 2;
722                    }
723                    // Trailing backslash at end of statement: drop it.
724                    None => self.pos += 1,
725                }
726                chunk_start = self.pos;
727            } else if self.stmt.get(self.pos + 1) == Some(&b'\'') {
728                // Doubled quote '' is an escaped quote: keep one.
729                owned.extend_from_slice(&self.stmt[chunk_start..=self.pos]);
730                self.pos += 2;
731                chunk_start = self.pos;
732            } else {
733                let end = self.pos;
734                self.pos += 1; // Consume the closing quote
735                break end;
736            }
737        };
738
739        let tail = &self.stmt[chunk_start..content_end];
740        let value = if owned.is_empty() {
741            bytes_to_string(tail)
742        } else {
743            owned.extend_from_slice(tail);
744            // Consume the already-owned bytes without a second copy; only
745            // invalid UTF-8 falls back to the lossy re-encode.
746            match String::from_utf8(owned) {
747                Ok(s) => s,
748                Err(e) => String::from_utf8_lossy(e.as_bytes()).into_owned(),
749            }
750        };
751
752        ParsedValue::String { value }
753    }
754
755    /// Parse a hex literal 0xABCD...
756    fn parse_hex_value(&mut self) -> ParsedValue {
757        let start = self.pos;
758        self.pos += 2; // Skip 0x
759
760        while self.pos < self.stmt.len() {
761            let b = self.stmt[self.pos];
762            if b.is_ascii_hexdigit() {
763                self.pos += 1;
764            } else {
765                break;
766            }
767        }
768
769        let raw = self.stmt[start..self.pos].to_vec();
770        ParsedValue::Hex(raw)
771    }
772
773    /// Parse a number or other non-string value
774    fn parse_number_value(&mut self) -> ParsedValue {
775        let start = self.pos;
776        let mut has_dot = false;
777
778        // Handle leading minus
779        if self.pos < self.stmt.len() && self.stmt[self.pos] == b'-' {
780            self.pos += 1;
781        }
782
783        while self.pos < self.stmt.len() {
784            let b = self.stmt[self.pos];
785            if b.is_ascii_digit() {
786                self.pos += 1;
787            } else if b == b'.' && !has_dot {
788                has_dot = true;
789                self.pos += 1;
790            } else if b == b'e' || b == b'E' {
791                // Scientific notation
792                self.pos += 1;
793                if self.pos < self.stmt.len()
794                    && (self.stmt[self.pos] == b'+' || self.stmt[self.pos] == b'-')
795                {
796                    self.pos += 1;
797                }
798            } else if b == b',' || b == b')' || b.is_ascii_whitespace() {
799                break;
800            } else {
801                // Unknown character: this is an expression/function call rather
802                // than a plain number. Skip to the delimiter that ends this
803                // value, respecting string/identifier quotes (' and ") and
804                // nested parentheses so a value like
805                // ST_GeomFromText('POLYGON((0 0,1 1))') or CONCAT("x)y", "z")
806                // isn't split inside its own string/parens (bug #11).
807                let mut depth = 0i32;
808                let mut quote: Option<u8> = None;
809                let honor_backslash = self.dialect == SqlDialect::MySql;
810                while self.pos < self.stmt.len() {
811                    let c = self.stmt[self.pos];
812                    if let Some(q) = quote {
813                        if c == b'\\' && honor_backslash {
814                            self.pos += 2;
815                            continue;
816                        }
817                        if c == q {
818                            // A doubled quote ('' or "") stays inside.
819                            if self.stmt.get(self.pos + 1) == Some(&q) {
820                                self.pos += 2;
821                                continue;
822                            }
823                            quote = None;
824                        }
825                        self.pos += 1;
826                        continue;
827                    }
828                    match c {
829                        b'\'' | b'"' => quote = Some(c),
830                        b'(' => depth += 1,
831                        b')' if depth > 0 => depth -= 1,
832                        b')' => break,
833                        b',' if depth == 0 => break,
834                        _ => {}
835                    }
836                    self.pos += 1;
837                }
838                break;
839            }
840        }
841
842        let raw = &self.stmt[start..self.pos];
843
844        // Try to parse as integer before copying: plain integers (the common
845        // case for IDs) then need no allocation at all.
846        if !has_dot {
847            if let Ok(value_str) = std::str::from_utf8(raw) {
848                if let Ok(n) = value_str.parse::<i64>() {
849                    return ParsedValue::Integer(n);
850                }
851                if let Ok(n) = value_str.parse::<i128>() {
852                    return ParsedValue::BigInteger(n);
853                }
854            }
855        }
856
857        // Fall back to raw value
858        ParsedValue::Other(raw.to_vec())
859    }
860
861    /// Skip whitespace and newlines
862    fn skip_whitespace(&mut self) {
863        while self.pos < self.stmt.len() {
864            let b = self.stmt[self.pos];
865            if b.is_ascii_whitespace() {
866                self.pos += 1;
867            } else {
868                break;
869            }
870        }
871    }
872
873    /// Extract PK, FK, and all values from parsed values
874    fn extract_pk_fk(
875        &self,
876        values: &[ParsedValue],
877        schema: &TableSchema,
878    ) -> (Option<PkTuple>, Vec<(FkRef, PkTuple)>, Vec<PkValue>) {
879        extract_pk_fk_generic(
880            values,
881            schema,
882            &self.column_order,
883            &self.col_to_value,
884            self.extraction == RowExtraction::Full,
885            |v, col| self.value_to_pk(v, col),
886        )
887    }
888
889    /// Convert a parsed value to a PkValue
890    fn value_to_pk(&self, value: &ParsedValue, col: Option<&crate::schema::Column>) -> PkValue {
891        match value {
892            ParsedValue::Null => PkValue::Null,
893            ParsedValue::Integer(n) => PkValue::Int(*n),
894            ParsedValue::BigInteger(n) => PkValue::BigInt(*n),
895            ParsedValue::String { value } => {
896                // Check if this might be an integer stored as string
897                coerce_text_pk(value, col)
898                    .unwrap_or_else(|| PkValue::Text(value.clone().into_boxed_str()))
899            }
900            ParsedValue::Hex(raw) => {
901                PkValue::Text(String::from_utf8_lossy(raw).into_owned().into_boxed_str())
902            }
903            ParsedValue::Other(raw) => {
904                PkValue::Text(String::from_utf8_lossy(raw).into_owned().into_boxed_str())
905            }
906        }
907    }
908}
909
910/// Parsed value from an INSERT statement
911///
912/// Used for bulk loading via DuckDB Appender and for PK/FK extraction.
913#[derive(Debug, Clone)]
914pub enum ParsedValue {
915    /// NULL value
916    Null,
917    /// Integer value (fits in i64)
918    Integer(i64),
919    /// Big integer value (requires i128)
920    BigInteger(i128),
921    /// String/text value (already unescaped)
922    String { value: String },
923    /// Hex literal (0xABCD...)
924    Hex(Vec<u8>),
925    /// Other value (decimals, floats, expressions) as raw bytes
926    Other(Vec<u8>),
927}
928
929/// Parse all rows from an INSERT statement using the given dialect's escaping.
930pub fn parse_insert_rows(
931    stmt: &[u8],
932    schema: &TableSchema,
933    dialect: SqlDialect,
934) -> anyhow::Result<Vec<ParsedRow>> {
935    parse_insert_rows_with(stmt, schema, dialect, RowExtraction::Full)
936}
937
938/// Like [`parse_insert_rows`], but with an explicit [`RowExtraction`] level so
939/// consumers that don't need `all_values` (or PK/FK at all) skip that work.
940///
941/// This is a collecting adapter over [`visit_insert_rows_with`]: it simply
942/// pushes each streamed row into a `Vec`. Existing consumers that want the
943/// whole statement's rows keep using it unchanged.
944pub fn parse_insert_rows_with(
945    stmt: &[u8],
946    schema: &TableSchema,
947    dialect: SqlDialect,
948    extraction: RowExtraction,
949) -> anyhow::Result<Vec<ParsedRow>> {
950    let mut rows = Vec::new();
951    visit_insert_rows_with(stmt, schema, dialect, extraction, |row| {
952        rows.push(row);
953        Ok(RowFlow::Continue)
954    })?;
955    Ok(rows)
956}
957
958/// Stream the rows of an INSERT statement to a visitor, one at a time, without
959/// building a statement-sized `Vec`. `f` returns a [`RowFlow`] to stop early.
960/// Only the fields required by `extraction` are allocated per row.
961pub fn visit_insert_rows_with<F>(
962    stmt: &[u8],
963    schema: &TableSchema,
964    dialect: SqlDialect,
965    extraction: RowExtraction,
966    f: F,
967) -> anyhow::Result<()>
968where
969    F: FnMut(ParsedRow) -> anyhow::Result<RowFlow>,
970{
971    let mut parser = InsertParser::new(stmt)
972        .with_schema(schema)
973        .with_dialect(dialect)
974        .with_extraction(extraction);
975    parser.parse_rows_visit(f)
976}
977
978/// Precomputed per-statement column context, so [`Parser::visit_events`]
979/// consumers can parse individual INSERT tuples (delivered as
980/// [`crate::parser::ParserEvent::InsertRow`]) without re-deriving the column
981/// order for every row. Built once per INSERT header.
982///
983/// [`Parser::visit_events`]: crate::parser::Parser::visit_events
984pub struct InsertRowContext {
985    column_order: Vec<Option<ColumnId>>,
986    col_to_value: Arc<[Option<usize>]>,
987}
988
989impl InsertRowContext {
990    /// Build the context from an INSERT header (the statement bytes up to and
991    /// including the `VALUES` keyword) and the table schema, exactly as the
992    /// full-statement parser would.
993    pub fn from_header(header: &[u8], schema: &TableSchema) -> Self {
994        let values_pos = find_values_keyword_pos(header).unwrap_or(header.len());
995        let column_order: Vec<Option<ColumnId>> =
996            match extract_column_list_before(header, values_pos) {
997                Some(cols) => cols.iter().map(|n| schema.get_column_id(n)).collect(),
998                None => schema.columns.iter().map(|c| Some(c.ordinal)).collect(),
999            };
1000        let col_to_value = build_col_to_value(&column_order, schema.columns.len());
1001        Self {
1002            column_order,
1003            col_to_value,
1004        }
1005    }
1006}
1007
1008/// Parse a single INSERT `(...)` tuple with a precomputed [`InsertRowContext`].
1009///
1010/// Produces a [`ParsedRow`] byte-identical to the one the full-statement parser
1011/// would produce for the same tuple bytes and column context.
1012pub fn parse_insert_tuple(
1013    tuple: &[u8],
1014    schema: &TableSchema,
1015    ctx: &InsertRowContext,
1016    dialect: SqlDialect,
1017    extraction: RowExtraction,
1018) -> Option<ParsedRow> {
1019    let mut p = InsertParser::new(tuple)
1020        .with_schema(schema)
1021        .with_dialect(dialect)
1022        .with_extraction(extraction);
1023    p.column_order = ctx.column_order.clone();
1024    p.col_to_value = Arc::clone(&ctx.col_to_value);
1025    p.parse_row()
1026}
1027
1028/// Find the extent of one INSERT tuple beginning at `data[0]` (which must be
1029/// `(`), using the exact same logic as [`InsertParser::parse_row`].
1030///
1031/// Returns `(consumed, complete)`: `consumed` is the number of bytes the tuple
1032/// occupies (so `data[..consumed]` is the raw tuple), and `complete` is `false`
1033/// when `data` ended before the matching `)` (the caller should buffer more).
1034/// Returns `None` only when `data` does not start at a `(`.
1035pub(crate) fn scan_insert_tuple(data: &[u8], dialect: SqlDialect) -> Option<(usize, bool)> {
1036    let mut p = InsertParser::new(data)
1037        .with_dialect(dialect)
1038        .with_extraction(RowExtraction::ValuesOnly);
1039    // parse_row returns None only when not positioned at '('.
1040    p.parse_row()?;
1041    Some((p.pos, p.last_complete))
1042}
1043
1044/// Parse all rows from a MySQL INSERT statement
1045pub fn parse_mysql_insert_rows(
1046    stmt: &[u8],
1047    schema: &TableSchema,
1048) -> anyhow::Result<Vec<ParsedRow>> {
1049    parse_insert_rows(stmt, schema, SqlDialect::MySql)
1050}
1051
1052/// Parse rows without schema (just raw row extraction)
1053pub fn parse_mysql_insert_rows_raw(stmt: &[u8]) -> anyhow::Result<Vec<ParsedRow>> {
1054    let mut parser = InsertParser::new(stmt);
1055    parser.parse_rows()
1056}
1057
1058#[cfg(test)]
1059mod tests {
1060    use super::*;
1061
1062    #[test]
1063    fn test_parse_insert_for_bulk_simple() {
1064        let sql = b"INSERT INTO users VALUES (1, 'Alice')";
1065        let result = parse_insert_for_bulk(sql, SqlDialect::MySql).unwrap();
1066        assert_eq!(result.table, "users");
1067        assert!(result.columns.is_none());
1068        assert_eq!(result.rows.len(), 1);
1069    }
1070
1071    #[test]
1072    fn test_parse_insert_for_bulk_with_columns() {
1073        let sql = b"INSERT INTO users (name, id) VALUES ('Alice', 1)";
1074        let result = parse_insert_for_bulk(sql, SqlDialect::MySql).unwrap();
1075        assert_eq!(result.table, "users");
1076        assert_eq!(
1077            result.columns,
1078            Some(vec!["name".to_string(), "id".to_string()])
1079        );
1080        assert_eq!(result.rows.len(), 1);
1081    }
1082
1083    #[test]
1084    fn test_parse_insert_for_bulk_mssql() {
1085        let sql =
1086            b"INSERT INTO [dbo].[users] ([email], [name]) VALUES (N'alice@example.com', N'Alice')";
1087        let result = parse_insert_for_bulk(sql, SqlDialect::Mssql).unwrap();
1088        assert_eq!(result.table, "users");
1089        assert_eq!(
1090            result.columns,
1091            Some(vec!["email".to_string(), "name".to_string()])
1092        );
1093        assert_eq!(result.rows.len(), 1);
1094    }
1095
1096    #[test]
1097    fn test_parse_insert_for_bulk_mysql() {
1098        let sql = b"INSERT INTO `users` (`id`, `name`) VALUES (1, 'Bob')";
1099        let result = parse_insert_for_bulk(sql, SqlDialect::MySql).unwrap();
1100        assert_eq!(result.table, "users");
1101        assert_eq!(
1102            result.columns,
1103            Some(vec!["id".to_string(), "name".to_string()])
1104        );
1105        assert_eq!(result.rows.len(), 1);
1106    }
1107}
1108
1109/// Result of parsing INSERT values for bulk loading
1110#[derive(Debug, Clone)]
1111pub struct InsertValues {
1112    /// Table name (without schema prefix or quotes)
1113    pub table: String,
1114    /// Column list if specified, None if using natural order
1115    pub columns: Option<Vec<String>>,
1116    /// Parsed rows with values
1117    pub rows: Vec<Vec<ParsedValue>>,
1118}
1119
1120/// Parse INSERT statement for bulk loading (extracts table, columns, and values)
1121///
1122/// This function extracts table name, optional column list, and all VALUES
1123/// from an INSERT statement without requiring a schema. It's optimized for
1124/// bulk loading into DuckDB via the Appender API.
1125pub fn parse_insert_for_bulk(stmt: &[u8], dialect: SqlDialect) -> anyhow::Result<InsertValues> {
1126    // Extract table name: INSERT INTO [schema.]table_name [(columns)] VALUES
1127    let table = extract_insert_table_name(stmt, dialect)?;
1128
1129    // Locate VALUES as a keyword (not a substring) so tables/columns containing
1130    // "values" don't shift parsing (bug #2), then extract the column list.
1131    let columns =
1132        find_values_keyword_pos(stmt).and_then(|pos| extract_column_list_before(stmt, pos));
1133
1134    // Parse rows using the existing parser
1135    let mut parser = InsertParser::new(stmt).with_dialect(dialect);
1136    let parsed_rows = parser.parse_rows()?;
1137
1138    let rows = parsed_rows.into_iter().map(|r| r.values).collect();
1139
1140    Ok(InsertValues {
1141        table,
1142        columns,
1143        rows,
1144    })
1145}
1146
1147/// Extract the table name from an INSERT statement without copying or
1148/// uppercasing the whole statement — extended INSERTs can be many MB, and the
1149/// table name lives in the first few bytes. Quote handling, schema stripping
1150/// and `IF EXISTS`/`ONLY` skipping are shared with the split path via
1151/// [`super::extract_table_name_flexible`].
1152fn extract_insert_table_name(stmt: &[u8], dialect: SqlDialect) -> anyhow::Result<String> {
1153    let stmt = super::strip_leading_comments_and_whitespace(stmt);
1154
1155    const INSERT_INTO: &[u8] = b"INSERT INTO";
1156    const INSERT: &[u8] = b"INSERT";
1157    let offset = if stmt.len() >= INSERT_INTO.len()
1158        && stmt[..INSERT_INTO.len()].eq_ignore_ascii_case(INSERT_INTO)
1159    {
1160        INSERT_INTO.len()
1161    } else if stmt.len() >= INSERT.len() && stmt[..INSERT.len()].eq_ignore_ascii_case(INSERT) {
1162        INSERT.len()
1163    } else {
1164        anyhow::bail!("Not an INSERT statement");
1165    };
1166
1167    super::extract_table_name_flexible(stmt, offset, dialect)
1168        .ok_or_else(|| anyhow::anyhow!("Empty table reference"))
1169}