1pub mod mysql_insert;
2pub mod postgres_copy;
3
4#[cfg_attr(not(feature = "duckdb-query"), allow(unused_imports))]
7pub use mysql_insert::{parse_insert_for_bulk, ParsedValue};
8
9use once_cell::sync::Lazy;
10use regex::bytes::Regex;
11use std::io::{BufRead, BufReader, Read};
12
13pub const SMALL_BUFFER_SIZE: usize = 64 * 1024;
14pub const MEDIUM_BUFFER_SIZE: usize = 256 * 1024;
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
18pub enum SqlDialect {
19 #[default]
21 MySql,
22 Postgres,
24 Sqlite,
26 Mssql,
28}
29
30impl std::str::FromStr for SqlDialect {
31 type Err = String;
32
33 fn from_str(s: &str) -> Result<Self, Self::Err> {
34 match s.to_lowercase().as_str() {
35 "mysql" | "mariadb" => Ok(SqlDialect::MySql),
36 "postgres" | "postgresql" | "pg" => Ok(SqlDialect::Postgres),
37 "sqlite" | "sqlite3" => Ok(SqlDialect::Sqlite),
38 "mssql" | "sqlserver" | "sql_server" | "tsql" => Ok(SqlDialect::Mssql),
39 _ => Err(format!(
40 "Unknown dialect: {}. Valid options: mysql, postgres, sqlite, mssql",
41 s
42 )),
43 }
44 }
45}
46
47impl std::fmt::Display for SqlDialect {
48 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
49 match self {
50 SqlDialect::MySql => write!(f, "mysql"),
51 SqlDialect::Postgres => write!(f, "postgres"),
52 SqlDialect::Sqlite => write!(f, "sqlite"),
53 SqlDialect::Mssql => write!(f, "mssql"),
54 }
55 }
56}
57
58#[derive(Debug, Clone)]
60pub struct DialectDetectionResult {
61 pub dialect: SqlDialect,
62 pub confidence: DialectConfidence,
63}
64
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
67pub enum DialectConfidence {
68 High,
70 Medium,
72 Low,
74}
75
76#[derive(Default)]
77struct DialectScore {
78 mysql: u32,
79 postgres: u32,
80 sqlite: u32,
81 mssql: u32,
82}
83
84pub fn detect_dialect(header: &[u8]) -> DialectDetectionResult {
87 let mut score = DialectScore::default();
88
89 if contains_bytes(header, b"pg_dump") {
91 score.postgres += 10;
92 }
93 if contains_bytes(header, b"PostgreSQL database dump") {
94 score.postgres += 10;
95 }
96 if contains_bytes(header, b"MySQL dump") {
97 score.mysql += 10;
98 }
99 if contains_bytes(header, b"MariaDB dump") {
100 score.mysql += 10;
101 }
102 if contains_bytes(header, b"SQLite") {
103 score.sqlite += 10;
104 }
105
106 if contains_bytes(header, b"COPY ") && contains_bytes(header, b"FROM stdin") {
108 score.postgres += 5;
109 }
110 if contains_bytes(header, b"search_path") {
111 score.postgres += 5;
112 }
113 if contains_bytes(header, b"/*!40") || contains_bytes(header, b"/*!50") {
114 score.mysql += 5;
115 }
116 if contains_bytes(header, b"LOCK TABLES") {
117 score.mysql += 5;
118 }
119 if contains_bytes(header, b"PRAGMA") {
120 score.sqlite += 5;
121 }
122
123 if contains_bytes(header, b"$$") {
125 score.postgres += 2;
126 }
127 if contains_bytes(header, b"CREATE EXTENSION") {
128 score.postgres += 2;
129 }
130 if contains_bytes(header, b"BEGIN TRANSACTION") {
132 score.sqlite += 2;
133 }
134 if header.contains(&b'`') {
136 score.mysql += 2;
137 }
138
139 if contains_bytes(header, b"SET ANSI_NULLS") {
142 score.mssql += 20;
143 }
144 if contains_bytes(header, b"SET QUOTED_IDENTIFIER") {
145 score.mssql += 20;
146 }
147
148 if contains_bytes(header, b"\nGO\n") || contains_bytes(header, b"\nGO\r\n") {
151 score.mssql += 15;
152 }
153 if header.contains(&b'[') && header.contains(&b']') {
155 score.mssql += 10;
156 }
157 if contains_bytes(header, b"IDENTITY(") {
158 score.mssql += 10;
159 }
160 if contains_bytes(header, b"ON [PRIMARY]") {
161 score.mssql += 10;
162 }
163
164 if contains_bytes(header, b"N'") {
166 score.mssql += 5;
167 }
168 if contains_bytes(header, b"NVARCHAR") {
169 score.mssql += 5;
170 }
171 if contains_bytes(header, b"CLUSTERED") {
172 score.mssql += 5;
173 }
174 if contains_bytes(header, b"SET NOCOUNT") {
175 score.mssql += 5;
176 }
177
178 let max_score = score
180 .mysql
181 .max(score.postgres)
182 .max(score.sqlite)
183 .max(score.mssql);
184
185 if max_score == 0 {
186 return DialectDetectionResult {
187 dialect: SqlDialect::MySql,
188 confidence: DialectConfidence::Low,
189 };
190 }
191
192 let (dialect, winning_score) = if score.mssql > score.mysql
194 && score.mssql > score.postgres
195 && score.mssql > score.sqlite
196 {
197 (SqlDialect::Mssql, score.mssql)
198 } else if score.postgres > score.mysql && score.postgres > score.sqlite {
199 (SqlDialect::Postgres, score.postgres)
200 } else if score.sqlite > score.mysql {
201 (SqlDialect::Sqlite, score.sqlite)
202 } else {
203 (SqlDialect::MySql, score.mysql)
204 };
205
206 let confidence = if winning_score >= 10 {
208 DialectConfidence::High
209 } else if winning_score >= 5 {
210 DialectConfidence::Medium
211 } else {
212 DialectConfidence::Low
213 };
214
215 DialectDetectionResult {
216 dialect,
217 confidence,
218 }
219}
220
221pub fn detect_dialect_from_file(path: &std::path::Path) -> std::io::Result<DialectDetectionResult> {
223 use std::fs::File;
224 use std::io::Read;
225
226 let mut file = File::open(path)?;
227 let mut buf = [0u8; 8192];
228 let n = file.read(&mut buf)?;
229 Ok(detect_dialect(&buf[..n]))
230}
231
232#[inline]
233fn contains_bytes(haystack: &[u8], needle: &[u8]) -> bool {
234 haystack
235 .windows(needle.len())
236 .any(|window| window == needle)
237}
238
239fn is_go_line(line: &[u8]) -> bool {
243 let mut start = 0;
245 while start < line.len()
246 && (line[start] == b' ' || line[start] == b'\t' || line[start] == b'\r')
247 {
248 start += 1;
249 }
250
251 let mut end = line.len();
253 while end > start
254 && (line[end - 1] == b' '
255 || line[end - 1] == b'\t'
256 || line[end - 1] == b'\r'
257 || line[end - 1] == b'\n')
258 {
259 end -= 1;
260 }
261
262 let trimmed = &line[start..end];
263
264 if trimmed.len() < 2 {
265 return false;
266 }
267
268 if trimmed.len() == 2 {
270 return (trimmed[0] == b'G' || trimmed[0] == b'g')
271 && (trimmed[1] == b'O' || trimmed[1] == b'o');
272 }
273
274 if (trimmed[0] == b'G' || trimmed[0] == b'g')
276 && (trimmed[1] == b'O' || trimmed[1] == b'o')
277 && (trimmed[2] == b' ' || trimmed[2] == b'\t')
278 {
279 let rest = &trimmed[3..];
281 let rest_trimmed = rest
282 .iter()
283 .skip_while(|&&b| b == b' ' || b == b'\t')
284 .copied()
285 .collect::<Vec<_>>();
286 return rest_trimmed.is_empty() || rest_trimmed.iter().all(|&b| b.is_ascii_digit());
287 }
288
289 false
290}
291
292#[derive(Debug, Clone, Copy, PartialEq, Eq)]
293pub enum StatementType {
294 Unknown,
295 CreateTable,
296 Insert,
297 CreateIndex,
298 AlterTable,
299 DropTable,
300 Copy,
302}
303
304impl StatementType {
305 pub fn is_schema(&self) -> bool {
307 matches!(
308 self,
309 StatementType::CreateTable
310 | StatementType::CreateIndex
311 | StatementType::AlterTable
312 | StatementType::DropTable
313 )
314 }
315
316 pub fn is_data(&self) -> bool {
318 matches!(self, StatementType::Insert | StatementType::Copy)
319 }
320}
321
322#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
324pub enum ContentFilter {
325 #[default]
327 All,
328 SchemaOnly,
330 DataOnly,
332}
333
334static CREATE_TABLE_RE: Lazy<Regex> =
335 Lazy::new(|| Regex::new(r"(?i)^\s*CREATE\s+TABLE\s+`?([^\s`(]+)`?").unwrap());
336
337static INSERT_INTO_RE: Lazy<Regex> =
338 Lazy::new(|| Regex::new(r"(?i)^\s*INSERT\s+INTO\s+`?([^\s`(]+)`?").unwrap());
339
340static CREATE_INDEX_RE: Lazy<Regex> =
341 Lazy::new(|| Regex::new(r"(?i)ON\s+`?([^\s`(;]+)`?").unwrap());
342
343static CREATE_INDEX_MSSQL_RE: Lazy<Regex> =
347 Lazy::new(|| Regex::new(r"(?i)ON\s+(?:\[?[^\[\]\s]+\]?\s*\.\s*)*\[([^\[\]]+)\]").unwrap());
348
349static ALTER_TABLE_RE: Lazy<Regex> =
350 Lazy::new(|| Regex::new(r"(?i)ALTER\s+TABLE\s+`?([^\s`;]+)`?").unwrap());
351
352static DROP_TABLE_RE: Lazy<Regex> = Lazy::new(|| {
353 Regex::new(r#"(?i)DROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?[`"]?([^\s`"`;]+)[`"]?"#).unwrap()
354});
355
356static COPY_RE: Lazy<Regex> =
358 Lazy::new(|| Regex::new(r#"(?i)^\s*COPY\s+(?:ONLY\s+)?[`"]?([^\s`"(]+)[`"]?"#).unwrap());
359
360static CREATE_TABLE_FLEXIBLE_RE: Lazy<Regex> = Lazy::new(|| {
366 Regex::new(r#"(?i)^\s*CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(?:[`"]?[\w]+[`"]?\s*\.\s*)?[`"]?([\w]+)[`"]?"#).unwrap()
367});
368
369static INSERT_FLEXIBLE_RE: Lazy<Regex> = Lazy::new(|| {
370 Regex::new(
371 r#"(?i)^\s*INSERT\s+INTO\s+(?:ONLY\s+)?(?:[`"]?[\w]+[`"]?\s*\.\s*)?[`"]?([\w]+)[`"]?"#,
372 )
373 .unwrap()
374});
375
376pub struct Parser<R: Read> {
377 reader: BufReader<R>,
378 stmt_buffer: Vec<u8>,
379 dialect: SqlDialect,
380 in_copy_data: bool,
382}
383
384impl<R: Read> Parser<R> {
385 #[allow(dead_code)]
386 pub fn new(reader: R, buffer_size: usize) -> Self {
387 Self::with_dialect(reader, buffer_size, SqlDialect::default())
388 }
389
390 pub fn with_dialect(reader: R, buffer_size: usize, dialect: SqlDialect) -> Self {
391 Self {
392 reader: BufReader::with_capacity(buffer_size, reader),
393 stmt_buffer: Vec::with_capacity(32 * 1024),
394 dialect,
395 in_copy_data: false,
396 }
397 }
398
399 pub fn read_statement(&mut self) -> std::io::Result<Option<Vec<u8>>> {
400 if self.in_copy_data {
402 return self.read_copy_data();
403 }
404
405 if self.dialect == SqlDialect::Mssql {
407 return self.read_statement_mssql();
408 }
409
410 self.stmt_buffer.clear();
411
412 let mut inside_single_quote = false;
413 let mut inside_double_quote = false;
414 let mut escaped = false;
415 let mut in_line_comment = false;
416 let mut in_dollar_quote = false;
418 let mut dollar_tag: Vec<u8> = Vec::new();
419
420 loop {
421 let buf = self.reader.fill_buf()?;
422 if buf.is_empty() {
423 if self.stmt_buffer.is_empty() {
424 return Ok(None);
425 }
426 let result = std::mem::take(&mut self.stmt_buffer);
427 return Ok(Some(result));
428 }
429
430 let mut consumed = 0;
431 let mut found_terminator = false;
432
433 for (i, &b) in buf.iter().enumerate() {
434 let inside_string = inside_single_quote || inside_double_quote || in_dollar_quote;
435
436 if in_line_comment {
438 if b == b'\n' {
439 in_line_comment = false;
440 }
441 continue;
442 }
443
444 if escaped {
445 escaped = false;
446 continue;
447 }
448
449 if b == b'\\' && inside_string && self.dialect == SqlDialect::MySql {
451 escaped = true;
452 continue;
453 }
454
455 if b == b'-' && !inside_string && i + 1 < buf.len() && buf[i + 1] == b'-' {
457 in_line_comment = true;
458 continue;
459 }
460
461 if self.dialect == SqlDialect::Postgres
463 && !inside_single_quote
464 && !inside_double_quote
465 {
466 if b == b'$' && !in_dollar_quote {
467 if let Some(end) = buf[i + 1..].iter().position(|&c| c == b'$') {
469 let tag_bytes = &buf[i + 1..i + 1 + end];
470
471 let is_valid_tag = if tag_bytes.is_empty() {
473 true
474 } else {
475 let mut iter = tag_bytes.iter();
476 match iter.next() {
477 Some(&first)
478 if first.is_ascii_alphabetic() || first == b'_' =>
479 {
480 iter.all(|&c| c.is_ascii_alphanumeric() || c == b'_')
481 }
482 _ => false,
483 }
484 };
485
486 if is_valid_tag {
487 dollar_tag = tag_bytes.to_vec();
488 in_dollar_quote = true;
489 continue;
490 }
491 }
493 } else if b == b'$' && in_dollar_quote {
494 let tag_len = dollar_tag.len();
496 if i + 1 + tag_len < buf.len()
497 && buf[i + 1..i + 1 + tag_len] == dollar_tag[..]
498 && buf.get(i + 1 + tag_len) == Some(&b'$')
499 {
500 in_dollar_quote = false;
501 dollar_tag.clear();
502 continue;
503 }
504 }
505 }
506
507 if b == b'\'' && !inside_double_quote && !in_dollar_quote {
508 inside_single_quote = !inside_single_quote;
509 } else if b == b'"' && !inside_single_quote && !in_dollar_quote {
510 inside_double_quote = !inside_double_quote;
511 } else if b == b';' && !inside_string {
512 self.stmt_buffer.extend_from_slice(&buf[..=i]);
513 consumed = i + 1;
514 found_terminator = true;
515 break;
516 }
517 }
518
519 if found_terminator {
520 self.reader.consume(consumed);
521 let result = std::mem::take(&mut self.stmt_buffer);
522
523 if self.dialect == SqlDialect::Postgres && self.is_copy_from_stdin(&result) {
525 self.in_copy_data = true;
526 }
527
528 return Ok(Some(result));
529 }
530
531 self.stmt_buffer.extend_from_slice(buf);
532 let len = buf.len();
533 self.reader.consume(len);
534 }
535 }
536
537 fn is_copy_from_stdin(&self, stmt: &[u8]) -> bool {
539 let stmt = strip_leading_comments_and_whitespace(stmt);
541 if stmt.len() < 15 {
542 return false;
544 }
545
546 let mut prefix = [0u8; 5];
548 for (i, &b) in stmt.iter().take(5).enumerate() {
549 prefix[i] = b.to_ascii_uppercase();
550 }
551 if &prefix != b"COPY " {
552 return false;
553 }
554
555 let search_len = stmt.len().min(500);
558 for i in 0..search_len.saturating_sub(10) {
559 if stmt[i..i + 10]
560 .iter()
561 .zip(b"FROM STDIN".iter())
562 .all(|(&a, &b)| a.to_ascii_uppercase() == b)
563 {
564 return true;
565 }
566 }
567 false
568 }
569
570 fn read_copy_data(&mut self) -> std::io::Result<Option<Vec<u8>>> {
572 self.stmt_buffer.clear();
573
574 loop {
575 let buf = self.reader.fill_buf()?;
577 if buf.is_empty() {
578 self.in_copy_data = false;
579 if self.stmt_buffer.is_empty() {
580 return Ok(None);
581 }
582 return Ok(Some(std::mem::take(&mut self.stmt_buffer)));
583 }
584
585 let newline_pos = buf.iter().position(|&b| b == b'\n');
587
588 if let Some(i) = newline_pos {
589 self.stmt_buffer.extend_from_slice(&buf[..=i]);
591 self.reader.consume(i + 1);
592
593 if self.ends_with_copy_terminator() {
596 self.in_copy_data = false;
597 return Ok(Some(std::mem::take(&mut self.stmt_buffer)));
598 }
599 } else {
601 let len = buf.len();
603 self.stmt_buffer.extend_from_slice(buf);
604 self.reader.consume(len);
605 }
606 }
607 }
608
609 fn ends_with_copy_terminator(&self) -> bool {
611 let data = &self.stmt_buffer;
612 if data.len() < 2 {
613 return false;
614 }
615
616 let last_newline = data[..data.len() - 1]
619 .iter()
620 .rposition(|&b| b == b'\n')
621 .map(|i| i + 1)
622 .unwrap_or(0);
623
624 let last_line = &data[last_newline..];
625
626 last_line == b"\\.\n" || last_line == b"\\.\r\n"
628 }
629
630 fn read_statement_mssql(&mut self) -> std::io::Result<Option<Vec<u8>>> {
633 self.stmt_buffer.clear();
634
635 let mut inside_single_quote = false;
636 let mut inside_bracket_quote = false;
637 let mut in_line_comment = false;
638 let mut line_start = 0usize; loop {
641 let buf = self.reader.fill_buf()?;
642 if buf.is_empty() {
643 if self.stmt_buffer.is_empty() {
644 return Ok(None);
645 }
646 let result = std::mem::take(&mut self.stmt_buffer);
647 return Ok(Some(result));
648 }
649
650 let mut consumed = 0;
651 let mut found_terminator = false;
652
653 for (i, &b) in buf.iter().enumerate() {
654 let inside_string = inside_single_quote || inside_bracket_quote;
655
656 if in_line_comment {
658 if b == b'\n' {
659 in_line_comment = false;
660 self.stmt_buffer.extend_from_slice(&buf[consumed..=i]);
662 consumed = i + 1;
663 line_start = self.stmt_buffer.len();
664 }
665 continue;
666 }
667
668 if b == b'-' && !inside_string && i + 1 < buf.len() && buf[i + 1] == b'-' {
670 in_line_comment = true;
671 continue;
672 }
673
674 if b == b'\'' && !inside_bracket_quote {
679 inside_single_quote = !inside_single_quote;
680 } else if b == b'[' && !inside_single_quote {
681 inside_bracket_quote = true;
682 } else if b == b']' && inside_bracket_quote {
683 if i + 1 < buf.len() && buf[i + 1] == b']' {
685 continue;
687 }
688 inside_bracket_quote = false;
689 } else if b == b';' && !inside_string {
690 self.stmt_buffer.extend_from_slice(&buf[consumed..=i]);
692 consumed = i + 1;
693 found_terminator = true;
694 break;
695 } else if b == b'\n' && !inside_string {
696 self.stmt_buffer.extend_from_slice(&buf[consumed..=i]);
699 consumed = i + 1;
700
701 let line = &self.stmt_buffer[line_start..];
703 if is_go_line(line) {
704 self.stmt_buffer.truncate(line_start);
706 while self
708 .stmt_buffer
709 .last()
710 .is_some_and(|&b| b == b'\n' || b == b'\r' || b == b' ' || b == b'\t')
711 {
712 self.stmt_buffer.pop();
713 }
714 if !self.stmt_buffer.is_empty() {
716 self.reader.consume(consumed);
717 let result = std::mem::take(&mut self.stmt_buffer);
718 return Ok(Some(result));
719 }
720 line_start = 0;
722 } else {
723 line_start = self.stmt_buffer.len();
725 }
726 continue;
727 }
728 }
729
730 if found_terminator {
731 self.reader.consume(consumed);
732 let result = std::mem::take(&mut self.stmt_buffer);
733 return Ok(Some(result));
734 }
735
736 if consumed < buf.len() {
738 self.stmt_buffer.extend_from_slice(&buf[consumed..]);
739 }
740 let len = buf.len();
741 self.reader.consume(len);
742 }
743 }
744
745 #[allow(dead_code)]
746 pub fn parse_statement(stmt: &[u8]) -> (StatementType, String) {
747 Self::parse_statement_with_dialect(stmt, SqlDialect::MySql)
748 }
749
750 pub fn parse_statement_with_dialect(
752 stmt: &[u8],
753 dialect: SqlDialect,
754 ) -> (StatementType, String) {
755 let stmt = strip_leading_comments_and_whitespace(stmt);
757
758 if stmt.len() < 4 {
759 return (StatementType::Unknown, String::new());
760 }
761
762 let mut upper_prefix = [0u8; 25];
764 let prefix_len = stmt.len().min(25);
765 for (i, &b) in stmt.iter().take(prefix_len).enumerate() {
766 upper_prefix[i] = b.to_ascii_uppercase();
767 }
768 let upper_prefix = &upper_prefix[..prefix_len];
769
770 if upper_prefix.starts_with(b"COPY ") {
772 if let Some(caps) = COPY_RE.captures(stmt) {
773 if let Some(m) = caps.get(1) {
774 let name = String::from_utf8_lossy(m.as_bytes()).into_owned();
775 let table_name = name.split('.').next_back().unwrap_or(&name).to_string();
777 return (StatementType::Copy, table_name);
778 }
779 }
780 }
781
782 if upper_prefix.starts_with(b"CREATE TABLE") {
783 if let Some(name) = extract_table_name_flexible(stmt, 12, dialect) {
785 return (StatementType::CreateTable, name);
786 }
787 if let Some(caps) = CREATE_TABLE_FLEXIBLE_RE.captures(stmt) {
789 if let Some(m) = caps.get(1) {
790 return (
791 StatementType::CreateTable,
792 String::from_utf8_lossy(m.as_bytes()).into_owned(),
793 );
794 }
795 }
796 if let Some(caps) = CREATE_TABLE_RE.captures(stmt) {
798 if let Some(m) = caps.get(1) {
799 return (
800 StatementType::CreateTable,
801 String::from_utf8_lossy(m.as_bytes()).into_owned(),
802 );
803 }
804 }
805 }
806
807 if upper_prefix.starts_with(b"INSERT INTO") || upper_prefix.starts_with(b"INSERT ONLY") {
808 if let Some(name) = extract_table_name_flexible(stmt, 11, dialect) {
809 return (StatementType::Insert, name);
810 }
811 if let Some(caps) = INSERT_FLEXIBLE_RE.captures(stmt) {
812 if let Some(m) = caps.get(1) {
813 return (
814 StatementType::Insert,
815 String::from_utf8_lossy(m.as_bytes()).into_owned(),
816 );
817 }
818 }
819 if let Some(caps) = INSERT_INTO_RE.captures(stmt) {
820 if let Some(m) = caps.get(1) {
821 return (
822 StatementType::Insert,
823 String::from_utf8_lossy(m.as_bytes()).into_owned(),
824 );
825 }
826 }
827 }
828
829 if upper_prefix.starts_with(b"CREATE INDEX")
830 || upper_prefix.starts_with(b"CREATE UNIQUE")
831 || upper_prefix.starts_with(b"CREATE CLUSTERED")
832 || upper_prefix.starts_with(b"CREATE NONCLUSTER")
833 {
834 if dialect == SqlDialect::Mssql {
836 if let Some(caps) = CREATE_INDEX_MSSQL_RE.captures(stmt) {
837 if let Some(m) = caps.get(1) {
838 return (
839 StatementType::CreateIndex,
840 String::from_utf8_lossy(m.as_bytes()).into_owned(),
841 );
842 }
843 }
844 }
845 if let Some(caps) = CREATE_INDEX_RE.captures(stmt) {
847 if let Some(m) = caps.get(1) {
848 return (
849 StatementType::CreateIndex,
850 String::from_utf8_lossy(m.as_bytes()).into_owned(),
851 );
852 }
853 }
854 }
855
856 if upper_prefix.starts_with(b"ALTER TABLE") {
857 if let Some(name) = extract_table_name_flexible(stmt, 11, dialect) {
858 return (StatementType::AlterTable, name);
859 }
860 if let Some(caps) = ALTER_TABLE_RE.captures(stmt) {
861 if let Some(m) = caps.get(1) {
862 return (
863 StatementType::AlterTable,
864 String::from_utf8_lossy(m.as_bytes()).into_owned(),
865 );
866 }
867 }
868 }
869
870 if upper_prefix.starts_with(b"DROP TABLE") {
871 if let Some(name) = extract_table_name_flexible(stmt, 10, dialect) {
872 return (StatementType::DropTable, name);
873 }
874 if let Some(caps) = DROP_TABLE_RE.captures(stmt) {
875 if let Some(m) = caps.get(1) {
876 return (
877 StatementType::DropTable,
878 String::from_utf8_lossy(m.as_bytes()).into_owned(),
879 );
880 }
881 }
882 }
883
884 if upper_prefix.starts_with(b"BULK INSERT") {
886 if let Some(name) = extract_table_name_flexible(stmt, 11, dialect) {
887 return (StatementType::Insert, name);
888 }
889 }
890
891 (StatementType::Unknown, String::new())
892 }
893}
894
895#[inline]
896fn trim_ascii_start(data: &[u8]) -> &[u8] {
897 let start = data
898 .iter()
899 .position(|&b| !matches!(b, b' ' | b'\t' | b'\n' | b'\r'))
900 .unwrap_or(data.len());
901 &data[start..]
902}
903
904fn strip_leading_comments_and_whitespace(mut data: &[u8]) -> &[u8] {
907 loop {
908 data = trim_ascii_start(data);
910
911 if data.len() >= 2 && data[0] == b'-' && data[1] == b'-' {
913 if let Some(pos) = data.iter().position(|&b| b == b'\n') {
915 data = &data[pos + 1..];
916 continue;
917 } else {
918 return &[];
920 }
921 }
922
923 if data.len() >= 2 && data[0] == b'/' && data[1] == b'*' {
925 let mut i = 2;
927 let mut depth = 1;
928 while i < data.len() - 1 && depth > 0 {
929 if data[i] == b'*' && data[i + 1] == b'/' {
930 depth -= 1;
931 i += 2;
932 } else if data[i] == b'/' && data[i + 1] == b'*' {
933 depth += 1;
934 i += 2;
935 } else {
936 i += 1;
937 }
938 }
939 if depth == 0 {
940 data = &data[i..];
941 continue;
942 } else {
943 return &[];
945 }
946 }
947
948 if !data.is_empty() && data[0] == b'#' {
950 if let Some(pos) = data.iter().position(|&b| b == b'\n') {
951 data = &data[pos + 1..];
952 continue;
953 } else {
954 return &[];
955 }
956 }
957
958 break;
959 }
960
961 data
962}
963
964#[inline]
970fn extract_table_name_flexible(stmt: &[u8], offset: usize, dialect: SqlDialect) -> Option<String> {
971 let mut i = offset;
972
973 while i < stmt.len() && is_whitespace(stmt[i]) {
975 i += 1;
976 }
977
978 if i >= stmt.len() {
979 return None;
980 }
981
982 let mut upper_check = [0u8; 20];
984 let check_len = (stmt.len() - i).min(20);
985 for (idx, &b) in stmt[i..].iter().take(check_len).enumerate() {
986 upper_check[idx] = b.to_ascii_uppercase();
987 }
988 let upper_slice = &upper_check[..check_len];
989 if upper_slice.starts_with(b"IF NOT EXISTS") {
990 i += 13; while i < stmt.len() && is_whitespace(stmt[i]) {
992 i += 1;
993 }
994 } else if upper_slice.starts_with(b"IF EXISTS") {
995 i += 9; while i < stmt.len() && is_whitespace(stmt[i]) {
997 i += 1;
998 }
999 }
1000
1001 let only_check = if i < stmt.len() {
1003 let mut buf = [0u8; 10];
1004 let len = (stmt.len() - i).min(10);
1005 for (idx, &b) in stmt[i..].iter().take(len).enumerate() {
1006 buf[idx] = b.to_ascii_uppercase();
1007 }
1008 (buf, len)
1009 } else {
1010 ([0u8; 10], 0)
1011 };
1012 let only_slice = &only_check.0[..only_check.1];
1013 if only_slice.starts_with(b"ONLY ") || only_slice.starts_with(b"ONLY\t") {
1014 i += 4;
1015 while i < stmt.len() && is_whitespace(stmt[i]) {
1016 i += 1;
1017 }
1018 }
1019
1020 if i >= stmt.len() {
1021 return None;
1022 }
1023
1024 let mut parts: Vec<String> = Vec::new();
1026
1027 loop {
1028 let (quote_char, close_char) = match stmt.get(i) {
1030 Some(b'`') if dialect == SqlDialect::MySql => {
1031 i += 1;
1032 (Some(b'`'), b'`')
1033 }
1034 Some(b'"') if dialect != SqlDialect::MySql => {
1035 i += 1;
1036 (Some(b'"'), b'"')
1037 }
1038 Some(b'"') => {
1039 i += 1;
1041 (Some(b'"'), b'"')
1042 }
1043 Some(b'[') if dialect == SqlDialect::Mssql => {
1044 i += 1;
1046 (Some(b'['), b']')
1047 }
1048 _ => (None, 0),
1049 };
1050
1051 let start = i;
1052
1053 while i < stmt.len() {
1054 let b = stmt[i];
1055 if quote_char.is_some() {
1056 if b == close_char {
1057 if dialect == SqlDialect::Mssql
1059 && close_char == b']'
1060 && i + 1 < stmt.len()
1061 && stmt[i + 1] == b']'
1062 {
1063 i += 2;
1065 continue;
1066 }
1067 let name = &stmt[start..i];
1068 let name_str = if dialect == SqlDialect::Mssql {
1070 String::from_utf8_lossy(name).replace("]]", "]")
1071 } else {
1072 String::from_utf8_lossy(name).into_owned()
1073 };
1074 parts.push(name_str);
1075 i += 1; break;
1077 }
1078 } else if is_whitespace(b) || b == b'(' || b == b';' || b == b',' || b == b'.' {
1079 if i > start {
1080 let name = &stmt[start..i];
1081 parts.push(String::from_utf8_lossy(name).into_owned());
1082 }
1083 break;
1084 }
1085 i += 1;
1086 }
1087
1088 if quote_char.is_some() && i <= start {
1090 break;
1091 }
1092
1093 while i < stmt.len() && is_whitespace(stmt[i]) {
1095 i += 1;
1096 }
1097
1098 if i < stmt.len() && stmt[i] == b'.' {
1099 i += 1; while i < stmt.len() && is_whitespace(stmt[i]) {
1101 i += 1;
1102 }
1103 } else {
1105 break;
1106 }
1107 }
1108
1109 parts.pop()
1111}
1112
1113#[inline]
1114fn is_whitespace(b: u8) -> bool {
1115 matches!(b, b' ' | b'\t' | b'\n' | b'\r')
1116}
1117
1118pub fn determine_buffer_size(file_size: u64) -> usize {
1119 if file_size > 1024 * 1024 * 1024 {
1120 MEDIUM_BUFFER_SIZE
1121 } else {
1122 SMALL_BUFFER_SIZE
1123 }
1124}