1pub mod copy_to_insert;
12mod types;
13mod warnings;
14
15#[allow(unused_imports)]
16pub use copy_to_insert::{
17 copy_to_inserts, parse_copy_data, parse_copy_header, CopyHeader, CopyValue,
18};
19
20use crate::parser::{Parser, SqlDialect, StatementType};
21use crate::splitter::{open_input, open_input_with_progress};
22use indicatif::{ProgressBar, ProgressStyle};
23use std::collections::HashMap;
24use std::fs::File;
25use std::io::{BufWriter, Read, Write};
26use std::path::PathBuf;
27
28pub use types::TypeMapper;
29#[allow(unused_imports)]
33pub(crate) use types::map_column_type;
34pub use warnings::{print_warnings_summary, ConvertWarning, WarningCollector};
35
36#[derive(Debug)]
38pub struct ConvertConfig {
39 pub input: PathBuf,
41 pub output: Option<PathBuf>,
43 pub from_dialect: Option<SqlDialect>,
45 pub to_dialect: SqlDialect,
47 pub dry_run: bool,
49 pub progress: bool,
51 pub strict: bool,
53}
54
55impl Default for ConvertConfig {
56 fn default() -> Self {
57 Self {
58 input: PathBuf::new(),
59 output: None,
60 from_dialect: None,
61 to_dialect: SqlDialect::Postgres,
62 dry_run: false,
63 progress: false,
64 strict: false,
65 }
66 }
67}
68
69#[derive(Debug, Default, serde::Serialize)]
71pub struct ConvertStats {
72 pub statements_processed: u64,
74 pub statements_converted: u64,
76 pub statements_unchanged: u64,
78 pub statements_skipped: u64,
80 pub warnings: Vec<ConvertWarning>,
82}
83
84pub struct Converter {
86 from: SqlDialect,
87 to: SqlDialect,
88 warnings: WarningCollector,
89 strict: bool,
90 pending_copy_header: Option<CopyHeader>,
92 created_tables: HashMap<String, String>,
97 deferred: Vec<String>,
100}
101
102fn table_key(name: &str) -> String {
105 name.rsplit('.')
106 .next()
107 .unwrap_or(name)
108 .trim_matches(|c| c == '"' || c == '`' || c == '[' || c == ']')
109 .to_lowercase()
110}
111
112fn declared_column_type(create_table: &str, column: &str) -> Option<String> {
122 use regex::Regex;
123
124 let pattern = format!(
125 r#"(?i)[(,]\s*[`"\[]?{}[`"\]]?\s+(?P<type>[A-Za-z]+(?:\s*\(\s*\d+\s*\))?)"#,
126 regex::escape(column)
127 );
128 let captures = Regex::new(&pattern).ok()?.captures(create_table)?;
129 Some(captures.name("type")?.as_str().trim().to_string())
130}
131
132impl Converter {
133 pub fn new(from: SqlDialect, to: SqlDialect) -> Self {
134 Self {
135 from,
136 to,
137 warnings: WarningCollector::new(),
138 strict: false,
139 pending_copy_header: None,
140 created_tables: HashMap::new(),
141 deferred: Vec::new(),
142 }
143 }
144
145 pub fn take_deferred_statements(&mut self) -> Vec<String> {
149 std::mem::take(&mut self.deferred)
150 }
151
152 pub fn with_strict(mut self, strict: bool) -> Self {
153 self.strict = strict;
154 self
155 }
156
157 pub fn has_pending_copy(&self) -> bool {
159 self.pending_copy_header.is_some()
160 }
161
162 pub fn process_copy_data(&mut self, data: &[u8]) -> Result<Vec<Vec<u8>>, ConvertWarning> {
164 if let Some(header) = self.pending_copy_header.take() {
165 if self.from == SqlDialect::Postgres && self.to != SqlDialect::Postgres {
166 let inserts = copy_to_inserts(&header, data, self.to);
168 return Ok(inserts);
169 }
170 }
171 Ok(vec![data.to_vec()])
173 }
174
175 pub fn convert_statement(&mut self, stmt: &[u8]) -> Result<Vec<u8>, ConvertWarning> {
177 let (stmt_type, table_name) =
178 Parser::<&[u8]>::parse_statement_with_dialect(stmt, self.from);
179
180 let table = if table_name.is_empty() {
181 None
182 } else {
183 Some(table_name.as_str())
184 };
185
186 match stmt_type {
187 StatementType::CreateTable => self.convert_create_table(stmt, table),
188 StatementType::Insert => self.convert_insert(stmt, table),
189 StatementType::CreateIndex => self.convert_create_index(stmt),
190 StatementType::AlterTable => self.convert_alter_table(stmt),
191 StatementType::DropTable => self.convert_drop_table(stmt),
192 StatementType::Copy => self.convert_copy(stmt, table),
193 StatementType::Unknown => self.convert_other(stmt),
194 }
195 }
196
197 fn convert_create_table(
199 &mut self,
200 stmt: &[u8],
201 table_name: Option<&str>,
202 ) -> Result<Vec<u8>, ConvertWarning> {
203 let stmt_str = String::from_utf8_lossy(stmt);
204 let mut result = stmt_str.to_string();
205
206 self.detect_unsupported_features(&result, table_name)?;
208
209 if self.from == SqlDialect::Mssql && self.to != SqlDialect::Mssql {
212 result = self.strip_mssql_schema_prefix(&result);
213 result = self.convert_mssql_getdate(&result);
214 result = self.strip_mssql_on_filegroup(&result);
215 result = self.strip_mssql_clustered(&result);
216 result = self.convert_mssql_unicode_strings(&result);
217 }
218
219 result = self.convert_identifiers(&result);
221
222 result = self.convert_data_types(&result);
224
225 result = self.convert_auto_increment(&result, table_name);
227
228 if self.from == SqlDialect::Postgres && self.to != SqlDialect::Postgres {
230 result = self.strip_postgres_casts(&result);
231 result = self.convert_nextval(&result);
232 result = self.convert_default_now(&result);
233 result = self.strip_schema_prefix(&result);
234 }
235
236 result = self.convert_string_escapes(&result);
238
239 result = self.strip_conditional_comments(&result);
241
242 result = self.strip_engine_clause(&result);
244
245 result = self.strip_charset_clauses(&result);
247
248 result = self.strip_mysql_comment_clauses(&result);
250
251 result = self.convert_unique_key_constraint(&result);
253
254 if self.to == SqlDialect::MySql {
259 if let Some(name) = table_name {
260 self.created_tables.insert(table_key(name), result.clone());
261 }
262 }
263
264 Ok(result.into_bytes())
265 }
266
267 fn convert_insert(
269 &mut self,
270 stmt: &[u8],
271 _table_name: Option<&str>,
272 ) -> Result<Vec<u8>, ConvertWarning> {
273 let stmt_str = String::from_utf8_lossy(stmt);
274 let mut result = stmt_str.to_string();
275
276 if self.from == SqlDialect::Mssql && self.to != SqlDialect::Mssql {
278 result = self.strip_mssql_schema_prefix(&result);
279 result = self.convert_mssql_unicode_strings(&result);
280 }
281
282 result = self.convert_identifiers(&result);
284
285 if self.from == SqlDialect::Postgres && self.to != SqlDialect::Postgres {
287 result = self.strip_postgres_casts(&result);
288 result = self.strip_schema_prefix(&result);
289 }
290
291 result = self.convert_string_escapes(&result);
293
294 Ok(result.into_bytes())
295 }
296
297 fn convert_create_index(&mut self, stmt: &[u8]) -> Result<Vec<u8>, ConvertWarning> {
299 let stmt_str = String::from_utf8_lossy(stmt);
300 let mut result = stmt_str.to_string();
301
302 if self.from == SqlDialect::Mssql && self.to != SqlDialect::Mssql {
304 result = self.strip_mssql_schema_prefix(&result);
305 result = self.strip_mssql_clustered(&result);
306 }
307
308 result = self.convert_identifiers(&result);
310
311 if self.from == SqlDialect::Postgres && self.to != SqlDialect::Postgres {
313 result = self.strip_postgres_casts(&result);
314 result = self.strip_schema_prefix(&result);
315 }
316
317 if result.contains("FULLTEXT") || result.contains("fulltext") {
319 self.warnings.add(ConvertWarning::UnsupportedFeature {
320 feature: "FULLTEXT INDEX".to_string(),
321 suggestion: Some("Use PostgreSQL GIN index or skip".to_string()),
322 });
323 if self.strict {
324 return Err(ConvertWarning::UnsupportedFeature {
325 feature: "FULLTEXT INDEX".to_string(),
326 suggestion: None,
327 });
328 }
329 }
330
331 Ok(result.into_bytes())
332 }
333
334 fn convert_alter_table(&mut self, stmt: &[u8]) -> Result<Vec<u8>, ConvertWarning> {
336 let stmt_str = String::from_utf8_lossy(stmt);
337 let mut result = stmt_str.to_string();
338
339 if self.from == SqlDialect::Postgres
345 && self.to != SqlDialect::Postgres
346 && self.is_sequence_default_alter(&result)
347 {
348 if let Some(restored) = self.defer_mysql_auto_increment(&result) {
349 self.deferred.push(restored);
350 return Ok(Vec::new());
351 }
352 let preview = self.strip_leading_sql_comments(&result);
353 self.warnings.add(ConvertWarning::SkippedStatement {
354 reason: "sequence-backed column default has no equivalent".to_string(),
355 statement_preview: preview.trim().chars().take(60).collect(),
356 });
357 return Ok(Vec::new());
358 }
359
360 result = self.convert_identifiers(&result);
361 result = self.convert_data_types(&result);
362
363 if self.from == SqlDialect::Postgres && self.to != SqlDialect::Postgres {
365 result = self.strip_postgres_casts(&result);
366 result = self.convert_nextval(&result);
367 result = self.convert_default_now(&result);
368 result = self.strip_schema_prefix(&result);
369 result = self.strip_postgres_only(&result);
370 }
371
372 if self.to == SqlDialect::Sqlite {
377 if let Some(rewritten) = self.rewrite_add_constraint_for_sqlite(&result) {
378 return Ok(rewritten.into_bytes());
379 }
380 }
381
382 Ok(result.into_bytes())
383 }
384
385 fn rewrite_add_constraint_for_sqlite(&mut self, stmt: &str) -> Option<String> {
397 use once_cell::sync::Lazy;
398 use regex::Regex;
399
400 static RE_ADD_CONSTRAINT: Lazy<Regex> = Lazy::new(|| {
401 Regex::new(
402 r"(?is)^\s*ALTER\s+TABLE\s+(?P<table>\S+)\s+ADD\s+CONSTRAINT\s+(?P<name>[^\s(]+)\s+(?P<kind>UNIQUE|PRIMARY\s+KEY|FOREIGN\s+KEY|CHECK)\b(?P<rest>.*)$",
403 )
404 .unwrap()
405 });
406 static RE_LEADING_COLUMNS: Lazy<Regex> =
407 Lazy::new(|| Regex::new(r"(?s)^\s*\(([^)]*)\)").unwrap());
408
409 let body = self.strip_leading_sql_comments(stmt);
412 let caps = RE_ADD_CONSTRAINT.captures(&body)?;
413 let kind = caps["kind"]
414 .split_whitespace()
415 .collect::<Vec<_>>()
416 .join(" ");
417 let kind = kind.to_uppercase();
418
419 if kind == "UNIQUE" || kind == "PRIMARY KEY" {
420 if let Some(columns) = RE_LEADING_COLUMNS.captures(&caps["rest"]) {
421 if kind == "PRIMARY KEY" {
422 self.warnings.add(ConvertWarning::UnsupportedFeature {
423 feature: format!("PRIMARY KEY added to existing table {}", &caps["table"]),
424 suggestion: Some(
425 "re-expressed as a UNIQUE INDEX; SQLite only accepts a \
426 primary key inside CREATE TABLE"
427 .to_string(),
428 ),
429 });
430 }
431 return Some(format!(
432 "CREATE UNIQUE INDEX {} ON {} ({});",
433 &caps["name"],
434 &caps["table"],
435 columns[1].trim()
436 ));
437 }
438 }
439
440 self.warnings.add(ConvertWarning::SkippedStatement {
441 reason: format!("SQLite cannot add a {kind} constraint to an existing table"),
442 statement_preview: body.trim().chars().take(60).collect(),
443 });
444 Some(String::new())
445 }
446
447 fn convert_drop_table(&mut self, stmt: &[u8]) -> Result<Vec<u8>, ConvertWarning> {
449 let stmt_str = String::from_utf8_lossy(stmt);
450 let mut result = stmt_str.to_string();
451
452 result = self.convert_identifiers(&result);
453
454 if self.from == SqlDialect::Postgres && self.to != SqlDialect::Postgres {
456 result = self.strip_schema_prefix(&result);
457 }
458
459 Ok(result.into_bytes())
460 }
461
462 fn convert_copy(
467 &mut self,
468 stmt: &[u8],
469 _table_name: Option<&str>,
470 ) -> Result<Vec<u8>, ConvertWarning> {
471 let stmt_str = String::from_utf8_lossy(stmt);
472
473 let upper = stmt_str.to_uppercase();
475 if upper.contains("FROM STDIN") {
476 if let Some(header) = parse_copy_header(&stmt_str) {
478 if self.from == SqlDialect::Postgres && self.to != SqlDialect::Postgres {
479 self.pending_copy_header = Some(header);
481 return Ok(Vec::new());
483 }
484 }
485 }
486
487 Ok(stmt.to_vec())
489 }
490
491 fn convert_other(&mut self, stmt: &[u8]) -> Result<Vec<u8>, ConvertWarning> {
493 let stmt_str = String::from_utf8_lossy(stmt);
494 let result = stmt_str.to_string();
495 let trimmed = result.trim();
496
497 if self.from == SqlDialect::MySql
499 && self.to != SqlDialect::MySql
500 && self.is_mysql_session_command(&result)
501 {
502 return Ok(Vec::new()); }
504
505 if self.from == SqlDialect::Postgres
507 && self.to != SqlDialect::Postgres
508 && self.is_postgres_session_command(&result)
509 {
510 return Ok(Vec::new()); }
512 if self.from == SqlDialect::Postgres
517 && self.to != SqlDialect::Postgres
518 && self.is_psql_meta_command(trimmed)
519 {
520 return Ok(Vec::new()); }
522 if self.from == SqlDialect::Postgres
523 && self.to != SqlDialect::Postgres
524 && self.is_postgres_only_feature(trimmed)
525 {
526 self.warnings.add(ConvertWarning::SkippedStatement {
527 reason: "PostgreSQL-only feature".to_string(),
528 statement_preview: trimmed.chars().take(60).collect(),
529 });
530 return Ok(Vec::new()); }
532
533 if self.from == SqlDialect::Sqlite
535 && self.to != SqlDialect::Sqlite
536 && self.is_sqlite_pragma(&result)
537 {
538 return Ok(Vec::new()); }
540
541 if self.from == SqlDialect::Mssql
543 && self.to != SqlDialect::Mssql
544 && self.is_mssql_session_command(&result)
545 {
546 return Ok(Vec::new()); }
548
549 if result.contains("/*!") {
551 let stripped = self.strip_conditional_comments(&result);
552 return Ok(stripped.into_bytes());
553 }
554
555 Ok(stmt.to_vec())
556 }
557
558 fn is_mysql_session_command(&self, stmt: &str) -> bool {
560 let upper = stmt.to_uppercase();
561 upper.contains("SET NAMES")
562 || upper.contains("SET CHARACTER")
563 || upper.contains("SET SQL_MODE")
564 || upper.contains("SET TIME_ZONE")
565 || upper.contains("SET FOREIGN_KEY_CHECKS")
566 || upper.contains("LOCK TABLES")
567 || upper.contains("UNLOCK TABLES")
568 }
569
570 fn is_postgres_session_command(&self, stmt: &str) -> bool {
572 let upper = stmt.to_uppercase();
573 upper.contains("SET CLIENT_ENCODING")
575 || upper.contains("SET STANDARD_CONFORMING_STRINGS")
576 || upper.contains("SET CHECK_FUNCTION_BODIES")
577 || upper.contains("SET SEARCH_PATH")
578 || upper.contains("SET DEFAULT_TABLESPACE")
579 || upper.contains("SET LOCK_TIMEOUT")
580 || upper.contains("SET IDLE_IN_TRANSACTION_SESSION_TIMEOUT")
581 || upper.contains("SET ROW_SECURITY")
582 || upper.contains("SET STATEMENT_TIMEOUT")
583 || upper.contains("SET XMLOPTION")
584 || upper.contains("SET CLIENT_MIN_MESSAGES")
585 || upper.contains("SET DEFAULT_TABLE_ACCESS_METHOD")
586 || upper.contains("SELECT PG_CATALOG")
587 || upper.contains("OWNER TO")
589 || upper.contains("GRANT ")
590 || upper.contains("REVOKE ")
591 }
592
593 fn is_postgres_only_feature(&self, stmt: &str) -> bool {
595 let stripped = self.strip_leading_sql_comments(stmt);
597 let upper = stripped.to_uppercase();
598
599 upper.starts_with("CREATE DOMAIN")
601 || upper.starts_with("CREATE TYPE")
602 || upper.starts_with("CREATE FUNCTION")
603 || upper.starts_with("CREATE PROCEDURE")
604 || upper.starts_with("CREATE AGGREGATE")
605 || upper.starts_with("CREATE OPERATOR")
606 || upper.starts_with("CREATE SEQUENCE")
607 || upper.starts_with("CREATE EXTENSION")
608 || upper.starts_with("CREATE SCHEMA")
609 || upper.starts_with("CREATE TRIGGER")
610 || upper.starts_with("ALTER DOMAIN")
611 || upper.starts_with("ALTER TYPE")
612 || upper.starts_with("ALTER FUNCTION")
613 || upper.starts_with("ALTER SEQUENCE")
614 || upper.starts_with("ALTER SCHEMA")
615 || upper.starts_with("COMMENT ON")
616 }
617
618 fn strip_leading_sql_comments(&self, stmt: &str) -> String {
620 let mut result = stmt.trim();
621 loop {
622 if result.starts_with("--") {
624 if let Some(pos) = result.find('\n') {
625 result = result[pos + 1..].trim();
626 continue;
627 } else {
628 return String::new();
629 }
630 }
631 if result.starts_with("/*") {
633 if let Some(pos) = result.find("*/") {
634 result = result[pos + 2..].trim();
635 continue;
636 } else {
637 return String::new();
638 }
639 }
640 break;
641 }
642 result.to_string()
643 }
644
645 fn is_sqlite_pragma(&self, stmt: &str) -> bool {
647 let upper = stmt.to_uppercase();
648 upper.contains("PRAGMA")
649 }
650
651 fn is_mssql_session_command(&self, stmt: &str) -> bool {
653 let upper = stmt.to_uppercase();
654 upper.contains("SET ANSI_NULLS")
655 || upper.contains("SET QUOTED_IDENTIFIER")
656 || upper.contains("SET NOCOUNT")
657 || upper.contains("SET XACT_ABORT")
658 || upper.contains("SET ARITHABORT")
659 || upper.contains("SET ANSI_WARNINGS")
660 || upper.contains("SET ANSI_PADDING")
661 || upper.contains("SET CONCAT_NULL_YIELDS_NULL")
662 || upper.contains("SET NUMERIC_ROUNDABORT")
663 || upper.contains("SET IDENTITY_INSERT")
664 }
665
666 fn convert_identifiers(&self, stmt: &str) -> String {
668 match (self.from, self.to) {
669 (SqlDialect::MySql, SqlDialect::Postgres | SqlDialect::Sqlite) => {
670 self.backticks_to_double_quotes(stmt)
672 }
673 (SqlDialect::MySql, SqlDialect::Mssql) => {
674 self.backticks_to_square_brackets(stmt)
676 }
677 (SqlDialect::Postgres | SqlDialect::Sqlite, SqlDialect::MySql) => {
678 self.double_quotes_to_backticks(stmt)
680 }
681 (SqlDialect::Postgres | SqlDialect::Sqlite, SqlDialect::Mssql) => {
682 self.double_quotes_to_square_brackets(stmt)
684 }
685 (SqlDialect::Mssql, SqlDialect::MySql) => {
686 self.square_brackets_to_backticks(stmt)
688 }
689 (SqlDialect::Mssql, SqlDialect::Postgres | SqlDialect::Sqlite) => {
690 self.square_brackets_to_double_quotes(stmt)
692 }
693 _ => stmt.to_string(),
694 }
695 }
696
697 pub fn backticks_to_double_quotes(&self, stmt: &str) -> String {
699 let mut result = String::with_capacity(stmt.len());
700 let mut in_string = false;
701 let mut in_backtick = false;
702
703 for c in stmt.chars() {
704 if c == '\'' && !in_backtick {
705 in_string = !in_string;
706 result.push(c);
707 } else if c == '`' && !in_string {
708 in_backtick = !in_backtick;
709 result.push('"');
710 } else {
711 result.push(c);
712 }
713 }
714 result
715 }
716
717 pub fn double_quotes_to_backticks(&self, stmt: &str) -> String {
719 let mut result = String::with_capacity(stmt.len());
720 let mut in_string = false;
721 let mut in_dquote = false;
722 let chars = stmt.chars();
723
724 for c in chars {
725 if c == '\'' && !in_dquote {
726 in_string = !in_string;
727 result.push(c);
728 } else if c == '"' && !in_string {
729 in_dquote = !in_dquote;
730 result.push('`');
731 } else {
732 result.push(c);
733 }
734 }
735 result
736 }
737
738 pub fn backticks_to_square_brackets(&self, stmt: &str) -> String {
740 let mut result = String::with_capacity(stmt.len());
741 let mut in_string = false;
742 let mut in_backtick = false;
743
744 for c in stmt.chars() {
745 if c == '\'' && !in_backtick {
746 in_string = !in_string;
747 result.push(c);
748 } else if c == '`' && !in_string {
749 if !in_backtick {
750 result.push('[');
751 } else {
752 result.push(']');
753 }
754 in_backtick = !in_backtick;
755 } else {
756 result.push(c);
757 }
758 }
759 result
760 }
761
762 pub fn double_quotes_to_square_brackets(&self, stmt: &str) -> String {
764 let mut result = String::with_capacity(stmt.len());
765 let mut in_string = false;
766 let mut in_dquote = false;
767
768 for c in stmt.chars() {
769 if c == '\'' && !in_dquote {
770 in_string = !in_string;
771 result.push(c);
772 } else if c == '"' && !in_string {
773 if !in_dquote {
774 result.push('[');
775 } else {
776 result.push(']');
777 }
778 in_dquote = !in_dquote;
779 } else {
780 result.push(c);
781 }
782 }
783 result
784 }
785
786 pub fn square_brackets_to_backticks(&self, stmt: &str) -> String {
788 let mut result = String::with_capacity(stmt.len());
789 let mut in_string = false;
790
791 for c in stmt.chars() {
792 if c == '\'' {
793 in_string = !in_string;
794 result.push(c);
795 } else if !in_string && (c == '[' || c == ']') {
796 result.push('`');
797 } else {
798 result.push(c);
799 }
800 }
801 result
802 }
803
804 pub fn square_brackets_to_double_quotes(&self, stmt: &str) -> String {
806 let mut result = String::with_capacity(stmt.len());
807 let mut in_string = false;
808
809 for c in stmt.chars() {
810 if c == '\'' {
811 in_string = !in_string;
812 result.push(c);
813 } else if !in_string && (c == '[' || c == ']') {
814 result.push('"');
815 } else {
816 result.push(c);
817 }
818 }
819 result
820 }
821
822 fn convert_data_types(&self, stmt: &str) -> String {
824 TypeMapper::convert(stmt, self.from, self.to)
825 }
826
827 fn convert_auto_increment(&self, stmt: &str, _table_name: Option<&str>) -> String {
829 let stmt = if self.from == SqlDialect::MySql && self.to != SqlDialect::MySql {
835 self.strip_mysql_auto_increment_table_option(stmt)
836 } else {
837 stmt.to_string()
838 };
839 let stmt = stmt.as_str();
840
841 match (self.from, self.to) {
842 (SqlDialect::MySql, SqlDialect::Postgres) => {
843 self.convert_mysql_auto_increment_keyword(stmt)
849 }
850 (SqlDialect::MySql, SqlDialect::Sqlite) => {
851 use once_cell::sync::Lazy;
852 use regex::Regex;
853 static RE_SIZED_AI: Lazy<Regex> = Lazy::new(|| {
860 Regex::new(r"(?i)\b(?:BIG|MEDIUM|SMALL|TINY)?INT\s+AUTO_INCREMENT").unwrap()
861 });
862 static RE_BARE_AI: Lazy<Regex> =
866 Lazy::new(|| Regex::new(r"(?i)AUTO_INCREMENT\b").unwrap());
867 map_outside_string_literals(stmt, |seg| {
868 let seg = RE_SIZED_AI.replace_all(seg, "INTEGER");
869 RE_BARE_AI.replace_all(&seg, "").into_owned()
870 })
871 }
872 (SqlDialect::Postgres, SqlDialect::MySql) => {
873 let result = stmt.replace("BIGSERIAL", "BIGINT AUTO_INCREMENT");
876 let result = result.replace("bigserial", "BIGINT AUTO_INCREMENT");
877 let result = result.replace("SMALLSERIAL", "SMALLINT AUTO_INCREMENT");
878 let result = result.replace("smallserial", "SMALLINT AUTO_INCREMENT");
879 let result = result.replace("SERIAL", "INT AUTO_INCREMENT");
880 result.replace("serial", "INT AUTO_INCREMENT")
881 }
882 (SqlDialect::Postgres, SqlDialect::Sqlite) => {
883 let result = stmt.replace("BIGSERIAL", "INTEGER");
885 let result = result.replace("bigserial", "INTEGER");
886 let result = result.replace("SMALLSERIAL", "INTEGER");
887 let result = result.replace("smallserial", "INTEGER");
888 let result = result.replace("SERIAL", "INTEGER");
889 result.replace("serial", "INTEGER")
890 }
891 (SqlDialect::Sqlite, SqlDialect::MySql) => {
892 stmt.to_string()
895 }
896 (SqlDialect::Sqlite, SqlDialect::Postgres) => {
897 stmt.to_string()
900 }
901 (SqlDialect::MySql, SqlDialect::Mssql) => {
903 use once_cell::sync::Lazy;
904 use regex::Regex;
905 static RE_BIGINT_AI: Lazy<Regex> =
910 Lazy::new(|| Regex::new(r"(?i)\bBIGINT\s+AUTO_INCREMENT").unwrap());
911 static RE_INT_AI: Lazy<Regex> =
912 Lazy::new(|| Regex::new(r"(?i)\bINT\s+AUTO_INCREMENT").unwrap());
913 static RE_BARE_AI: Lazy<Regex> =
916 Lazy::new(|| Regex::new(r"(?i)AUTO_INCREMENT\b").unwrap());
917 map_outside_string_literals(stmt, |seg| {
918 let seg = RE_BIGINT_AI.replace_all(seg, "BIGINT IDENTITY(1,1)");
919 let seg = RE_INT_AI.replace_all(&seg, "INT IDENTITY(1,1)");
920 RE_BARE_AI.replace_all(&seg, "IDENTITY(1,1)").into_owned()
921 })
922 }
923 (SqlDialect::Mssql, SqlDialect::MySql) => {
924 self.convert_identity_to_auto_increment(stmt)
926 }
927 (SqlDialect::Postgres, SqlDialect::Mssql) => {
928 stmt.to_string()
930 }
931 (SqlDialect::Mssql, SqlDialect::Postgres) => {
932 self.convert_identity_to_serial(stmt)
934 }
935 (SqlDialect::Sqlite, SqlDialect::Mssql) => {
936 stmt.to_string()
938 }
939 (SqlDialect::Mssql, SqlDialect::Sqlite) => {
940 self.strip_identity(stmt)
942 }
943 _ => stmt.to_string(),
944 }
945 }
946
947 fn convert_identity_to_auto_increment(&self, stmt: &str) -> String {
949 use once_cell::sync::Lazy;
950 use regex::Regex;
951
952 static RE_IDENTITY: Lazy<Regex> =
953 Lazy::new(|| Regex::new(r"(?i)\bIDENTITY\s*\(\s*\d+\s*,\s*\d+\s*\)").unwrap());
954
955 RE_IDENTITY.replace_all(stmt, "AUTO_INCREMENT").to_string()
956 }
957
958 fn convert_identity_to_serial(&self, stmt: &str) -> String {
960 use once_cell::sync::Lazy;
961 use regex::Regex;
962
963 static RE_BIGINT_IDENTITY: Lazy<Regex> =
965 Lazy::new(|| Regex::new(r"(?i)\bBIGINT\s+IDENTITY\s*\(\s*\d+\s*,\s*\d+\s*\)").unwrap());
966 static RE_INT_IDENTITY: Lazy<Regex> =
967 Lazy::new(|| Regex::new(r"(?i)\bINT\s+IDENTITY\s*\(\s*\d+\s*,\s*\d+\s*\)").unwrap());
968 static RE_SMALLINT_IDENTITY: Lazy<Regex> = Lazy::new(|| {
969 Regex::new(r"(?i)\bSMALLINT\s+IDENTITY\s*\(\s*\d+\s*,\s*\d+\s*\)").unwrap()
970 });
971
972 let result = RE_BIGINT_IDENTITY
973 .replace_all(stmt, "BIGSERIAL")
974 .to_string();
975 let result = RE_INT_IDENTITY.replace_all(&result, "SERIAL").to_string();
976 RE_SMALLINT_IDENTITY
977 .replace_all(&result, "SMALLSERIAL")
978 .to_string()
979 }
980
981 fn strip_identity(&self, stmt: &str) -> String {
983 use once_cell::sync::Lazy;
984 use regex::Regex;
985
986 static RE_IDENTITY: Lazy<Regex> =
987 Lazy::new(|| Regex::new(r"(?i)\s*IDENTITY\s*\(\s*\d+\s*,\s*\d+\s*\)").unwrap());
988
989 RE_IDENTITY.replace_all(stmt, "").to_string()
990 }
991
992 fn convert_string_escapes(&self, stmt: &str) -> String {
994 match (self.from, self.to) {
995 (SqlDialect::MySql, SqlDialect::Postgres | SqlDialect::Sqlite | SqlDialect::Mssql) => {
999 self.mysql_escapes_to_standard(stmt)
1000 }
1001 _ => stmt.to_string(),
1002 }
1003 }
1004
1005 fn mysql_escapes_to_standard(&self, stmt: &str) -> String {
1007 let mut result = String::with_capacity(stmt.len());
1008 let mut chars = stmt.chars().peekable();
1009 let mut in_string = false;
1010
1011 while let Some(c) = chars.next() {
1012 if c == '\'' {
1013 in_string = !in_string;
1014 result.push(c);
1015 } else if c == '\\' && in_string {
1016 match chars.next() {
1021 Some(next) => match next {
1022 '\'' => result.push_str("''"),
1024 '"' => result.push('"'),
1025 '\\' => result.push('\\'),
1027 'n' => result.push('\n'),
1028 'r' => result.push('\r'),
1029 't' => result.push('\t'),
1030 '0' => result.push('\0'),
1031 'b' => result.push('\u{08}'),
1032 'Z' => result.push('\u{1a}'),
1033 '%' => result.push_str("\\%"),
1035 '_' => result.push_str("\\_"),
1036 other => result.push(other),
1038 },
1039 None => result.push('\\'),
1041 }
1042 } else {
1043 result.push(c);
1044 }
1045 }
1046 result
1047 }
1048
1049 fn strip_conditional_comments(&self, stmt: &str) -> String {
1051 let mut result = String::with_capacity(stmt.len());
1052 let mut chars = stmt.chars().peekable();
1053
1054 while let Some(c) = chars.next() {
1055 if c == '/' && chars.peek() == Some(&'*') {
1056 chars.next(); if chars.peek() == Some(&'!') {
1058 chars.next(); while chars.peek().map(|c| c.is_ascii_digit()).unwrap_or(false) {
1062 chars.next();
1063 }
1064 let mut depth = 1;
1066 while depth > 0 {
1067 match chars.next() {
1068 Some('*') if chars.peek() == Some(&'/') => {
1069 chars.next();
1070 depth -= 1;
1071 }
1072 Some('/') if chars.peek() == Some(&'*') => {
1073 chars.next();
1074 depth += 1;
1075 }
1076 None => break,
1077 _ => {}
1078 }
1079 }
1080 } else {
1081 result.push('/');
1083 result.push('*');
1084 }
1085 } else {
1086 result.push(c);
1087 }
1088 }
1089 result
1090 }
1091
1092 fn strip_engine_clause(&self, stmt: &str) -> String {
1094 use once_cell::sync::Lazy;
1095 use regex::Regex;
1096
1097 if self.to == SqlDialect::MySql {
1098 return stmt.to_string();
1099 }
1100
1101 static RE_ENGINE: Lazy<Regex> =
1103 Lazy::new(|| Regex::new(r"(?i)\s*ENGINE\s*=\s*\w+").unwrap());
1104 RE_ENGINE.replace_all(stmt, "").to_string()
1105 }
1106
1107 fn strip_charset_clauses(&self, stmt: &str) -> String {
1109 use once_cell::sync::Lazy;
1110 use regex::Regex;
1111
1112 if self.to == SqlDialect::MySql {
1113 return stmt.to_string();
1114 }
1115
1116 static RE_CHARSET: Lazy<Regex> =
1117 Lazy::new(|| Regex::new(r"(?i)\s*(DEFAULT\s+)?CHARSET\s*=\s*\w+").unwrap());
1118 static RE_COLLATE: Lazy<Regex> =
1119 Lazy::new(|| Regex::new(r"(?i)\s*COLLATE\s*=?\s*\w+").unwrap());
1120
1121 let result = RE_CHARSET.replace_all(stmt, "").to_string();
1122 RE_COLLATE.replace_all(&result, "").to_string()
1123 }
1124
1125 fn match_keyword_ci(chars: &[char], pos: usize, keyword: &str) -> Option<usize> {
1130 let kw_len = keyword.len();
1131 if pos > 0 && (chars[pos - 1].is_alphanumeric() || chars[pos - 1] == '_') {
1132 return None;
1133 }
1134 let end = pos + kw_len;
1135 if end > chars.len() {
1136 return None;
1137 }
1138 let candidate: String = chars[pos..end].iter().collect();
1139 if !candidate.eq_ignore_ascii_case(keyword) {
1140 return None;
1141 }
1142 if end < chars.len() && (chars[end].is_alphanumeric() || chars[end] == '_') {
1143 return None;
1144 }
1145 Some(end)
1146 }
1147
1148 fn trim_trailing_whitespace(result: &mut String) {
1152 while result.ends_with(|c: char| c.is_whitespace()) {
1153 result.pop();
1154 }
1155 }
1156
1157 fn strip_mysql_auto_increment_table_option(&self, stmt: &str) -> String {
1162 let chars: Vec<char> = stmt.chars().collect();
1163 let n = chars.len();
1164 let mut result = String::with_capacity(stmt.len());
1165 let mut in_string = false;
1166 let mut i = 0;
1167
1168 while i < n {
1169 let c = chars[i];
1170 if c == '\'' {
1171 in_string = !in_string;
1172 result.push(c);
1173 i += 1;
1174 continue;
1175 }
1176 if !in_string {
1177 if let Some(after_kw) = Self::match_keyword_ci(&chars, i, "AUTO_INCREMENT") {
1178 let mut j = after_kw;
1179 while j < n && chars[j].is_whitespace() {
1180 j += 1;
1181 }
1182 if j < n && chars[j] == '=' {
1183 j += 1;
1184 while j < n && chars[j].is_whitespace() {
1185 j += 1;
1186 }
1187 let digits_start = j;
1188 while j < n && chars[j].is_ascii_digit() {
1189 j += 1;
1190 }
1191 if j > digits_start {
1192 Self::trim_trailing_whitespace(&mut result);
1193 i = j;
1194 continue;
1195 }
1196 }
1197 }
1198 }
1199 result.push(c);
1200 i += 1;
1201 }
1202 result
1203 }
1204
1205 fn strip_mysql_comment_clauses(&self, stmt: &str) -> String {
1211 if self.to == SqlDialect::MySql {
1212 return stmt.to_string();
1213 }
1214
1215 let chars: Vec<char> = stmt.chars().collect();
1216 let n = chars.len();
1217 let mut result = String::with_capacity(stmt.len());
1218 let mut in_string = false;
1219 let mut i = 0;
1220
1221 while i < n {
1222 let c = chars[i];
1223 if c == '\'' {
1224 in_string = !in_string;
1225 result.push(c);
1226 i += 1;
1227 continue;
1228 }
1229 if !in_string {
1230 if let Some(after_kw) = Self::match_keyword_ci(&chars, i, "COMMENT") {
1231 let mut j = after_kw;
1232 while j < n && chars[j].is_whitespace() {
1233 j += 1;
1234 }
1235 if j < n && chars[j] == '=' {
1236 j += 1;
1237 while j < n && chars[j].is_whitespace() {
1238 j += 1;
1239 }
1240 }
1241 if j < n && chars[j] == '\'' {
1242 j += 1;
1245 loop {
1246 if j >= n {
1247 break;
1248 }
1249 if chars[j] == '\'' {
1250 if j + 1 < n && chars[j + 1] == '\'' {
1251 j += 2;
1252 continue;
1253 }
1254 j += 1;
1255 break;
1256 }
1257 j += 1;
1258 }
1259 Self::trim_trailing_whitespace(&mut result);
1260 i = j;
1261 continue;
1262 }
1263 }
1264 }
1265 result.push(c);
1266 i += 1;
1267 }
1268 result
1269 }
1270
1271 fn convert_mysql_auto_increment_keyword(&self, stmt: &str) -> String {
1277 let chars: Vec<char> = stmt.chars().collect();
1278 let n = chars.len();
1279 let mut result = String::with_capacity(stmt.len());
1280 let mut in_string = false;
1281 let mut i = 0;
1282
1283 while i < n {
1284 let c = chars[i];
1285 if c == '\'' {
1286 in_string = !in_string;
1287 result.push(c);
1288 i += 1;
1289 continue;
1290 }
1291 if !in_string {
1292 if let Some(after_type) = Self::match_keyword_ci(&chars, i, "BIGINT") {
1293 let mut j = after_type;
1294 while j < n && chars[j].is_whitespace() {
1295 j += 1;
1296 }
1297 if let Some(end) = Self::match_keyword_ci(&chars, j, "AUTO_INCREMENT") {
1298 result.push_str("BIGSERIAL");
1299 i = end;
1300 continue;
1301 }
1302 }
1303 if let Some(after_type) = Self::match_keyword_ci(&chars, i, "INT") {
1304 let mut j = after_type;
1305 while j < n && chars[j].is_whitespace() {
1306 j += 1;
1307 }
1308 if let Some(end) = Self::match_keyword_ci(&chars, j, "AUTO_INCREMENT") {
1309 result.push_str("SERIAL");
1310 i = end;
1311 continue;
1312 }
1313 }
1314 if let Some(end) = Self::match_keyword_ci(&chars, i, "AUTO_INCREMENT") {
1315 i = end;
1319 continue;
1320 }
1321 }
1322 result.push(c);
1323 i += 1;
1324 }
1325 result
1326 }
1327
1328 fn convert_unique_key_constraint(&self, stmt: &str) -> String {
1333 use once_cell::sync::Lazy;
1334 use regex::{Captures, Regex};
1335
1336 if self.to == SqlDialect::MySql {
1337 return stmt.to_string();
1338 }
1339
1340 static RE: Lazy<Regex> = Lazy::new(|| {
1344 Regex::new(
1345 r#"(?i)UNIQUE\s+KEY\s+(?:"[^"]*"\s+)?(\([^()]*(?:\(\d+\)[^()]*)*\))(?:\s*USING\s+(?:BTREE|HASH))?"#,
1346 )
1347 .unwrap()
1348 });
1349 static RE_PREFIX_LEN: Lazy<Regex> = Lazy::new(|| Regex::new(r"\(\d+\)").unwrap());
1350
1351 RE.replace_all(stmt, |caps: &Captures| {
1352 let cols = RE_PREFIX_LEN.replace_all(&caps[1], "");
1353 format!("UNIQUE {}", cols)
1354 })
1355 .to_string()
1356 }
1357
1358 fn strip_postgres_casts(&self, stmt: &str) -> String {
1360 use once_cell::sync::Lazy;
1361 use regex::Regex;
1362
1363 static RE_CAST: Lazy<Regex> = Lazy::new(|| {
1365 Regex::new(r"::[a-zA-Z_][a-zA-Z0-9_]*(?:\s+[a-zA-Z_][a-zA-Z0-9_]*)*").unwrap()
1366 });
1367
1368 map_outside_string_literals(stmt, |seg| RE_CAST.replace_all(seg, "").into_owned())
1371 }
1372
1373 fn convert_nextval(&self, stmt: &str) -> String {
1375 use once_cell::sync::Lazy;
1376 use regex::Regex;
1377
1378 static RE_NEXTVAL: Lazy<Regex> =
1381 Lazy::new(|| Regex::new(r"(?i)\s*DEFAULT\s+nextval\s*\([^)]+\)").unwrap());
1382
1383 RE_NEXTVAL.replace_all(stmt, "").to_string()
1384 }
1385
1386 fn defer_mysql_auto_increment(&self, stmt: &str) -> Option<String> {
1400 use once_cell::sync::Lazy;
1401 use regex::Regex;
1402
1403 static RE_SEQUENCE_TARGET: Lazy<Regex> = Lazy::new(|| {
1404 Regex::new(
1405 r"(?is)\bALTER\s+TABLE\s+(?:ONLY\s+)?(?P<table>\S+)\s+ALTER\s+COLUMN\s+(?P<column>[^\s]+)\s+SET\s+DEFAULT\s+nextval",
1406 )
1407 .unwrap()
1408 });
1409
1410 if self.to != SqlDialect::MySql {
1411 return None;
1412 }
1413
1414 let caps = RE_SEQUENCE_TARGET.captures(stmt)?;
1415 let table = table_key(&caps["table"]);
1416 let column = caps["column"].trim_matches(|c| c == '"' || c == '`');
1417 let create_table = self.created_tables.get(&table)?;
1418 let column_type = declared_column_type(create_table, column)?;
1419
1420 if !matches!(
1423 column_type.to_uppercase().as_str(),
1424 "INT" | "INTEGER" | "BIGINT" | "SMALLINT" | "MEDIUMINT" | "TINYINT"
1425 ) {
1426 return None;
1427 }
1428
1429 Some(format!(
1430 "ALTER TABLE `{table}` MODIFY COLUMN `{column}` {column_type} NOT NULL AUTO_INCREMENT;"
1431 ))
1432 }
1433
1434 fn strip_postgres_only(&self, stmt: &str) -> String {
1438 use once_cell::sync::Lazy;
1439 use regex::Regex;
1440
1441 static RE_ALTER_ONLY: Lazy<Regex> =
1442 Lazy::new(|| Regex::new(r"(?i)\b(ALTER\s+TABLE)\s+ONLY\s+").unwrap());
1443
1444 RE_ALTER_ONLY.replace_all(stmt, "$1 ").to_string()
1445 }
1446
1447 fn is_sequence_default_alter(&self, stmt: &str) -> bool {
1451 use once_cell::sync::Lazy;
1452 use regex::Regex;
1453
1454 static RE_SEQUENCE_DEFAULT: Lazy<Regex> = Lazy::new(|| {
1455 Regex::new(r"(?is)\bALTER\s+COLUMN\b.*?\bSET\s+DEFAULT\s+nextval\s*\(").unwrap()
1456 });
1457
1458 RE_SEQUENCE_DEFAULT.is_match(stmt)
1459 }
1460
1461 fn is_psql_meta_command(&self, stmt: &str) -> bool {
1465 let stripped = self.strip_leading_sql_comments(stmt);
1466 let trimmed = stripped.trim_start();
1467 trimmed.starts_with('\\') && !trimmed.starts_with("\\.")
1468 }
1469
1470 fn convert_default_now(&self, stmt: &str) -> String {
1472 use once_cell::sync::Lazy;
1473 use regex::Regex;
1474
1475 static RE_NOW: Lazy<Regex> =
1476 Lazy::new(|| Regex::new(r"(?i)\bDEFAULT\s+now\s*\(\s*\)").unwrap());
1477
1478 RE_NOW
1479 .replace_all(stmt, "DEFAULT CURRENT_TIMESTAMP")
1480 .to_string()
1481 }
1482
1483 fn strip_schema_prefix(&self, stmt: &str) -> String {
1485 use once_cell::sync::Lazy;
1486 use regex::Regex;
1487
1488 static RE_SCHEMA: Lazy<Regex> =
1491 Lazy::new(|| Regex::new(r#"(?i)\b(public|pg_catalog|pg_temp)\s*\.\s*"#).unwrap());
1492
1493 map_outside_string_literals(stmt, |seg| RE_SCHEMA.replace_all(seg, "").into_owned())
1496 }
1497
1498 fn convert_mssql_getdate(&self, stmt: &str) -> String {
1500 use once_cell::sync::Lazy;
1501 use regex::Regex;
1502
1503 static RE_GETDATE: Lazy<Regex> =
1504 Lazy::new(|| Regex::new(r"(?i)\bGETDATE\s*\(\s*\)").unwrap());
1505 static RE_SYSDATETIME: Lazy<Regex> =
1506 Lazy::new(|| Regex::new(r"(?i)\bSYSDATETIME\s*\(\s*\)").unwrap());
1507 static RE_GETUTCDATE: Lazy<Regex> =
1508 Lazy::new(|| Regex::new(r"(?i)\bGETUTCDATE\s*\(\s*\)").unwrap());
1509
1510 let result = RE_GETDATE
1511 .replace_all(stmt, "CURRENT_TIMESTAMP")
1512 .to_string();
1513 let result = RE_SYSDATETIME
1514 .replace_all(&result, "CURRENT_TIMESTAMP")
1515 .to_string();
1516 RE_GETUTCDATE
1517 .replace_all(&result, "CURRENT_TIMESTAMP")
1518 .to_string()
1519 }
1520
1521 fn strip_mssql_on_filegroup(&self, stmt: &str) -> String {
1523 use once_cell::sync::Lazy;
1524 use regex::Regex;
1525
1526 static RE_ON_FILEGROUP: Lazy<Regex> =
1528 Lazy::new(|| Regex::new(r"(?i)\s+ON\s*\[\s*\w+\s*\]").unwrap());
1529
1530 RE_ON_FILEGROUP.replace_all(stmt, "").to_string()
1531 }
1532
1533 fn strip_mssql_clustered(&self, stmt: &str) -> String {
1535 use once_cell::sync::Lazy;
1536 use regex::Regex;
1537
1538 static RE_CLUSTERED: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bCLUSTERED\s+").unwrap());
1539 static RE_NONCLUSTERED: Lazy<Regex> =
1540 Lazy::new(|| Regex::new(r"(?i)\bNONCLUSTERED\s+").unwrap());
1541
1542 let result = RE_CLUSTERED.replace_all(stmt, "").to_string();
1543 RE_NONCLUSTERED.replace_all(&result, "").to_string()
1544 }
1545
1546 fn convert_mssql_unicode_strings(&self, stmt: &str) -> String {
1552 let bytes = stmt.as_bytes();
1553 let mut out = String::with_capacity(stmt.len());
1554 let mut i = 0;
1555 let mut copied = 0;
1557 while i < bytes.len() {
1558 if bytes[i] == b'\'' {
1559 i = skip_sql_string_literal(bytes, i);
1561 } else if matches!(bytes[i], b'N' | b'n')
1562 && bytes.get(i + 1) == Some(&b'\'')
1563 && (i == 0 || !(bytes[i - 1].is_ascii_alphanumeric() || bytes[i - 1] == b'_'))
1564 {
1565 out.push_str(&stmt[copied..i]);
1568 copied = i + 1;
1569 i += 1;
1570 } else {
1571 i += 1;
1572 }
1573 }
1574 out.push_str(&stmt[copied..]);
1575 out
1576 }
1577
1578 fn strip_mssql_schema_prefix(&self, stmt: &str) -> String {
1580 use once_cell::sync::Lazy;
1581 use regex::Regex;
1582
1583 static RE_MSSQL_SCHEMA: Lazy<Regex> =
1586 Lazy::new(|| Regex::new(r"(?i)\[?dbo\]?\s*\.\s*").unwrap());
1587
1588 map_outside_string_literals(stmt, |seg| {
1591 RE_MSSQL_SCHEMA.replace_all(seg, "").into_owned()
1592 })
1593 }
1594
1595 fn detect_unsupported_features(
1597 &mut self,
1598 stmt: &str,
1599 table_name: Option<&str>,
1600 ) -> Result<(), ConvertWarning> {
1601 let upper = stmt.to_uppercase();
1602
1603 if self.from == SqlDialect::MySql {
1605 if upper.contains("ENUM(") {
1607 let warning = ConvertWarning::UnsupportedFeature {
1608 feature: format!(
1609 "ENUM type{}",
1610 table_name
1611 .map(|t| format!(" in table {}", t))
1612 .unwrap_or_default()
1613 ),
1614 suggestion: Some(
1615 "Converted to VARCHAR - consider adding CHECK constraint".to_string(),
1616 ),
1617 };
1618 self.warnings.add(warning.clone());
1619 if self.strict {
1620 return Err(warning);
1621 }
1622 }
1623
1624 if upper.contains("SET(") {
1626 let warning = ConvertWarning::UnsupportedFeature {
1627 feature: format!(
1628 "SET type{}",
1629 table_name
1630 .map(|t| format!(" in table {}", t))
1631 .unwrap_or_default()
1632 ),
1633 suggestion: Some(
1634 "Converted to VARCHAR - SET semantics not preserved".to_string(),
1635 ),
1636 };
1637 self.warnings.add(warning.clone());
1638 if self.strict {
1639 return Err(warning);
1640 }
1641 }
1642
1643 if upper.contains("UNSIGNED") {
1645 self.warnings.add(ConvertWarning::UnsupportedFeature {
1646 feature: "UNSIGNED modifier".to_string(),
1647 suggestion: Some(
1648 "Removed - consider adding CHECK constraint for non-negative values"
1649 .to_string(),
1650 ),
1651 });
1652 }
1653 }
1654
1655 if self.from == SqlDialect::Postgres {
1657 if upper.contains("[]") || upper.contains("ARRAY[") {
1659 let warning = ConvertWarning::UnsupportedFeature {
1660 feature: format!(
1661 "Array type{}",
1662 table_name
1663 .map(|t| format!(" in table {}", t))
1664 .unwrap_or_default()
1665 ),
1666 suggestion: Some(
1667 "Array types not supported in target dialect - consider using JSON"
1668 .to_string(),
1669 ),
1670 };
1671 self.warnings.add(warning.clone());
1672 if self.strict {
1673 return Err(warning);
1674 }
1675 }
1676
1677 if upper.contains("INHERITS") {
1679 let warning = ConvertWarning::UnsupportedFeature {
1680 feature: "Table inheritance (INHERITS)".to_string(),
1681 suggestion: Some(
1682 "PostgreSQL table inheritance not supported in target dialect".to_string(),
1683 ),
1684 };
1685 self.warnings.add(warning.clone());
1686 if self.strict {
1687 return Err(warning);
1688 }
1689 }
1690
1691 if upper.contains("PARTITION BY") && self.to == SqlDialect::Sqlite {
1693 let warning = ConvertWarning::UnsupportedFeature {
1694 feature: "Table partitioning".to_string(),
1695 suggestion: Some("Partitioning not supported in SQLite".to_string()),
1696 };
1697 self.warnings.add(warning.clone());
1698 if self.strict {
1699 return Err(warning);
1700 }
1701 }
1702 }
1703
1704 Ok(())
1705 }
1706
1707 pub fn warnings(&self) -> &[ConvertWarning] {
1709 self.warnings.warnings()
1710 }
1711}
1712
1713pub fn run(config: ConvertConfig) -> anyhow::Result<ConvertStats> {
1715 let mut stats = ConvertStats::default();
1716
1717 let from_dialect = if let Some(d) = config.from_dialect {
1719 d
1720 } else {
1721 let result = crate::parser::detect_dialect_from_file(&config.input)?;
1722 if config.progress {
1723 eprintln!(
1724 "Auto-detected source dialect: {} (confidence: {:?})",
1725 result.dialect, result.confidence
1726 );
1727 }
1728 result.dialect
1729 };
1730
1731 if from_dialect == config.to_dialect {
1733 anyhow::bail!(
1734 "Source and target dialects are the same ({}). No conversion needed.",
1735 from_dialect
1736 );
1737 }
1738
1739 let file_size = std::fs::metadata(&config.input)?.len();
1741
1742 let progress_bar = if config.progress {
1743 let pb = ProgressBar::new(file_size);
1744 pb.set_style(
1745 ProgressStyle::with_template(
1746 "{spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] {bytes}/{total_bytes} ({percent}%) {msg}",
1747 )
1748 .unwrap()
1749 .progress_chars("█▓▒░ ")
1750 .tick_chars("⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"),
1751 );
1752 pb.enable_steady_tick(std::time::Duration::from_millis(100));
1753 pb.set_message("Converting...");
1754 Some(pb)
1755 } else {
1756 None
1757 };
1758
1759 let mut converter = Converter::new(from_dialect, config.to_dialect).with_strict(config.strict);
1761
1762 let reader: Box<dyn Read> = if let Some(ref pb) = progress_bar {
1765 let pb_clone = pb.clone();
1766 open_input_with_progress(
1767 &config.input,
1768 Box::new(move |bytes| pb_clone.set_position(bytes)),
1769 )?
1770 } else {
1771 open_input(&config.input)?
1772 };
1773 let mut parser = Parser::with_dialect(reader, 64 * 1024, from_dialect);
1774
1775 let mut writer: Box<dyn Write> = if config.dry_run {
1777 Box::new(std::io::sink())
1778 } else {
1779 match &config.output {
1780 Some(path) => {
1781 if let Some(parent) = path.parent() {
1782 std::fs::create_dir_all(parent)?;
1783 }
1784 Box::new(BufWriter::with_capacity(256 * 1024, File::create(path)?))
1785 }
1786 None => Box::new(BufWriter::new(std::io::stdout())),
1787 }
1788 };
1789
1790 if !config.dry_run {
1792 write_header(&mut writer, &config, from_dialect)?;
1793 }
1794
1795 while let Some(stmt) = parser.read_statement()? {
1797 stats.statements_processed += 1;
1798
1799 if converter.has_pending_copy() {
1801 match converter.process_copy_data(&stmt) {
1803 Ok(inserts) => {
1804 for insert in inserts {
1805 if !insert.is_empty() {
1806 stats.statements_converted += 1;
1807 if !config.dry_run {
1808 writer.write_all(&insert)?;
1809 writer.write_all(b"\n")?;
1810 }
1811 }
1812 }
1813 }
1814 Err(warning) => {
1815 stats.warnings.push(warning);
1816 stats.statements_skipped += 1;
1817 }
1818 }
1819 continue;
1820 }
1821
1822 match converter.convert_statement(&stmt) {
1823 Ok(converted) => {
1824 if converted.is_empty() {
1825 stats.statements_skipped += 1;
1826 } else if converted == stmt {
1827 stats.statements_unchanged += 1;
1828 if !config.dry_run {
1829 writer.write_all(&converted)?;
1830 writer.write_all(b"\n")?;
1831 }
1832 } else {
1833 stats.statements_converted += 1;
1834 if !config.dry_run {
1835 writer.write_all(&converted)?;
1836 writer.write_all(b"\n")?;
1837 }
1838 }
1839 }
1840 Err(warning) => {
1841 stats.warnings.push(warning);
1842 stats.statements_skipped += 1;
1843 }
1844 }
1845 }
1846
1847 for statement in converter.take_deferred_statements() {
1851 stats.statements_converted += 1;
1852 if !config.dry_run {
1853 writer.write_all(statement.as_bytes())?;
1854 writer.write_all(b"\n")?;
1855 }
1856 }
1857
1858 stats.warnings.extend(converter.warnings().iter().cloned());
1860
1861 if let Some(pb) = progress_bar {
1862 pb.finish_with_message("done");
1863 }
1864
1865 Ok(stats)
1866}
1867
1868fn write_header(
1870 writer: &mut dyn Write,
1871 config: &ConvertConfig,
1872 from: SqlDialect,
1873) -> std::io::Result<()> {
1874 writeln!(writer, "-- Converted by sql-splitter")?;
1875 writeln!(writer, "-- From: {} → To: {}", from, config.to_dialect)?;
1876 writeln!(writer, "-- Source: {}", config.input.display())?;
1877 writeln!(writer)?;
1878
1879 match config.to_dialect {
1881 SqlDialect::Postgres => {
1882 writeln!(writer, "SET client_encoding = 'UTF8';")?;
1883 writeln!(writer, "SET standard_conforming_strings = on;")?;
1884 }
1885 SqlDialect::Sqlite => {
1886 writeln!(writer, "PRAGMA foreign_keys = OFF;")?;
1887 }
1888 SqlDialect::MySql => {
1889 writeln!(writer, "SET NAMES utf8mb4;")?;
1890 writeln!(writer, "SET FOREIGN_KEY_CHECKS = 0;")?;
1891 }
1892 SqlDialect::Mssql => {
1893 writeln!(writer, "SET ANSI_NULLS ON;")?;
1894 writeln!(writer, "SET QUOTED_IDENTIFIER ON;")?;
1895 writeln!(writer, "SET NOCOUNT ON;")?;
1896 }
1897 }
1898 writeln!(writer)?;
1899
1900 Ok(())
1901}
1902
1903fn skip_sql_string_literal(bytes: &[u8], start: usize) -> usize {
1908 let mut i = start + 1;
1909 while i < bytes.len() {
1910 if bytes[i] == b'\'' {
1911 if bytes.get(i + 1) == Some(&b'\'') {
1912 i += 2; } else {
1914 return i + 1; }
1916 } else {
1917 i += 1;
1918 }
1919 }
1920 i
1921}
1922
1923fn map_outside_string_literals(stmt: &str, f: impl Fn(&str) -> String) -> String {
1927 let bytes = stmt.as_bytes();
1928 let mut out = String::with_capacity(stmt.len());
1929 let mut i = 0;
1930 let mut seg_start = 0;
1931 while i < bytes.len() {
1932 if bytes[i] == b'\'' {
1933 out.push_str(&f(&stmt[seg_start..i]));
1935 let lit_end = skip_sql_string_literal(bytes, i);
1936 out.push_str(&stmt[i..lit_end]); i = lit_end;
1938 seg_start = i;
1939 } else {
1940 i += 1;
1941 }
1942 }
1943 out.push_str(&f(&stmt[seg_start..]));
1944 out
1945}