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