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