1use crate::parser::{RowFlow, SqlDialect};
7use crate::schema::{ColumnId, ColumnType, TableSchema};
8use ahash::AHashSet;
9use smallvec::SmallVec;
10use std::sync::Arc;
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
18pub enum RowExtraction {
19 ValuesOnly,
21 PkFk,
23 #[default]
26 Full,
27}
28
29#[derive(Debug, Clone, PartialEq, Eq, Hash)]
31pub enum PkValue {
32 Int(i64),
34 BigInt(i128),
36 Text(Box<str>),
38 Null,
40}
41
42impl PkValue {
43 pub fn is_null(&self) -> bool {
45 matches!(self, PkValue::Null)
46 }
47}
48
49pub type PkTuple = SmallVec<[PkValue; 2]>;
51
52pub type PkSet = AHashSet<PkTuple>;
54
55pub type PkHashSet = AHashSet<u64>;
59
60pub fn hash_pk_tuple(pk: &PkTuple) -> u64 {
63 use std::hash::{Hash, Hasher};
64 let mut hasher = ahash::AHasher::default();
65
66 (pk.len() as u8).hash(&mut hasher);
68
69 for v in pk {
70 match v {
71 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
98pub struct FkRef {
99 pub table_id: u32,
101 pub fk_index: u16,
103}
104
105#[derive(Debug, Clone)]
107pub struct ParsedRow {
108 pub raw: Vec<u8>,
110 pub values: Vec<ParsedValue>,
112 pub pk: Option<PkTuple>,
114 pub fk_values: Vec<(FkRef, PkTuple)>,
117 pub all_values: Vec<PkValue>,
120 pub column_map: Arc<[Option<usize>]>,
124}
125
126impl ParsedRow {
127 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#[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
152pub(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 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
244pub(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
279pub(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
298pub(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#[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 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 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 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
394pub struct InsertParser<'a> {
396 stmt: &'a [u8],
397 pos: usize,
398 table_schema: Option<&'a TableSchema>,
399 column_order: Vec<Option<ColumnId>>,
401 col_to_value: Arc<[Option<usize>]>,
404 dialect: SqlDialect,
407 extraction: RowExtraction,
409 last_complete: bool,
413}
414
415impl<'a> InsertParser<'a> {
416 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 pub fn with_schema(mut self, schema: &'a TableSchema) -> Self {
432 self.table_schema = Some(schema);
433 self
434 }
435
436 pub fn with_dialect(mut self, dialect: SqlDialect) -> Self {
438 self.dialect = dialect;
439 self
440 }
441
442 pub fn with_extraction(mut self, extraction: RowExtraction) -> Self {
444 self.extraction = extraction;
445 self
446 }
447
448 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 pub fn parse_rows_visit<F>(&mut self, mut f: F) -> anyhow::Result<()>
465 where
466 F: FnMut(ParsedRow) -> anyhow::Result<RowFlow>,
467 {
468 let values_pos = self.find_values_keyword()?;
470 self.pos = values_pos;
471
472 self.parse_column_list();
474
475 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 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 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 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 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 self.column_order = schema.columns.iter().map(|c| Some(c.ordinal)).collect();
530 }
531
532 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; 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 self.last_complete = depth == 0;
578
579 let end = self.pos;
580 let raw = self.stmt[start..end].to_vec();
581
582 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 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 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 if b == b'\'' {
621 return self.parse_string_value();
622 }
623
624 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; return self.parse_string_value();
631 }
632
633 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 self.parse_number_value()
643 }
644
645 fn parse_string_value(&mut self) -> ParsedValue {
647 self.pos += 1; let honor_backslash = self.dialect == SqlDialect::MySql;
653
654 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 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 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, };
686 owned.push(escaped);
687 self.pos += 2;
688 }
689 None => self.pos += 1,
691 }
692 chunk_start = self.pos;
693 } else if self.stmt.get(self.pos + 1) == Some(&b'\'') {
694 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; 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 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 fn parse_hex_value(&mut self) -> ParsedValue {
723 let start = self.pos;
724 self.pos += 2; 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 fn parse_number_value(&mut self) -> ParsedValue {
741 let start = self.pos;
742 let mut has_dot = false;
743
744 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 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 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 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 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 ParsedValue::Other(raw.to_vec())
825 }
826
827 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 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 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 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#[derive(Debug, Clone)]
880pub enum ParsedValue {
881 Null,
883 Integer(i64),
885 BigInteger(i128),
887 String { value: String },
889 Hex(Vec<u8>),
891 Other(Vec<u8>),
893}
894
895pub 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
904pub 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
924pub 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
944pub struct InsertRowContext {
951 column_order: Vec<Option<ColumnId>>,
952 col_to_value: Arc<[Option<usize>]>,
953}
954
955impl InsertRowContext {
956 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
974pub 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
994pub(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 p.parse_row()?;
1007 Some((p.pos, p.last_complete))
1008}
1009
1010pub 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
1018pub 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#[derive(Debug, Clone)]
1077pub struct InsertValues {
1078 pub table: String,
1080 pub columns: Option<Vec<String>>,
1082 pub rows: Vec<Vec<ParsedValue>>,
1084}
1085
1086pub fn parse_insert_for_bulk(stmt: &[u8], dialect: SqlDialect) -> anyhow::Result<InsertValues> {
1092 let table = extract_insert_table_name(stmt, dialect)?;
1094
1095 let columns =
1098 find_values_keyword_pos(stmt).and_then(|pos| extract_column_list_before(stmt, pos));
1099
1100 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
1113fn 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}