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