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::fs::File;
24use std::io::{BufWriter, Read, Write};
25use std::path::PathBuf;
26
27pub use types::TypeMapper;
28#[allow(unused_imports)]
32pub(crate) use types::map_column_type;
33pub use warnings::{print_warnings_summary, ConvertWarning, WarningCollector};
34
35#[derive(Debug)]
37pub struct ConvertConfig {
38 pub input: PathBuf,
40 pub output: Option<PathBuf>,
42 pub from_dialect: Option<SqlDialect>,
44 pub to_dialect: SqlDialect,
46 pub dry_run: bool,
48 pub progress: bool,
50 pub strict: bool,
52}
53
54impl Default for ConvertConfig {
55 fn default() -> Self {
56 Self {
57 input: PathBuf::new(),
58 output: None,
59 from_dialect: None,
60 to_dialect: SqlDialect::Postgres,
61 dry_run: false,
62 progress: false,
63 strict: false,
64 }
65 }
66}
67
68#[derive(Debug, Default, serde::Serialize)]
70pub struct ConvertStats {
71 pub statements_processed: u64,
73 pub statements_converted: u64,
75 pub statements_unchanged: u64,
77 pub statements_skipped: u64,
79 pub warnings: Vec<ConvertWarning>,
81}
82
83pub struct Converter {
85 from: SqlDialect,
86 to: SqlDialect,
87 warnings: WarningCollector,
88 strict: bool,
89 pending_copy_header: Option<CopyHeader>,
91}
92
93impl Converter {
94 pub fn new(from: SqlDialect, to: SqlDialect) -> Self {
95 Self {
96 from,
97 to,
98 warnings: WarningCollector::new(),
99 strict: false,
100 pending_copy_header: None,
101 }
102 }
103
104 pub fn with_strict(mut self, strict: bool) -> Self {
105 self.strict = strict;
106 self
107 }
108
109 pub fn has_pending_copy(&self) -> bool {
111 self.pending_copy_header.is_some()
112 }
113
114 pub fn process_copy_data(&mut self, data: &[u8]) -> Result<Vec<Vec<u8>>, ConvertWarning> {
116 if let Some(header) = self.pending_copy_header.take() {
117 if self.from == SqlDialect::Postgres && self.to != SqlDialect::Postgres {
118 let inserts = copy_to_inserts(&header, data, self.to);
120 return Ok(inserts);
121 }
122 }
123 Ok(vec![data.to_vec()])
125 }
126
127 pub fn convert_statement(&mut self, stmt: &[u8]) -> Result<Vec<u8>, ConvertWarning> {
129 let (stmt_type, table_name) =
130 Parser::<&[u8]>::parse_statement_with_dialect(stmt, self.from);
131
132 let table = if table_name.is_empty() {
133 None
134 } else {
135 Some(table_name.as_str())
136 };
137
138 match stmt_type {
139 StatementType::CreateTable => self.convert_create_table(stmt, table),
140 StatementType::Insert => self.convert_insert(stmt, table),
141 StatementType::CreateIndex => self.convert_create_index(stmt),
142 StatementType::AlterTable => self.convert_alter_table(stmt),
143 StatementType::DropTable => self.convert_drop_table(stmt),
144 StatementType::Copy => self.convert_copy(stmt, table),
145 StatementType::Unknown => self.convert_other(stmt),
146 }
147 }
148
149 fn convert_create_table(
151 &mut self,
152 stmt: &[u8],
153 table_name: Option<&str>,
154 ) -> Result<Vec<u8>, ConvertWarning> {
155 let stmt_str = String::from_utf8_lossy(stmt);
156 let mut result = stmt_str.to_string();
157
158 self.detect_unsupported_features(&result, table_name)?;
160
161 if self.from == SqlDialect::Mssql && self.to != SqlDialect::Mssql {
164 result = self.strip_mssql_schema_prefix(&result);
165 result = self.convert_mssql_getdate(&result);
166 result = self.strip_mssql_on_filegroup(&result);
167 result = self.strip_mssql_clustered(&result);
168 result = self.convert_mssql_unicode_strings(&result);
169 }
170
171 result = self.convert_identifiers(&result);
173
174 result = self.convert_data_types(&result);
176
177 result = self.convert_auto_increment(&result, table_name);
179
180 if self.from == SqlDialect::Postgres && self.to != SqlDialect::Postgres {
182 result = self.strip_postgres_casts(&result);
183 result = self.convert_nextval(&result);
184 result = self.convert_default_now(&result);
185 result = self.strip_schema_prefix(&result);
186 }
187
188 result = self.convert_string_escapes(&result);
190
191 result = self.strip_conditional_comments(&result);
193
194 result = self.strip_engine_clause(&result);
196
197 result = self.strip_charset_clauses(&result);
199
200 result = self.strip_mysql_comment_clauses(&result);
202
203 result = self.convert_unique_key_constraint(&result);
205
206 Ok(result.into_bytes())
207 }
208
209 fn convert_insert(
211 &mut self,
212 stmt: &[u8],
213 _table_name: Option<&str>,
214 ) -> Result<Vec<u8>, ConvertWarning> {
215 let stmt_str = String::from_utf8_lossy(stmt);
216 let mut result = stmt_str.to_string();
217
218 if self.from == SqlDialect::Mssql && self.to != SqlDialect::Mssql {
220 result = self.strip_mssql_schema_prefix(&result);
221 result = self.convert_mssql_unicode_strings(&result);
222 }
223
224 result = self.convert_identifiers(&result);
226
227 if self.from == SqlDialect::Postgres && self.to != SqlDialect::Postgres {
229 result = self.strip_postgres_casts(&result);
230 result = self.strip_schema_prefix(&result);
231 }
232
233 result = self.convert_string_escapes(&result);
235
236 Ok(result.into_bytes())
237 }
238
239 fn convert_create_index(&mut self, stmt: &[u8]) -> Result<Vec<u8>, ConvertWarning> {
241 let stmt_str = String::from_utf8_lossy(stmt);
242 let mut result = stmt_str.to_string();
243
244 if self.from == SqlDialect::Mssql && self.to != SqlDialect::Mssql {
246 result = self.strip_mssql_schema_prefix(&result);
247 result = self.strip_mssql_clustered(&result);
248 }
249
250 result = self.convert_identifiers(&result);
252
253 if self.from == SqlDialect::Postgres && self.to != SqlDialect::Postgres {
255 result = self.strip_postgres_casts(&result);
256 result = self.strip_schema_prefix(&result);
257 }
258
259 if result.contains("FULLTEXT") || result.contains("fulltext") {
261 self.warnings.add(ConvertWarning::UnsupportedFeature {
262 feature: "FULLTEXT INDEX".to_string(),
263 suggestion: Some("Use PostgreSQL GIN index or skip".to_string()),
264 });
265 if self.strict {
266 return Err(ConvertWarning::UnsupportedFeature {
267 feature: "FULLTEXT INDEX".to_string(),
268 suggestion: None,
269 });
270 }
271 }
272
273 Ok(result.into_bytes())
274 }
275
276 fn convert_alter_table(&mut self, stmt: &[u8]) -> Result<Vec<u8>, ConvertWarning> {
278 let stmt_str = String::from_utf8_lossy(stmt);
279 let mut result = stmt_str.to_string();
280
281 result = self.convert_identifiers(&result);
282 result = self.convert_data_types(&result);
283
284 if self.from == SqlDialect::Postgres && self.to != SqlDialect::Postgres {
286 result = self.strip_postgres_casts(&result);
287 result = self.convert_nextval(&result);
288 result = self.convert_default_now(&result);
289 result = self.strip_schema_prefix(&result);
290 }
291
292 Ok(result.into_bytes())
293 }
294
295 fn convert_drop_table(&mut self, stmt: &[u8]) -> Result<Vec<u8>, ConvertWarning> {
297 let stmt_str = String::from_utf8_lossy(stmt);
298 let mut result = stmt_str.to_string();
299
300 result = self.convert_identifiers(&result);
301
302 if self.from == SqlDialect::Postgres && self.to != SqlDialect::Postgres {
304 result = self.strip_schema_prefix(&result);
305 }
306
307 Ok(result.into_bytes())
308 }
309
310 fn convert_copy(
315 &mut self,
316 stmt: &[u8],
317 _table_name: Option<&str>,
318 ) -> Result<Vec<u8>, ConvertWarning> {
319 let stmt_str = String::from_utf8_lossy(stmt);
320
321 let upper = stmt_str.to_uppercase();
323 if upper.contains("FROM STDIN") {
324 if let Some(header) = parse_copy_header(&stmt_str) {
326 if self.from == SqlDialect::Postgres && self.to != SqlDialect::Postgres {
327 self.pending_copy_header = Some(header);
329 return Ok(Vec::new());
331 }
332 }
333 }
334
335 Ok(stmt.to_vec())
337 }
338
339 fn convert_other(&mut self, stmt: &[u8]) -> Result<Vec<u8>, ConvertWarning> {
341 let stmt_str = String::from_utf8_lossy(stmt);
342 let result = stmt_str.to_string();
343 let trimmed = result.trim();
344
345 if self.from == SqlDialect::MySql
347 && self.to != SqlDialect::MySql
348 && self.is_mysql_session_command(&result)
349 {
350 return Ok(Vec::new()); }
352
353 if self.from == SqlDialect::Postgres
355 && self.to != SqlDialect::Postgres
356 && self.is_postgres_session_command(&result)
357 {
358 return Ok(Vec::new()); }
360 if self.from == SqlDialect::Postgres
361 && self.to != SqlDialect::Postgres
362 && self.is_postgres_only_feature(trimmed)
363 {
364 self.warnings.add(ConvertWarning::SkippedStatement {
365 reason: "PostgreSQL-only feature".to_string(),
366 statement_preview: trimmed.chars().take(60).collect(),
367 });
368 return Ok(Vec::new()); }
370
371 if self.from == SqlDialect::Sqlite
373 && self.to != SqlDialect::Sqlite
374 && self.is_sqlite_pragma(&result)
375 {
376 return Ok(Vec::new()); }
378
379 if self.from == SqlDialect::Mssql
381 && self.to != SqlDialect::Mssql
382 && self.is_mssql_session_command(&result)
383 {
384 return Ok(Vec::new()); }
386
387 if result.contains("/*!") {
389 let stripped = self.strip_conditional_comments(&result);
390 return Ok(stripped.into_bytes());
391 }
392
393 Ok(stmt.to_vec())
394 }
395
396 fn is_mysql_session_command(&self, stmt: &str) -> bool {
398 let upper = stmt.to_uppercase();
399 upper.contains("SET NAMES")
400 || upper.contains("SET CHARACTER")
401 || upper.contains("SET SQL_MODE")
402 || upper.contains("SET TIME_ZONE")
403 || upper.contains("SET FOREIGN_KEY_CHECKS")
404 || upper.contains("LOCK TABLES")
405 || upper.contains("UNLOCK TABLES")
406 }
407
408 fn is_postgres_session_command(&self, stmt: &str) -> bool {
410 let upper = stmt.to_uppercase();
411 upper.contains("SET CLIENT_ENCODING")
413 || upper.contains("SET STANDARD_CONFORMING_STRINGS")
414 || upper.contains("SET CHECK_FUNCTION_BODIES")
415 || upper.contains("SET SEARCH_PATH")
416 || upper.contains("SET DEFAULT_TABLESPACE")
417 || upper.contains("SET LOCK_TIMEOUT")
418 || upper.contains("SET IDLE_IN_TRANSACTION_SESSION_TIMEOUT")
419 || upper.contains("SET ROW_SECURITY")
420 || upper.contains("SET STATEMENT_TIMEOUT")
421 || upper.contains("SET XMLOPTION")
422 || upper.contains("SET CLIENT_MIN_MESSAGES")
423 || upper.contains("SET DEFAULT_TABLE_ACCESS_METHOD")
424 || upper.contains("SELECT PG_CATALOG")
425 || upper.contains("OWNER TO")
427 || upper.contains("GRANT ")
428 || upper.contains("REVOKE ")
429 }
430
431 fn is_postgres_only_feature(&self, stmt: &str) -> bool {
433 let stripped = self.strip_leading_sql_comments(stmt);
435 let upper = stripped.to_uppercase();
436
437 upper.starts_with("CREATE DOMAIN")
439 || upper.starts_with("CREATE TYPE")
440 || upper.starts_with("CREATE FUNCTION")
441 || upper.starts_with("CREATE PROCEDURE")
442 || upper.starts_with("CREATE AGGREGATE")
443 || upper.starts_with("CREATE OPERATOR")
444 || upper.starts_with("CREATE SEQUENCE")
445 || upper.starts_with("CREATE EXTENSION")
446 || upper.starts_with("CREATE SCHEMA")
447 || upper.starts_with("CREATE TRIGGER")
448 || upper.starts_with("ALTER DOMAIN")
449 || upper.starts_with("ALTER TYPE")
450 || upper.starts_with("ALTER FUNCTION")
451 || upper.starts_with("ALTER SEQUENCE")
452 || upper.starts_with("ALTER SCHEMA")
453 || upper.starts_with("COMMENT ON")
454 }
455
456 fn strip_leading_sql_comments(&self, stmt: &str) -> String {
458 let mut result = stmt.trim();
459 loop {
460 if result.starts_with("--") {
462 if let Some(pos) = result.find('\n') {
463 result = result[pos + 1..].trim();
464 continue;
465 } else {
466 return String::new();
467 }
468 }
469 if result.starts_with("/*") {
471 if let Some(pos) = result.find("*/") {
472 result = result[pos + 2..].trim();
473 continue;
474 } else {
475 return String::new();
476 }
477 }
478 break;
479 }
480 result.to_string()
481 }
482
483 fn is_sqlite_pragma(&self, stmt: &str) -> bool {
485 let upper = stmt.to_uppercase();
486 upper.contains("PRAGMA")
487 }
488
489 fn is_mssql_session_command(&self, stmt: &str) -> bool {
491 let upper = stmt.to_uppercase();
492 upper.contains("SET ANSI_NULLS")
493 || upper.contains("SET QUOTED_IDENTIFIER")
494 || upper.contains("SET NOCOUNT")
495 || upper.contains("SET XACT_ABORT")
496 || upper.contains("SET ARITHABORT")
497 || upper.contains("SET ANSI_WARNINGS")
498 || upper.contains("SET ANSI_PADDING")
499 || upper.contains("SET CONCAT_NULL_YIELDS_NULL")
500 || upper.contains("SET NUMERIC_ROUNDABORT")
501 || upper.contains("SET IDENTITY_INSERT")
502 }
503
504 fn convert_identifiers(&self, stmt: &str) -> String {
506 match (self.from, self.to) {
507 (SqlDialect::MySql, SqlDialect::Postgres | SqlDialect::Sqlite) => {
508 self.backticks_to_double_quotes(stmt)
510 }
511 (SqlDialect::MySql, SqlDialect::Mssql) => {
512 self.backticks_to_square_brackets(stmt)
514 }
515 (SqlDialect::Postgres | SqlDialect::Sqlite, SqlDialect::MySql) => {
516 self.double_quotes_to_backticks(stmt)
518 }
519 (SqlDialect::Postgres | SqlDialect::Sqlite, SqlDialect::Mssql) => {
520 self.double_quotes_to_square_brackets(stmt)
522 }
523 (SqlDialect::Mssql, SqlDialect::MySql) => {
524 self.square_brackets_to_backticks(stmt)
526 }
527 (SqlDialect::Mssql, SqlDialect::Postgres | SqlDialect::Sqlite) => {
528 self.square_brackets_to_double_quotes(stmt)
530 }
531 _ => stmt.to_string(),
532 }
533 }
534
535 pub fn backticks_to_double_quotes(&self, stmt: &str) -> String {
537 let mut result = String::with_capacity(stmt.len());
538 let mut in_string = false;
539 let mut in_backtick = false;
540
541 for c in stmt.chars() {
542 if c == '\'' && !in_backtick {
543 in_string = !in_string;
544 result.push(c);
545 } else if c == '`' && !in_string {
546 in_backtick = !in_backtick;
547 result.push('"');
548 } else {
549 result.push(c);
550 }
551 }
552 result
553 }
554
555 pub fn double_quotes_to_backticks(&self, stmt: &str) -> String {
557 let mut result = String::with_capacity(stmt.len());
558 let mut in_string = false;
559 let mut in_dquote = false;
560 let chars = stmt.chars();
561
562 for c in chars {
563 if c == '\'' && !in_dquote {
564 in_string = !in_string;
565 result.push(c);
566 } else if c == '"' && !in_string {
567 in_dquote = !in_dquote;
568 result.push('`');
569 } else {
570 result.push(c);
571 }
572 }
573 result
574 }
575
576 pub fn backticks_to_square_brackets(&self, stmt: &str) -> String {
578 let mut result = String::with_capacity(stmt.len());
579 let mut in_string = false;
580 let mut in_backtick = false;
581
582 for c in stmt.chars() {
583 if c == '\'' && !in_backtick {
584 in_string = !in_string;
585 result.push(c);
586 } else if c == '`' && !in_string {
587 if !in_backtick {
588 result.push('[');
589 } else {
590 result.push(']');
591 }
592 in_backtick = !in_backtick;
593 } else {
594 result.push(c);
595 }
596 }
597 result
598 }
599
600 pub fn double_quotes_to_square_brackets(&self, stmt: &str) -> String {
602 let mut result = String::with_capacity(stmt.len());
603 let mut in_string = false;
604 let mut in_dquote = false;
605
606 for c in stmt.chars() {
607 if c == '\'' && !in_dquote {
608 in_string = !in_string;
609 result.push(c);
610 } else if c == '"' && !in_string {
611 if !in_dquote {
612 result.push('[');
613 } else {
614 result.push(']');
615 }
616 in_dquote = !in_dquote;
617 } else {
618 result.push(c);
619 }
620 }
621 result
622 }
623
624 pub fn square_brackets_to_backticks(&self, stmt: &str) -> String {
626 let mut result = String::with_capacity(stmt.len());
627 let mut in_string = false;
628
629 for c in stmt.chars() {
630 if c == '\'' {
631 in_string = !in_string;
632 result.push(c);
633 } else if !in_string && (c == '[' || c == ']') {
634 result.push('`');
635 } else {
636 result.push(c);
637 }
638 }
639 result
640 }
641
642 pub fn square_brackets_to_double_quotes(&self, stmt: &str) -> String {
644 let mut result = String::with_capacity(stmt.len());
645 let mut in_string = false;
646
647 for c in stmt.chars() {
648 if c == '\'' {
649 in_string = !in_string;
650 result.push(c);
651 } else if !in_string && (c == '[' || c == ']') {
652 result.push('"');
653 } else {
654 result.push(c);
655 }
656 }
657 result
658 }
659
660 fn convert_data_types(&self, stmt: &str) -> String {
662 TypeMapper::convert(stmt, self.from, self.to)
663 }
664
665 fn convert_auto_increment(&self, stmt: &str, _table_name: Option<&str>) -> String {
667 let stmt = if self.from == SqlDialect::MySql && self.to != SqlDialect::MySql {
673 self.strip_mysql_auto_increment_table_option(stmt)
674 } else {
675 stmt.to_string()
676 };
677 let stmt = stmt.as_str();
678
679 match (self.from, self.to) {
680 (SqlDialect::MySql, SqlDialect::Postgres) => {
681 self.convert_mysql_auto_increment_keyword(stmt)
687 }
688 (SqlDialect::MySql, SqlDialect::Sqlite) => {
689 let mut result = stmt.to_string();
695 for sized in [
696 "BIGINT AUTO_INCREMENT",
697 "bigint AUTO_INCREMENT",
698 "MEDIUMINT AUTO_INCREMENT",
699 "mediumint AUTO_INCREMENT",
700 "SMALLINT AUTO_INCREMENT",
701 "smallint AUTO_INCREMENT",
702 "TINYINT AUTO_INCREMENT",
703 "tinyint AUTO_INCREMENT",
704 ] {
705 result = result.replace(sized, "INTEGER");
706 }
707 let result = result.replace("INT AUTO_INCREMENT", "INTEGER");
708 let result = result.replace("int AUTO_INCREMENT", "INTEGER");
709 result.replace("AUTO_INCREMENT", "")
710 }
711 (SqlDialect::Postgres, SqlDialect::MySql) => {
712 let result = stmt.replace("BIGSERIAL", "BIGINT AUTO_INCREMENT");
715 let result = result.replace("bigserial", "BIGINT AUTO_INCREMENT");
716 let result = result.replace("SMALLSERIAL", "SMALLINT AUTO_INCREMENT");
717 let result = result.replace("smallserial", "SMALLINT AUTO_INCREMENT");
718 let result = result.replace("SERIAL", "INT AUTO_INCREMENT");
719 result.replace("serial", "INT AUTO_INCREMENT")
720 }
721 (SqlDialect::Postgres, SqlDialect::Sqlite) => {
722 let result = stmt.replace("BIGSERIAL", "INTEGER");
724 let result = result.replace("bigserial", "INTEGER");
725 let result = result.replace("SMALLSERIAL", "INTEGER");
726 let result = result.replace("smallserial", "INTEGER");
727 let result = result.replace("SERIAL", "INTEGER");
728 result.replace("serial", "INTEGER")
729 }
730 (SqlDialect::Sqlite, SqlDialect::MySql) => {
731 stmt.to_string()
734 }
735 (SqlDialect::Sqlite, SqlDialect::Postgres) => {
736 stmt.to_string()
739 }
740 (SqlDialect::MySql, SqlDialect::Mssql) => {
742 let result = stmt.replace("BIGINT AUTO_INCREMENT", "BIGINT IDENTITY(1,1)");
744 let result = result.replace("bigint AUTO_INCREMENT", "BIGINT IDENTITY(1,1)");
745 let result = result.replace("INT AUTO_INCREMENT", "INT IDENTITY(1,1)");
746 let result = result.replace("int AUTO_INCREMENT", "INT IDENTITY(1,1)");
747 result.replace("AUTO_INCREMENT", "IDENTITY(1,1)")
748 }
749 (SqlDialect::Mssql, SqlDialect::MySql) => {
750 self.convert_identity_to_auto_increment(stmt)
752 }
753 (SqlDialect::Postgres, SqlDialect::Mssql) => {
754 stmt.to_string()
756 }
757 (SqlDialect::Mssql, SqlDialect::Postgres) => {
758 self.convert_identity_to_serial(stmt)
760 }
761 (SqlDialect::Sqlite, SqlDialect::Mssql) => {
762 stmt.to_string()
764 }
765 (SqlDialect::Mssql, SqlDialect::Sqlite) => {
766 self.strip_identity(stmt)
768 }
769 _ => stmt.to_string(),
770 }
771 }
772
773 fn convert_identity_to_auto_increment(&self, stmt: &str) -> String {
775 use once_cell::sync::Lazy;
776 use regex::Regex;
777
778 static RE_IDENTITY: Lazy<Regex> =
779 Lazy::new(|| Regex::new(r"(?i)\bIDENTITY\s*\(\s*\d+\s*,\s*\d+\s*\)").unwrap());
780
781 RE_IDENTITY.replace_all(stmt, "AUTO_INCREMENT").to_string()
782 }
783
784 fn convert_identity_to_serial(&self, stmt: &str) -> String {
786 use once_cell::sync::Lazy;
787 use regex::Regex;
788
789 static RE_BIGINT_IDENTITY: Lazy<Regex> =
791 Lazy::new(|| Regex::new(r"(?i)\bBIGINT\s+IDENTITY\s*\(\s*\d+\s*,\s*\d+\s*\)").unwrap());
792 static RE_INT_IDENTITY: Lazy<Regex> =
793 Lazy::new(|| Regex::new(r"(?i)\bINT\s+IDENTITY\s*\(\s*\d+\s*,\s*\d+\s*\)").unwrap());
794 static RE_SMALLINT_IDENTITY: Lazy<Regex> = Lazy::new(|| {
795 Regex::new(r"(?i)\bSMALLINT\s+IDENTITY\s*\(\s*\d+\s*,\s*\d+\s*\)").unwrap()
796 });
797
798 let result = RE_BIGINT_IDENTITY
799 .replace_all(stmt, "BIGSERIAL")
800 .to_string();
801 let result = RE_INT_IDENTITY.replace_all(&result, "SERIAL").to_string();
802 RE_SMALLINT_IDENTITY
803 .replace_all(&result, "SMALLSERIAL")
804 .to_string()
805 }
806
807 fn strip_identity(&self, stmt: &str) -> String {
809 use once_cell::sync::Lazy;
810 use regex::Regex;
811
812 static RE_IDENTITY: Lazy<Regex> =
813 Lazy::new(|| Regex::new(r"(?i)\s*IDENTITY\s*\(\s*\d+\s*,\s*\d+\s*\)").unwrap());
814
815 RE_IDENTITY.replace_all(stmt, "").to_string()
816 }
817
818 fn convert_string_escapes(&self, stmt: &str) -> String {
820 match (self.from, self.to) {
821 (SqlDialect::MySql, SqlDialect::Postgres | SqlDialect::Sqlite) => {
822 self.mysql_escapes_to_standard(stmt)
824 }
825 _ => stmt.to_string(),
826 }
827 }
828
829 fn mysql_escapes_to_standard(&self, stmt: &str) -> String {
831 let mut result = String::with_capacity(stmt.len());
832 let mut chars = stmt.chars().peekable();
833 let mut in_string = false;
834
835 while let Some(c) = chars.next() {
836 if c == '\'' {
837 in_string = !in_string;
838 result.push(c);
839 } else if c == '\\' && in_string {
840 if let Some(&next) = chars.peek() {
842 match next {
843 '\'' => {
844 chars.next();
846 result.push_str("''");
847 }
848 '\\' => {
849 chars.next();
851 result.push_str("\\\\");
852 }
853 'n' | 'r' | 't' | '0' => {
854 result.push(c);
856 }
857 _ => {
858 result.push(c);
859 }
860 }
861 } else {
862 result.push(c);
863 }
864 } else {
865 result.push(c);
866 }
867 }
868 result
869 }
870
871 fn strip_conditional_comments(&self, stmt: &str) -> String {
873 let mut result = String::with_capacity(stmt.len());
874 let mut chars = stmt.chars().peekable();
875
876 while let Some(c) = chars.next() {
877 if c == '/' && chars.peek() == Some(&'*') {
878 chars.next(); if chars.peek() == Some(&'!') {
880 chars.next(); while chars.peek().map(|c| c.is_ascii_digit()).unwrap_or(false) {
884 chars.next();
885 }
886 let mut depth = 1;
888 while depth > 0 {
889 match chars.next() {
890 Some('*') if chars.peek() == Some(&'/') => {
891 chars.next();
892 depth -= 1;
893 }
894 Some('/') if chars.peek() == Some(&'*') => {
895 chars.next();
896 depth += 1;
897 }
898 None => break,
899 _ => {}
900 }
901 }
902 } else {
903 result.push('/');
905 result.push('*');
906 }
907 } else {
908 result.push(c);
909 }
910 }
911 result
912 }
913
914 fn strip_engine_clause(&self, stmt: &str) -> String {
916 use once_cell::sync::Lazy;
917 use regex::Regex;
918
919 if self.to == SqlDialect::MySql {
920 return stmt.to_string();
921 }
922
923 static RE_ENGINE: Lazy<Regex> =
925 Lazy::new(|| Regex::new(r"(?i)\s*ENGINE\s*=\s*\w+").unwrap());
926 RE_ENGINE.replace_all(stmt, "").to_string()
927 }
928
929 fn strip_charset_clauses(&self, stmt: &str) -> String {
931 use once_cell::sync::Lazy;
932 use regex::Regex;
933
934 if self.to == SqlDialect::MySql {
935 return stmt.to_string();
936 }
937
938 static RE_CHARSET: Lazy<Regex> =
939 Lazy::new(|| Regex::new(r"(?i)\s*(DEFAULT\s+)?CHARSET\s*=\s*\w+").unwrap());
940 static RE_COLLATE: Lazy<Regex> =
941 Lazy::new(|| Regex::new(r"(?i)\s*COLLATE\s*=?\s*\w+").unwrap());
942
943 let result = RE_CHARSET.replace_all(stmt, "").to_string();
944 RE_COLLATE.replace_all(&result, "").to_string()
945 }
946
947 fn match_keyword_ci(chars: &[char], pos: usize, keyword: &str) -> Option<usize> {
952 let kw_len = keyword.len();
953 if pos > 0 && (chars[pos - 1].is_alphanumeric() || chars[pos - 1] == '_') {
954 return None;
955 }
956 let end = pos + kw_len;
957 if end > chars.len() {
958 return None;
959 }
960 let candidate: String = chars[pos..end].iter().collect();
961 if !candidate.eq_ignore_ascii_case(keyword) {
962 return None;
963 }
964 if end < chars.len() && (chars[end].is_alphanumeric() || chars[end] == '_') {
965 return None;
966 }
967 Some(end)
968 }
969
970 fn trim_trailing_whitespace(result: &mut String) {
974 while result.ends_with(|c: char| c.is_whitespace()) {
975 result.pop();
976 }
977 }
978
979 fn strip_mysql_auto_increment_table_option(&self, stmt: &str) -> String {
984 let chars: Vec<char> = stmt.chars().collect();
985 let n = chars.len();
986 let mut result = String::with_capacity(stmt.len());
987 let mut in_string = false;
988 let mut i = 0;
989
990 while i < n {
991 let c = chars[i];
992 if c == '\'' {
993 in_string = !in_string;
994 result.push(c);
995 i += 1;
996 continue;
997 }
998 if !in_string {
999 if let Some(after_kw) = Self::match_keyword_ci(&chars, i, "AUTO_INCREMENT") {
1000 let mut j = after_kw;
1001 while j < n && chars[j].is_whitespace() {
1002 j += 1;
1003 }
1004 if j < n && chars[j] == '=' {
1005 j += 1;
1006 while j < n && chars[j].is_whitespace() {
1007 j += 1;
1008 }
1009 let digits_start = j;
1010 while j < n && chars[j].is_ascii_digit() {
1011 j += 1;
1012 }
1013 if j > digits_start {
1014 Self::trim_trailing_whitespace(&mut result);
1015 i = j;
1016 continue;
1017 }
1018 }
1019 }
1020 }
1021 result.push(c);
1022 i += 1;
1023 }
1024 result
1025 }
1026
1027 fn strip_mysql_comment_clauses(&self, stmt: &str) -> String {
1033 if self.to == SqlDialect::MySql {
1034 return stmt.to_string();
1035 }
1036
1037 let chars: Vec<char> = stmt.chars().collect();
1038 let n = chars.len();
1039 let mut result = String::with_capacity(stmt.len());
1040 let mut in_string = false;
1041 let mut i = 0;
1042
1043 while i < n {
1044 let c = chars[i];
1045 if c == '\'' {
1046 in_string = !in_string;
1047 result.push(c);
1048 i += 1;
1049 continue;
1050 }
1051 if !in_string {
1052 if let Some(after_kw) = Self::match_keyword_ci(&chars, i, "COMMENT") {
1053 let mut j = after_kw;
1054 while j < n && chars[j].is_whitespace() {
1055 j += 1;
1056 }
1057 if j < n && chars[j] == '=' {
1058 j += 1;
1059 while j < n && chars[j].is_whitespace() {
1060 j += 1;
1061 }
1062 }
1063 if j < n && chars[j] == '\'' {
1064 j += 1;
1067 loop {
1068 if j >= n {
1069 break;
1070 }
1071 if chars[j] == '\'' {
1072 if j + 1 < n && chars[j + 1] == '\'' {
1073 j += 2;
1074 continue;
1075 }
1076 j += 1;
1077 break;
1078 }
1079 j += 1;
1080 }
1081 Self::trim_trailing_whitespace(&mut result);
1082 i = j;
1083 continue;
1084 }
1085 }
1086 }
1087 result.push(c);
1088 i += 1;
1089 }
1090 result
1091 }
1092
1093 fn convert_mysql_auto_increment_keyword(&self, stmt: &str) -> String {
1099 let chars: Vec<char> = stmt.chars().collect();
1100 let n = chars.len();
1101 let mut result = String::with_capacity(stmt.len());
1102 let mut in_string = false;
1103 let mut i = 0;
1104
1105 while i < n {
1106 let c = chars[i];
1107 if c == '\'' {
1108 in_string = !in_string;
1109 result.push(c);
1110 i += 1;
1111 continue;
1112 }
1113 if !in_string {
1114 if let Some(after_type) = Self::match_keyword_ci(&chars, i, "BIGINT") {
1115 let mut j = after_type;
1116 while j < n && chars[j].is_whitespace() {
1117 j += 1;
1118 }
1119 if let Some(end) = Self::match_keyword_ci(&chars, j, "AUTO_INCREMENT") {
1120 result.push_str("BIGSERIAL");
1121 i = end;
1122 continue;
1123 }
1124 }
1125 if let Some(after_type) = Self::match_keyword_ci(&chars, i, "INT") {
1126 let mut j = after_type;
1127 while j < n && chars[j].is_whitespace() {
1128 j += 1;
1129 }
1130 if let Some(end) = Self::match_keyword_ci(&chars, j, "AUTO_INCREMENT") {
1131 result.push_str("SERIAL");
1132 i = end;
1133 continue;
1134 }
1135 }
1136 if let Some(end) = Self::match_keyword_ci(&chars, i, "AUTO_INCREMENT") {
1137 i = end;
1141 continue;
1142 }
1143 }
1144 result.push(c);
1145 i += 1;
1146 }
1147 result
1148 }
1149
1150 fn convert_unique_key_constraint(&self, stmt: &str) -> String {
1155 use once_cell::sync::Lazy;
1156 use regex::{Captures, Regex};
1157
1158 if self.to == SqlDialect::MySql {
1159 return stmt.to_string();
1160 }
1161
1162 static RE: Lazy<Regex> = Lazy::new(|| {
1166 Regex::new(
1167 r#"(?i)UNIQUE\s+KEY\s+(?:"[^"]*"\s+)?(\([^()]*(?:\(\d+\)[^()]*)*\))(?:\s*USING\s+(?:BTREE|HASH))?"#,
1168 )
1169 .unwrap()
1170 });
1171 static RE_PREFIX_LEN: Lazy<Regex> = Lazy::new(|| Regex::new(r"\(\d+\)").unwrap());
1172
1173 RE.replace_all(stmt, |caps: &Captures| {
1174 let cols = RE_PREFIX_LEN.replace_all(&caps[1], "");
1175 format!("UNIQUE {}", cols)
1176 })
1177 .to_string()
1178 }
1179
1180 fn strip_postgres_casts(&self, stmt: &str) -> String {
1182 use once_cell::sync::Lazy;
1183 use regex::Regex;
1184
1185 static RE_CAST: Lazy<Regex> = Lazy::new(|| {
1187 Regex::new(r"::[a-zA-Z_][a-zA-Z0-9_]*(?:\s+[a-zA-Z_][a-zA-Z0-9_]*)*").unwrap()
1188 });
1189
1190 RE_CAST.replace_all(stmt, "").to_string()
1191 }
1192
1193 fn convert_nextval(&self, stmt: &str) -> String {
1195 use once_cell::sync::Lazy;
1196 use regex::Regex;
1197
1198 static RE_NEXTVAL: Lazy<Regex> =
1201 Lazy::new(|| Regex::new(r"(?i)\s*DEFAULT\s+nextval\s*\([^)]+\)").unwrap());
1202
1203 RE_NEXTVAL.replace_all(stmt, "").to_string()
1204 }
1205
1206 fn convert_default_now(&self, stmt: &str) -> String {
1208 use once_cell::sync::Lazy;
1209 use regex::Regex;
1210
1211 static RE_NOW: Lazy<Regex> =
1212 Lazy::new(|| Regex::new(r"(?i)\bDEFAULT\s+now\s*\(\s*\)").unwrap());
1213
1214 RE_NOW
1215 .replace_all(stmt, "DEFAULT CURRENT_TIMESTAMP")
1216 .to_string()
1217 }
1218
1219 fn strip_schema_prefix(&self, stmt: &str) -> String {
1221 use once_cell::sync::Lazy;
1222 use regex::Regex;
1223
1224 static RE_SCHEMA: Lazy<Regex> =
1227 Lazy::new(|| Regex::new(r#"(?i)\b(public|pg_catalog|pg_temp)\s*\.\s*"#).unwrap());
1228
1229 RE_SCHEMA.replace_all(stmt, "").to_string()
1230 }
1231
1232 fn convert_mssql_getdate(&self, stmt: &str) -> String {
1234 use once_cell::sync::Lazy;
1235 use regex::Regex;
1236
1237 static RE_GETDATE: Lazy<Regex> =
1238 Lazy::new(|| Regex::new(r"(?i)\bGETDATE\s*\(\s*\)").unwrap());
1239 static RE_SYSDATETIME: Lazy<Regex> =
1240 Lazy::new(|| Regex::new(r"(?i)\bSYSDATETIME\s*\(\s*\)").unwrap());
1241 static RE_GETUTCDATE: Lazy<Regex> =
1242 Lazy::new(|| Regex::new(r"(?i)\bGETUTCDATE\s*\(\s*\)").unwrap());
1243
1244 let result = RE_GETDATE
1245 .replace_all(stmt, "CURRENT_TIMESTAMP")
1246 .to_string();
1247 let result = RE_SYSDATETIME
1248 .replace_all(&result, "CURRENT_TIMESTAMP")
1249 .to_string();
1250 RE_GETUTCDATE
1251 .replace_all(&result, "CURRENT_TIMESTAMP")
1252 .to_string()
1253 }
1254
1255 fn strip_mssql_on_filegroup(&self, stmt: &str) -> String {
1257 use once_cell::sync::Lazy;
1258 use regex::Regex;
1259
1260 static RE_ON_FILEGROUP: Lazy<Regex> =
1262 Lazy::new(|| Regex::new(r"(?i)\s+ON\s*\[\s*\w+\s*\]").unwrap());
1263
1264 RE_ON_FILEGROUP.replace_all(stmt, "").to_string()
1265 }
1266
1267 fn strip_mssql_clustered(&self, stmt: &str) -> String {
1269 use once_cell::sync::Lazy;
1270 use regex::Regex;
1271
1272 static RE_CLUSTERED: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bCLUSTERED\s+").unwrap());
1273 static RE_NONCLUSTERED: Lazy<Regex> =
1274 Lazy::new(|| Regex::new(r"(?i)\bNONCLUSTERED\s+").unwrap());
1275
1276 let result = RE_CLUSTERED.replace_all(stmt, "").to_string();
1277 RE_NONCLUSTERED.replace_all(&result, "").to_string()
1278 }
1279
1280 fn convert_mssql_unicode_strings(&self, stmt: &str) -> String {
1282 use once_cell::sync::Lazy;
1283 use regex::Regex;
1284
1285 static RE_UNICODE_STRING: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bN'").unwrap());
1288
1289 RE_UNICODE_STRING.replace_all(stmt, "'").to_string()
1290 }
1291
1292 fn strip_mssql_schema_prefix(&self, stmt: &str) -> String {
1294 use once_cell::sync::Lazy;
1295 use regex::Regex;
1296
1297 static RE_MSSQL_SCHEMA: Lazy<Regex> =
1300 Lazy::new(|| Regex::new(r"(?i)\[?dbo\]?\s*\.\s*").unwrap());
1301
1302 RE_MSSQL_SCHEMA.replace_all(stmt, "").to_string()
1303 }
1304
1305 fn detect_unsupported_features(
1307 &mut self,
1308 stmt: &str,
1309 table_name: Option<&str>,
1310 ) -> Result<(), ConvertWarning> {
1311 let upper = stmt.to_uppercase();
1312
1313 if self.from == SqlDialect::MySql {
1315 if upper.contains("ENUM(") {
1317 let warning = ConvertWarning::UnsupportedFeature {
1318 feature: format!(
1319 "ENUM type{}",
1320 table_name
1321 .map(|t| format!(" in table {}", t))
1322 .unwrap_or_default()
1323 ),
1324 suggestion: Some(
1325 "Converted to VARCHAR - consider adding CHECK constraint".to_string(),
1326 ),
1327 };
1328 self.warnings.add(warning.clone());
1329 if self.strict {
1330 return Err(warning);
1331 }
1332 }
1333
1334 if upper.contains("SET(") {
1336 let warning = ConvertWarning::UnsupportedFeature {
1337 feature: format!(
1338 "SET type{}",
1339 table_name
1340 .map(|t| format!(" in table {}", t))
1341 .unwrap_or_default()
1342 ),
1343 suggestion: Some(
1344 "Converted to VARCHAR - SET semantics not preserved".to_string(),
1345 ),
1346 };
1347 self.warnings.add(warning.clone());
1348 if self.strict {
1349 return Err(warning);
1350 }
1351 }
1352
1353 if upper.contains("UNSIGNED") {
1355 self.warnings.add(ConvertWarning::UnsupportedFeature {
1356 feature: "UNSIGNED modifier".to_string(),
1357 suggestion: Some(
1358 "Removed - consider adding CHECK constraint for non-negative values"
1359 .to_string(),
1360 ),
1361 });
1362 }
1363 }
1364
1365 if self.from == SqlDialect::Postgres {
1367 if upper.contains("[]") || upper.contains("ARRAY[") {
1369 let warning = ConvertWarning::UnsupportedFeature {
1370 feature: format!(
1371 "Array type{}",
1372 table_name
1373 .map(|t| format!(" in table {}", t))
1374 .unwrap_or_default()
1375 ),
1376 suggestion: Some(
1377 "Array types not supported in target dialect - consider using JSON"
1378 .to_string(),
1379 ),
1380 };
1381 self.warnings.add(warning.clone());
1382 if self.strict {
1383 return Err(warning);
1384 }
1385 }
1386
1387 if upper.contains("INHERITS") {
1389 let warning = ConvertWarning::UnsupportedFeature {
1390 feature: "Table inheritance (INHERITS)".to_string(),
1391 suggestion: Some(
1392 "PostgreSQL table inheritance not supported in target dialect".to_string(),
1393 ),
1394 };
1395 self.warnings.add(warning.clone());
1396 if self.strict {
1397 return Err(warning);
1398 }
1399 }
1400
1401 if upper.contains("PARTITION BY") && self.to == SqlDialect::Sqlite {
1403 let warning = ConvertWarning::UnsupportedFeature {
1404 feature: "Table partitioning".to_string(),
1405 suggestion: Some("Partitioning not supported in SQLite".to_string()),
1406 };
1407 self.warnings.add(warning.clone());
1408 if self.strict {
1409 return Err(warning);
1410 }
1411 }
1412 }
1413
1414 Ok(())
1415 }
1416
1417 pub fn warnings(&self) -> &[ConvertWarning] {
1419 self.warnings.warnings()
1420 }
1421}
1422
1423pub fn run(config: ConvertConfig) -> anyhow::Result<ConvertStats> {
1425 let mut stats = ConvertStats::default();
1426
1427 let from_dialect = if let Some(d) = config.from_dialect {
1429 d
1430 } else {
1431 let result = crate::parser::detect_dialect_from_file(&config.input)?;
1432 if config.progress {
1433 eprintln!(
1434 "Auto-detected source dialect: {} (confidence: {:?})",
1435 result.dialect, result.confidence
1436 );
1437 }
1438 result.dialect
1439 };
1440
1441 if from_dialect == config.to_dialect {
1443 anyhow::bail!(
1444 "Source and target dialects are the same ({}). No conversion needed.",
1445 from_dialect
1446 );
1447 }
1448
1449 let file_size = std::fs::metadata(&config.input)?.len();
1451
1452 let progress_bar = if config.progress {
1453 let pb = ProgressBar::new(file_size);
1454 pb.set_style(
1455 ProgressStyle::with_template(
1456 "{spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] {bytes}/{total_bytes} ({percent}%) {msg}",
1457 )
1458 .unwrap()
1459 .progress_chars("█▓▒░ ")
1460 .tick_chars("⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"),
1461 );
1462 pb.enable_steady_tick(std::time::Duration::from_millis(100));
1463 pb.set_message("Converting...");
1464 Some(pb)
1465 } else {
1466 None
1467 };
1468
1469 let mut converter = Converter::new(from_dialect, config.to_dialect).with_strict(config.strict);
1471
1472 let reader: Box<dyn Read> = if let Some(ref pb) = progress_bar {
1475 let pb_clone = pb.clone();
1476 open_input_with_progress(
1477 &config.input,
1478 Box::new(move |bytes| pb_clone.set_position(bytes)),
1479 )?
1480 } else {
1481 open_input(&config.input)?
1482 };
1483 let mut parser = Parser::with_dialect(reader, 64 * 1024, from_dialect);
1484
1485 let mut writer: Box<dyn Write> = if config.dry_run {
1487 Box::new(std::io::sink())
1488 } else {
1489 match &config.output {
1490 Some(path) => {
1491 if let Some(parent) = path.parent() {
1492 std::fs::create_dir_all(parent)?;
1493 }
1494 Box::new(BufWriter::with_capacity(256 * 1024, File::create(path)?))
1495 }
1496 None => Box::new(BufWriter::new(std::io::stdout())),
1497 }
1498 };
1499
1500 if !config.dry_run {
1502 write_header(&mut writer, &config, from_dialect)?;
1503 }
1504
1505 while let Some(stmt) = parser.read_statement()? {
1507 stats.statements_processed += 1;
1508
1509 if converter.has_pending_copy() {
1511 match converter.process_copy_data(&stmt) {
1513 Ok(inserts) => {
1514 for insert in inserts {
1515 if !insert.is_empty() {
1516 stats.statements_converted += 1;
1517 if !config.dry_run {
1518 writer.write_all(&insert)?;
1519 writer.write_all(b"\n")?;
1520 }
1521 }
1522 }
1523 }
1524 Err(warning) => {
1525 stats.warnings.push(warning);
1526 stats.statements_skipped += 1;
1527 }
1528 }
1529 continue;
1530 }
1531
1532 match converter.convert_statement(&stmt) {
1533 Ok(converted) => {
1534 if converted.is_empty() {
1535 stats.statements_skipped += 1;
1536 } else if converted == stmt {
1537 stats.statements_unchanged += 1;
1538 if !config.dry_run {
1539 writer.write_all(&converted)?;
1540 writer.write_all(b"\n")?;
1541 }
1542 } else {
1543 stats.statements_converted += 1;
1544 if !config.dry_run {
1545 writer.write_all(&converted)?;
1546 writer.write_all(b"\n")?;
1547 }
1548 }
1549 }
1550 Err(warning) => {
1551 stats.warnings.push(warning);
1552 stats.statements_skipped += 1;
1553 }
1554 }
1555 }
1556
1557 stats.warnings.extend(converter.warnings().iter().cloned());
1559
1560 if let Some(pb) = progress_bar {
1561 pb.finish_with_message("done");
1562 }
1563
1564 Ok(stats)
1565}
1566
1567fn write_header(
1569 writer: &mut dyn Write,
1570 config: &ConvertConfig,
1571 from: SqlDialect,
1572) -> std::io::Result<()> {
1573 writeln!(writer, "-- Converted by sql-splitter")?;
1574 writeln!(writer, "-- From: {} → To: {}", from, config.to_dialect)?;
1575 writeln!(writer, "-- Source: {}", config.input.display())?;
1576 writeln!(writer)?;
1577
1578 match config.to_dialect {
1580 SqlDialect::Postgres => {
1581 writeln!(writer, "SET client_encoding = 'UTF8';")?;
1582 writeln!(writer, "SET standard_conforming_strings = on;")?;
1583 }
1584 SqlDialect::Sqlite => {
1585 writeln!(writer, "PRAGMA foreign_keys = OFF;")?;
1586 }
1587 SqlDialect::MySql => {
1588 writeln!(writer, "SET NAMES utf8mb4;")?;
1589 writeln!(writer, "SET FOREIGN_KEY_CHECKS = 0;")?;
1590 }
1591 SqlDialect::Mssql => {
1592 writeln!(writer, "SET ANSI_NULLS ON;")?;
1593 writeln!(writer, "SET QUOTED_IDENTIFIER ON;")?;
1594 writeln!(writer, "SET NOCOUNT ON;")?;
1595 }
1596 }
1597 writeln!(writer)?;
1598
1599 Ok(())
1600}