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::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            PkValue::Int(i) => {
72                0u8.hash(&mut hasher);
73                i.hash(&mut hasher);
74            }
75            PkValue::BigInt(i) => {
76                1u8.hash(&mut hasher);
77                i.hash(&mut hasher);
78            }
79            PkValue::Text(s) => {
80                2u8.hash(&mut hasher);
81                s.hash(&mut hasher);
82            }
83            PkValue::Null => {
84                3u8.hash(&mut hasher);
85            }
86        }
87    }
88
89    hasher.finish()
90}
91
92/// Reference to a specific foreign key in a table
93#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
94pub struct FkRef {
95    /// Table containing the FK
96    pub table_id: u32,
97    /// Index of the FK within the table's foreign_keys vector
98    pub fk_index: u16,
99}
100
101/// A parsed row from an INSERT statement
102#[derive(Debug, Clone)]
103pub struct ParsedRow {
104    /// Raw bytes of the row value list: "(val1, val2, ...)"
105    pub raw: Vec<u8>,
106    /// Parsed values for each column (for bulk loading)
107    pub values: Vec<ParsedValue>,
108    /// Extracted primary key values (if table has PK and values are non-NULL)
109    pub pk: Option<PkTuple>,
110    /// Extracted foreign key values with their references
111    /// Only includes FKs where all columns are non-NULL
112    pub fk_values: Vec<(FkRef, PkTuple)>,
113    /// All column values (for data diff comparison).
114    /// Empty unless parsed with [`RowExtraction::Full`].
115    pub all_values: Vec<PkValue>,
116    /// Mapping from schema column index to value index (for finding specific columns).
117    /// If column_map[schema_col_idx] == Some(val_idx), then all_values[val_idx] is the value.
118    /// Shared across all rows of a statement (computed once).
119    pub column_map: Arc<[Option<usize>]>,
120}
121
122impl ParsedRow {
123    /// Get the value for a specific schema column index
124    pub fn get_column_value(&self, schema_col_index: usize) -> Option<&PkValue> {
125        self.column_map
126            .get(schema_col_index)
127            .and_then(|v| *v)
128            .and_then(|val_idx| self.all_values.get(val_idx))
129    }
130}
131
132#[inline]
133fn is_ident_byte(b: u8) -> bool {
134    b.is_ascii_alphanumeric() || b == b'_'
135}
136
137/// Copy bytes into a `String`, validating UTF-8 once and falling back to a
138/// lossy re-encode only for invalid input. Unlike `from_utf8_lossy(..).into_owned()`,
139/// the valid path is a straight validate + copy with no chunk iteration.
140#[inline]
141pub(crate) fn bytes_to_string(bytes: &[u8]) -> String {
142    match std::str::from_utf8(bytes) {
143        Ok(s) => s.to_owned(),
144        Err(_) => String::from_utf8_lossy(bytes).into_owned(),
145    }
146}
147
148/// Find the byte offset just past the `VALUES` keyword, matching it as a
149/// keyword rather than a substring: it must be word-boundaried and must not
150/// appear inside a quoted identifier (backtick / double-quote / bracket) or a
151/// string literal. This prevents tables like `product_values` or
152/// `` `order values` `` from being mistaken for the VALUES clause (bug #2).
153pub(crate) fn find_values_keyword_pos(stmt: &[u8]) -> Option<usize> {
154    let mut in_single = false;
155    let mut in_double = false;
156    let mut in_backtick = false;
157    let mut in_bracket = false;
158    let mut i = 0;
159
160    while i < stmt.len() {
161        let b = stmt[i];
162
163        if in_single {
164            // Only need to find the end of the string; treat '' as an escaped
165            // quote so we don't exit early. Backslash handling is irrelevant
166            // here because string literals only ever follow VALUES.
167            if b == b'\'' {
168                if stmt.get(i + 1) == Some(&b'\'') {
169                    i += 2;
170                    continue;
171                }
172                in_single = false;
173            }
174            i += 1;
175            continue;
176        }
177        if in_double {
178            if b == b'"' {
179                in_double = false;
180            }
181            i += 1;
182            continue;
183        }
184        if in_backtick {
185            if b == b'`' {
186                in_backtick = false;
187            }
188            i += 1;
189            continue;
190        }
191        if in_bracket {
192            if b == b']' {
193                in_bracket = false;
194            }
195            i += 1;
196            continue;
197        }
198
199        match b {
200            b'\'' => {
201                in_single = true;
202                i += 1;
203                continue;
204            }
205            b'"' => {
206                in_double = true;
207                i += 1;
208                continue;
209            }
210            b'`' => {
211                in_backtick = true;
212                i += 1;
213                continue;
214            }
215            b'[' => {
216                in_bracket = true;
217                i += 1;
218                continue;
219            }
220            _ => {}
221        }
222
223        if (b == b'V' || b == b'v')
224            && i + 6 <= stmt.len()
225            && stmt[i..i + 6].eq_ignore_ascii_case(b"VALUES")
226        {
227            let before_ok = i == 0 || !is_ident_byte(stmt[i - 1]);
228            let after_ok = stmt.get(i + 6).is_none_or(|&c| !is_ident_byte(c));
229            if before_ok && after_ok {
230                return Some(i + 6);
231            }
232        }
233
234        i += 1;
235    }
236
237    None
238}
239
240/// Extract a column list `(a, b, c)` appearing immediately before the VALUES
241/// keyword, given the byte offset just past VALUES. Shared by
242/// [`InsertParser::parse_column_list`] and [`parse_insert_for_bulk`] (bug #2).
243pub(crate) fn extract_column_list_before(stmt: &[u8], values_pos: usize) -> Option<Vec<String>> {
244    let before = &stmt[..values_pos.saturating_sub(6)];
245    let s = String::from_utf8_lossy(before);
246
247    let close = s.rfind(')')?;
248    let open = s[..close].rfind('(')?;
249    let col_list = &s[open + 1..close];
250
251    let upper = col_list.to_uppercase();
252    if col_list.trim().is_empty() || upper.contains("SELECT") {
253        return None;
254    }
255
256    let columns: Vec<String> = col_list
257        .split(',')
258        .map(|c| {
259            c.trim()
260                .trim_matches('`')
261                .trim_matches('"')
262                .trim_matches('[')
263                .trim_matches(']')
264                .to_string()
265        })
266        .collect();
267
268    if columns.is_empty() {
269        None
270    } else {
271        Some(columns)
272    }
273}
274
275/// Extract PK tuple, FK tuples and all column values from one parsed row,
276/// shared by the INSERT and COPY parsers. `to_pk` converts a dialect-specific
277/// value into a [`PkValue`]; `column_order` maps value index -> column, and
278/// `col_to_value` is its precomputed inverse (schema ordinal -> value index).
279/// `all_values` (a `PkValue` per column, often a `String` allocation) is only
280/// built when `include_all_values` is set — see [`RowExtraction`].
281#[allow(clippy::type_complexity)]
282pub(crate) fn extract_pk_fk_generic<V>(
283    values: &[V],
284    schema: &TableSchema,
285    column_order: &[Option<ColumnId>],
286    col_to_value: &[Option<usize>],
287    include_all_values: bool,
288    to_pk: impl Fn(&V, Option<&crate::schema::Column>) -> PkValue,
289) -> (Option<PkTuple>, Vec<(FkRef, PkTuple)>, Vec<PkValue>) {
290    // All column values, in value order.
291    let all_values: Vec<PkValue> = if include_all_values {
292        values
293            .iter()
294            .enumerate()
295            .map(|(idx, v)| {
296                let col = column_order
297                    .get(idx)
298                    .and_then(|c| *c)
299                    .and_then(|id| schema.column(id));
300                to_pk(v, col)
301            })
302            .collect()
303    } else {
304        Vec::new()
305    };
306
307    // PK from columns marked primary key.
308    let mut pk_values = PkTuple::new();
309    for (idx, col_id_opt) in column_order.iter().enumerate() {
310        if let Some(col_id) = col_id_opt {
311            if schema.is_pk_column(*col_id) {
312                if let Some(value) = values.get(idx) {
313                    pk_values.push(to_pk(value, schema.column(*col_id)));
314                }
315            }
316        }
317    }
318
319    // FK tuples (only when every FK column is non-NULL).
320    let mut fk_values = Vec::new();
321    for (fk_idx, fk) in schema.foreign_keys.iter().enumerate() {
322        if fk.referenced_table_id.is_none() {
323            continue;
324        }
325        let mut fk_tuple = PkTuple::new();
326        let mut all_non_null = true;
327        for &col_id in &fk.columns {
328            if let Some(idx) = col_to_value.get(col_id.0 as usize).copied().flatten() {
329                if let Some(value) = values.get(idx) {
330                    let pk_val = to_pk(value, schema.column(col_id));
331                    if pk_val.is_null() {
332                        all_non_null = false;
333                        break;
334                    }
335                    fk_tuple.push(pk_val);
336                }
337            }
338        }
339        if all_non_null && !fk_tuple.is_empty() {
340            fk_values.push((
341                FkRef {
342                    table_id: schema.id.0,
343                    fk_index: fk_idx as u16,
344                },
345                fk_tuple,
346            ));
347        }
348    }
349
350    let pk = if pk_values.is_empty() || pk_values.iter().any(|v| v.is_null()) {
351        None
352    } else {
353        Some(pk_values)
354    };
355
356    (pk, fk_values, all_values)
357}
358
359/// Parser for MySQL INSERT statements
360pub struct InsertParser<'a> {
361    stmt: &'a [u8],
362    pos: usize,
363    table_schema: Option<&'a TableSchema>,
364    /// Column order in the INSERT (maps value index -> column ID)
365    column_order: Vec<Option<ColumnId>>,
366    /// Reverse of `column_order` (schema column ordinal -> value index),
367    /// computed once per statement and shared with every row via `Arc`.
368    col_to_value: Arc<[Option<usize>]>,
369    /// Dialect governs string escaping. Only MySQL treats `\` as an escape
370    /// character; Postgres/SQLite/MSSQL treat it as a literal byte.
371    dialect: SqlDialect,
372    /// How much derived data to compute per row.
373    extraction: RowExtraction,
374}
375
376impl<'a> InsertParser<'a> {
377    /// Create a new parser for an INSERT statement (defaults to MySQL escaping)
378    pub fn new(stmt: &'a [u8]) -> Self {
379        Self {
380            stmt,
381            pos: 0,
382            table_schema: None,
383            column_order: Vec::new(),
384            col_to_value: Arc::from(Vec::new()),
385            dialect: SqlDialect::MySql,
386            extraction: RowExtraction::Full,
387        }
388    }
389
390    /// Set the table schema for PK/FK extraction
391    pub fn with_schema(mut self, schema: &'a TableSchema) -> Self {
392        self.table_schema = Some(schema);
393        self
394    }
395
396    /// Set the dialect so string values are unescaped correctly (bug #3).
397    pub fn with_dialect(mut self, dialect: SqlDialect) -> Self {
398        self.dialect = dialect;
399        self
400    }
401
402    /// Choose how much per-row derived data to compute (default: [`RowExtraction::Full`]).
403    pub fn with_extraction(mut self, extraction: RowExtraction) -> Self {
404        self.extraction = extraction;
405        self
406    }
407
408    /// Parse all rows from the INSERT statement
409    pub fn parse_rows(&mut self) -> anyhow::Result<Vec<ParsedRow>> {
410        // Find the VALUES keyword
411        let values_pos = self.find_values_keyword()?;
412        self.pos = values_pos;
413
414        // Parse column list if present
415        self.parse_column_list();
416
417        // Precompute the reverse column map once for the whole statement;
418        // rows share it via Arc instead of cloning it per row.
419        if let Some(schema) = self.table_schema {
420            let mut map = vec![None; schema.columns.len()];
421            for (val_idx, col_id_opt) in self.column_order.iter().enumerate() {
422                if let Some(col_id) = col_id_opt {
423                    let ord = col_id.0 as usize;
424                    if ord < map.len() {
425                        map[ord] = Some(val_idx);
426                    }
427                }
428            }
429            self.col_to_value = map.into();
430        }
431
432        // Parse each row
433        let mut rows = Vec::new();
434        while self.pos < self.stmt.len() {
435            self.skip_whitespace();
436
437            if self.pos >= self.stmt.len() {
438                break;
439            }
440
441            if self.stmt[self.pos] == b'(' {
442                if let Some(row) = self.parse_row()? {
443                    rows.push(row);
444                }
445            } else if self.stmt[self.pos] == b',' {
446                self.pos += 1;
447            } else if self.stmt[self.pos] == b';' {
448                break;
449            } else {
450                self.pos += 1;
451            }
452        }
453
454        Ok(rows)
455    }
456
457    /// Find the VALUES keyword and return position after it
458    fn find_values_keyword(&self) -> anyhow::Result<usize> {
459        find_values_keyword_pos(self.stmt)
460            .ok_or_else(|| anyhow::anyhow!("INSERT statement missing VALUES keyword"))
461    }
462
463    /// Parse optional column list after INSERT INTO table_name
464    fn parse_column_list(&mut self) {
465        if self.table_schema.is_none() {
466            return;
467        }
468
469        let schema = self.table_schema.unwrap();
470
471        // self.pos is just past VALUES; look for a column list immediately
472        // before it (shared with the bulk-loader path).
473        if let Some(cols) = extract_column_list_before(self.stmt, self.pos) {
474            self.column_order = cols.iter().map(|name| schema.get_column_id(name)).collect();
475            return;
476        }
477
478        // No explicit column list - use natural order
479        self.column_order = schema.columns.iter().map(|c| Some(c.ordinal)).collect();
480    }
481
482    /// Parse a single row "(val1, val2, ...)"
483    fn parse_row(&mut self) -> anyhow::Result<Option<ParsedRow>> {
484        self.skip_whitespace();
485
486        if self.pos >= self.stmt.len() || self.stmt[self.pos] != b'(' {
487            return Ok(None);
488        }
489
490        let start = self.pos;
491        self.pos += 1; // Skip '('
492
493        let mut values: Vec<ParsedValue> = Vec::new();
494        let mut depth = 1;
495
496        while self.pos < self.stmt.len() && depth > 0 {
497            self.skip_whitespace();
498
499            if self.pos >= self.stmt.len() {
500                break;
501            }
502
503            match self.stmt[self.pos] {
504                b'(' => {
505                    depth += 1;
506                    self.pos += 1;
507                }
508                b')' => {
509                    depth -= 1;
510                    self.pos += 1;
511                }
512                b',' if depth == 1 => {
513                    self.pos += 1;
514                }
515                _ if depth == 1 => {
516                    values.push(self.parse_value()?);
517                }
518                _ => {
519                    self.pos += 1;
520                }
521            }
522        }
523
524        let end = self.pos;
525        let raw = self.stmt[start..end].to_vec();
526
527        // Extract PK, FK, and (for Full extraction) all values if we have a schema
528        let (pk, fk_values, all_values) = match (self.table_schema, self.extraction) {
529            (Some(schema), RowExtraction::PkFk | RowExtraction::Full) => {
530                self.extract_pk_fk(&values, schema)
531            }
532            _ => (None, Vec::new(), Vec::new()),
533        };
534
535        Ok(Some(ParsedRow {
536            raw,
537            values,
538            pk,
539            fk_values,
540            all_values,
541            column_map: Arc::clone(&self.col_to_value),
542        }))
543    }
544
545    /// Parse a single value (string, number, NULL, etc.)
546    fn parse_value(&mut self) -> anyhow::Result<ParsedValue> {
547        self.skip_whitespace();
548
549        if self.pos >= self.stmt.len() {
550            return Ok(ParsedValue::Null);
551        }
552
553        let b = self.stmt[self.pos];
554
555        // NULL
556        if self.pos + 4 <= self.stmt.len() {
557            let word = &self.stmt[self.pos..self.pos + 4];
558            if word.eq_ignore_ascii_case(b"NULL") {
559                self.pos += 4;
560                return Ok(ParsedValue::Null);
561            }
562        }
563
564        // String literal (including MSSQL N'...' Unicode prefix)
565        if b == b'\'' {
566            return self.parse_string_value();
567        }
568
569        // MSSQL N'...' Unicode string literal
570        if (b == b'N' || b == b'n')
571            && self.pos + 1 < self.stmt.len()
572            && self.stmt[self.pos + 1] == b'\''
573        {
574            self.pos += 1; // Skip the N prefix
575            return self.parse_string_value();
576        }
577
578        // Hex literal (0x...)
579        if b == b'0' && self.pos + 1 < self.stmt.len() {
580            let next = self.stmt[self.pos + 1];
581            if next == b'x' || next == b'X' {
582                return self.parse_hex_value();
583            }
584        }
585
586        // Number or expression
587        self.parse_number_value()
588    }
589
590    /// Parse a string literal 'value'
591    fn parse_string_value(&mut self) -> anyhow::Result<ParsedValue> {
592        self.pos += 1; // Skip opening quote
593
594        // Backslash is only an escape character in MySQL. Postgres (standard
595        // strings), SQLite and MSSQL treat it as a literal byte, so applying
596        // MySQL unescaping there corrupts Windows paths, regexes, JSON, etc.
597        let honor_backslash = self.dialect == SqlDialect::MySql;
598
599        // memchr from one significant byte (quote/backslash) to the next and
600        // bulk-copy the plain bytes in between. `owned` stays empty on the
601        // fast path (no escapes at all), where the literal is a single slice.
602        let mut owned: Vec<u8> = Vec::new();
603        let mut chunk_start = self.pos;
604
605        let content_end = loop {
606            let rest = &self.stmt[self.pos..];
607            let hit = if honor_backslash {
608                memchr::memchr2(b'\'', b'\\', rest)
609            } else {
610                memchr::memchr(b'\'', rest)
611            };
612            let Some(off) = hit else {
613                // Unterminated literal: take everything to the end.
614                self.pos = self.stmt.len();
615                break self.pos;
616            };
617            self.pos += off;
618
619            if self.stmt[self.pos] == b'\\' {
620                owned.extend_from_slice(&self.stmt[chunk_start..self.pos]);
621                match self.stmt.get(self.pos + 1) {
622                    Some(&c) => {
623                        // MySQL escape sequences
624                        let escaped = match c {
625                            b'n' => b'\n',
626                            b'r' => b'\r',
627                            b't' => b'\t',
628                            b'0' => 0,
629                            _ => c, // \', \\, etc.
630                        };
631                        owned.push(escaped);
632                        self.pos += 2;
633                    }
634                    // Trailing backslash at end of statement: drop it.
635                    None => self.pos += 1,
636                }
637                chunk_start = self.pos;
638            } else if self.stmt.get(self.pos + 1) == Some(&b'\'') {
639                // Doubled quote '' is an escaped quote: keep one.
640                owned.extend_from_slice(&self.stmt[chunk_start..=self.pos]);
641                self.pos += 2;
642                chunk_start = self.pos;
643            } else {
644                let end = self.pos;
645                self.pos += 1; // Consume the closing quote
646                break end;
647            }
648        };
649
650        let tail = &self.stmt[chunk_start..content_end];
651        let value = if owned.is_empty() {
652            bytes_to_string(tail)
653        } else {
654            owned.extend_from_slice(tail);
655            // Consume the already-owned bytes without a second copy; only
656            // invalid UTF-8 falls back to the lossy re-encode.
657            match String::from_utf8(owned) {
658                Ok(s) => s,
659                Err(e) => String::from_utf8_lossy(e.as_bytes()).into_owned(),
660            }
661        };
662
663        Ok(ParsedValue::String { value })
664    }
665
666    /// Parse a hex literal 0xABCD...
667    fn parse_hex_value(&mut self) -> anyhow::Result<ParsedValue> {
668        let start = self.pos;
669        self.pos += 2; // Skip 0x
670
671        while self.pos < self.stmt.len() {
672            let b = self.stmt[self.pos];
673            if b.is_ascii_hexdigit() {
674                self.pos += 1;
675            } else {
676                break;
677            }
678        }
679
680        let raw = self.stmt[start..self.pos].to_vec();
681        Ok(ParsedValue::Hex(raw))
682    }
683
684    /// Parse a number or other non-string value
685    fn parse_number_value(&mut self) -> anyhow::Result<ParsedValue> {
686        let start = self.pos;
687        let mut has_dot = false;
688
689        // Handle leading minus
690        if self.pos < self.stmt.len() && self.stmt[self.pos] == b'-' {
691            self.pos += 1;
692        }
693
694        while self.pos < self.stmt.len() {
695            let b = self.stmt[self.pos];
696            if b.is_ascii_digit() {
697                self.pos += 1;
698            } else if b == b'.' && !has_dot {
699                has_dot = true;
700                self.pos += 1;
701            } else if b == b'e' || b == b'E' {
702                // Scientific notation
703                self.pos += 1;
704                if self.pos < self.stmt.len()
705                    && (self.stmt[self.pos] == b'+' || self.stmt[self.pos] == b'-')
706                {
707                    self.pos += 1;
708                }
709            } else if b == b',' || b == b')' || b.is_ascii_whitespace() {
710                break;
711            } else {
712                // Unknown character: this is an expression/function call rather
713                // than a plain number. Skip to the delimiter that ends this
714                // value, respecting string/identifier quotes (' and ") and
715                // nested parentheses so a value like
716                // ST_GeomFromText('POLYGON((0 0,1 1))') or CONCAT("x)y", "z")
717                // isn't split inside its own string/parens (bug #11).
718                let mut depth = 0i32;
719                let mut quote: Option<u8> = None;
720                let honor_backslash = self.dialect == SqlDialect::MySql;
721                while self.pos < self.stmt.len() {
722                    let c = self.stmt[self.pos];
723                    if let Some(q) = quote {
724                        if c == b'\\' && honor_backslash {
725                            self.pos += 2;
726                            continue;
727                        }
728                        if c == q {
729                            // A doubled quote ('' or "") stays inside.
730                            if self.stmt.get(self.pos + 1) == Some(&q) {
731                                self.pos += 2;
732                                continue;
733                            }
734                            quote = None;
735                        }
736                        self.pos += 1;
737                        continue;
738                    }
739                    match c {
740                        b'\'' | b'"' => quote = Some(c),
741                        b'(' => depth += 1,
742                        b')' if depth > 0 => depth -= 1,
743                        b')' => break,
744                        b',' if depth == 0 => break,
745                        _ => {}
746                    }
747                    self.pos += 1;
748                }
749                break;
750            }
751        }
752
753        let raw = &self.stmt[start..self.pos];
754
755        // Try to parse as integer before copying: plain integers (the common
756        // case for IDs) then need no allocation at all.
757        if !has_dot {
758            if let Ok(value_str) = std::str::from_utf8(raw) {
759                if let Ok(n) = value_str.parse::<i64>() {
760                    return Ok(ParsedValue::Integer(n));
761                }
762                if let Ok(n) = value_str.parse::<i128>() {
763                    return Ok(ParsedValue::BigInteger(n));
764                }
765            }
766        }
767
768        // Fall back to raw value
769        Ok(ParsedValue::Other(raw.to_vec()))
770    }
771
772    /// Skip whitespace and newlines
773    fn skip_whitespace(&mut self) {
774        while self.pos < self.stmt.len() {
775            let b = self.stmt[self.pos];
776            if b.is_ascii_whitespace() {
777                self.pos += 1;
778            } else {
779                break;
780            }
781        }
782    }
783
784    /// Extract PK, FK, and all values from parsed values
785    fn extract_pk_fk(
786        &self,
787        values: &[ParsedValue],
788        schema: &TableSchema,
789    ) -> (Option<PkTuple>, Vec<(FkRef, PkTuple)>, Vec<PkValue>) {
790        extract_pk_fk_generic(
791            values,
792            schema,
793            &self.column_order,
794            &self.col_to_value,
795            self.extraction == RowExtraction::Full,
796            |v, col| self.value_to_pk(v, col),
797        )
798    }
799
800    /// Convert a parsed value to a PkValue
801    fn value_to_pk(&self, value: &ParsedValue, col: Option<&crate::schema::Column>) -> PkValue {
802        match value {
803            ParsedValue::Null => PkValue::Null,
804            ParsedValue::Integer(n) => PkValue::Int(*n),
805            ParsedValue::BigInteger(n) => PkValue::BigInt(*n),
806            ParsedValue::String { value } => {
807                // Check if this might be an integer stored as string
808                if let Some(col) = col {
809                    match col.col_type {
810                        ColumnType::Int => {
811                            if let Ok(n) = value.parse::<i64>() {
812                                return PkValue::Int(n);
813                            }
814                        }
815                        ColumnType::BigInt => {
816                            if let Ok(n) = value.parse::<i128>() {
817                                return PkValue::BigInt(n);
818                            }
819                        }
820                        _ => {}
821                    }
822                }
823                PkValue::Text(value.clone().into_boxed_str())
824            }
825            ParsedValue::Hex(raw) => {
826                PkValue::Text(String::from_utf8_lossy(raw).into_owned().into_boxed_str())
827            }
828            ParsedValue::Other(raw) => {
829                PkValue::Text(String::from_utf8_lossy(raw).into_owned().into_boxed_str())
830            }
831        }
832    }
833}
834
835/// Parsed value from an INSERT statement
836///
837/// Used for bulk loading via DuckDB Appender and for PK/FK extraction.
838#[derive(Debug, Clone)]
839pub enum ParsedValue {
840    /// NULL value
841    Null,
842    /// Integer value (fits in i64)
843    Integer(i64),
844    /// Big integer value (requires i128)
845    BigInteger(i128),
846    /// String/text value (already unescaped)
847    String { value: String },
848    /// Hex literal (0xABCD...)
849    Hex(Vec<u8>),
850    /// Other value (decimals, floats, expressions) as raw bytes
851    Other(Vec<u8>),
852}
853
854/// Parse all rows from an INSERT statement using the given dialect's escaping.
855pub fn parse_insert_rows(
856    stmt: &[u8],
857    schema: &TableSchema,
858    dialect: SqlDialect,
859) -> anyhow::Result<Vec<ParsedRow>> {
860    parse_insert_rows_with(stmt, schema, dialect, RowExtraction::Full)
861}
862
863/// Like [`parse_insert_rows`], but with an explicit [`RowExtraction`] level so
864/// consumers that don't need `all_values` (or PK/FK at all) skip that work.
865pub fn parse_insert_rows_with(
866    stmt: &[u8],
867    schema: &TableSchema,
868    dialect: SqlDialect,
869    extraction: RowExtraction,
870) -> anyhow::Result<Vec<ParsedRow>> {
871    let mut parser = InsertParser::new(stmt)
872        .with_schema(schema)
873        .with_dialect(dialect)
874        .with_extraction(extraction);
875    parser.parse_rows()
876}
877
878/// Parse all rows from a MySQL INSERT statement
879pub fn parse_mysql_insert_rows(
880    stmt: &[u8],
881    schema: &TableSchema,
882) -> anyhow::Result<Vec<ParsedRow>> {
883    parse_insert_rows(stmt, schema, SqlDialect::MySql)
884}
885
886/// Parse rows without schema (just raw row extraction)
887#[allow(dead_code)]
888pub fn parse_mysql_insert_rows_raw(stmt: &[u8]) -> anyhow::Result<Vec<ParsedRow>> {
889    let mut parser = InsertParser::new(stmt);
890    parser.parse_rows()
891}
892
893#[cfg(test)]
894mod tests {
895    use super::*;
896
897    #[test]
898    fn test_parse_insert_for_bulk_simple() {
899        let sql = b"INSERT INTO users VALUES (1, 'Alice')";
900        let result = parse_insert_for_bulk(sql, SqlDialect::MySql).unwrap();
901        assert_eq!(result.table, "users");
902        assert!(result.columns.is_none());
903        assert_eq!(result.rows.len(), 1);
904    }
905
906    #[test]
907    fn test_parse_insert_for_bulk_with_columns() {
908        let sql = b"INSERT INTO users (name, id) VALUES ('Alice', 1)";
909        let result = parse_insert_for_bulk(sql, SqlDialect::MySql).unwrap();
910        assert_eq!(result.table, "users");
911        assert_eq!(
912            result.columns,
913            Some(vec!["name".to_string(), "id".to_string()])
914        );
915        assert_eq!(result.rows.len(), 1);
916    }
917
918    #[test]
919    fn test_parse_insert_for_bulk_mssql() {
920        let sql =
921            b"INSERT INTO [dbo].[users] ([email], [name]) VALUES (N'alice@example.com', N'Alice')";
922        let result = parse_insert_for_bulk(sql, SqlDialect::Mssql).unwrap();
923        assert_eq!(result.table, "users");
924        assert_eq!(
925            result.columns,
926            Some(vec!["email".to_string(), "name".to_string()])
927        );
928        assert_eq!(result.rows.len(), 1);
929    }
930
931    #[test]
932    fn test_parse_insert_for_bulk_mysql() {
933        let sql = b"INSERT INTO `users` (`id`, `name`) VALUES (1, 'Bob')";
934        let result = parse_insert_for_bulk(sql, SqlDialect::MySql).unwrap();
935        assert_eq!(result.table, "users");
936        assert_eq!(
937            result.columns,
938            Some(vec!["id".to_string(), "name".to_string()])
939        );
940        assert_eq!(result.rows.len(), 1);
941    }
942}
943
944/// Result of parsing INSERT values for bulk loading
945#[derive(Debug, Clone)]
946pub struct InsertValues {
947    /// Table name (without schema prefix or quotes)
948    pub table: String,
949    /// Column list if specified, None if using natural order
950    pub columns: Option<Vec<String>>,
951    /// Parsed rows with values
952    pub rows: Vec<Vec<ParsedValue>>,
953}
954
955/// Parse INSERT statement for bulk loading (extracts table, columns, and values)
956///
957/// This function extracts table name, optional column list, and all VALUES
958/// from an INSERT statement without requiring a schema. It's optimized for
959/// bulk loading into DuckDB via the Appender API.
960pub fn parse_insert_for_bulk(stmt: &[u8], dialect: SqlDialect) -> anyhow::Result<InsertValues> {
961    let stmt_str = String::from_utf8_lossy(stmt);
962    let upper = stmt_str.to_uppercase();
963
964    // Extract table name: INSERT INTO [schema.]table_name [(columns)] VALUES
965    let table = extract_insert_table_name(&stmt_str, &upper)?;
966
967    // Locate VALUES as a keyword (not a substring) so tables/columns containing
968    // "values" don't shift parsing (bug #2), then extract the column list.
969    let columns =
970        find_values_keyword_pos(stmt).and_then(|pos| extract_column_list_before(stmt, pos));
971
972    // Parse rows using the existing parser
973    let mut parser = InsertParser::new(stmt).with_dialect(dialect);
974    let parsed_rows = parser.parse_rows()?;
975
976    let rows = parsed_rows.into_iter().map(|r| r.values).collect();
977
978    Ok(InsertValues {
979        table,
980        columns,
981        rows,
982    })
983}
984
985/// Extract table name from INSERT statement
986fn extract_insert_table_name(stmt: &str, upper: &str) -> anyhow::Result<String> {
987    // Find "INSERT INTO" or "INSERT"
988    let start_pos = if let Some(pos) = upper.find("INSERT INTO") {
989        pos + 11 // Length of "INSERT INTO"
990    } else if let Some(pos) = upper.find("INSERT") {
991        pos + 6 // Length of "INSERT"
992    } else {
993        anyhow::bail!("Not an INSERT statement");
994    };
995
996    // Skip whitespace
997    let remaining = stmt[start_pos..].trim_start();
998
999    // Extract the full table reference (might be schema.table or just table)
1000    let table_ref = extract_table_reference(remaining)?;
1001
1002    // Strip schema prefix if present
1003    if let Some(dot_pos) = table_ref.rfind('.') {
1004        let table_part = &table_ref[dot_pos + 1..];
1005        Ok(strip_identifier_quotes(table_part))
1006    } else {
1007        Ok(strip_identifier_quotes(&table_ref))
1008    }
1009}
1010
1011/// Extract a full table reference (e.g., "[dbo].[users]" or "schema.table")
1012fn extract_table_reference(s: &str) -> anyhow::Result<String> {
1013    let s = s.trim();
1014
1015    if s.is_empty() {
1016        anyhow::bail!("Empty table reference");
1017    }
1018
1019    let mut result = String::new();
1020    let mut chars = s.chars().peekable();
1021
1022    while let Some(&c) = chars.peek() {
1023        match c {
1024            '[' => {
1025                // MSSQL bracket quoting
1026                chars.next();
1027                result.push('[');
1028                while let Some(&inner) = chars.peek() {
1029                    chars.next();
1030                    result.push(inner);
1031                    if inner == ']' {
1032                        break;
1033                    }
1034                }
1035            }
1036            '`' => {
1037                // MySQL backtick quoting
1038                chars.next();
1039                result.push('`');
1040                while let Some(&inner) = chars.peek() {
1041                    chars.next();
1042                    result.push(inner);
1043                    if inner == '`' {
1044                        break;
1045                    }
1046                }
1047            }
1048            '"' => {
1049                // PostgreSQL/SQLite double-quote
1050                chars.next();
1051                result.push('"');
1052                while let Some(&inner) = chars.peek() {
1053                    chars.next();
1054                    result.push(inner);
1055                    if inner == '"' {
1056                        break;
1057                    }
1058                }
1059            }
1060            '.' => {
1061                // Schema separator
1062                chars.next();
1063                result.push('.');
1064            }
1065            c if c.is_whitespace() || c == '(' || c == ',' => {
1066                // End of table reference
1067                break;
1068            }
1069            _ => {
1070                // Regular identifier character
1071                chars.next();
1072                result.push(c);
1073            }
1074        }
1075    }
1076
1077    if result.is_empty() {
1078        anyhow::bail!("Empty table reference");
1079    }
1080
1081    Ok(result)
1082}
1083
1084/// Strip quotes from an identifier
1085fn strip_identifier_quotes(s: &str) -> String {
1086    s.trim_matches('`')
1087        .trim_matches('"')
1088        .trim_matches('[')
1089        .trim_matches(']')
1090        .to_string()
1091}