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 use once_cell::sync::Lazy;
690 use regex::Regex;
691 static RE_SIZED_AI: Lazy<Regex> = Lazy::new(|| {
698 Regex::new(r"(?i)\b(?:BIG|MEDIUM|SMALL|TINY)?INT\s+AUTO_INCREMENT").unwrap()
699 });
700 static RE_BARE_AI: Lazy<Regex> =
704 Lazy::new(|| Regex::new(r"(?i)AUTO_INCREMENT\b").unwrap());
705 map_outside_string_literals(stmt, |seg| {
706 let seg = RE_SIZED_AI.replace_all(seg, "INTEGER");
707 RE_BARE_AI.replace_all(&seg, "").into_owned()
708 })
709 }
710 (SqlDialect::Postgres, SqlDialect::MySql) => {
711 let result = stmt.replace("BIGSERIAL", "BIGINT AUTO_INCREMENT");
714 let result = result.replace("bigserial", "BIGINT AUTO_INCREMENT");
715 let result = result.replace("SMALLSERIAL", "SMALLINT AUTO_INCREMENT");
716 let result = result.replace("smallserial", "SMALLINT AUTO_INCREMENT");
717 let result = result.replace("SERIAL", "INT AUTO_INCREMENT");
718 result.replace("serial", "INT AUTO_INCREMENT")
719 }
720 (SqlDialect::Postgres, SqlDialect::Sqlite) => {
721 let result = stmt.replace("BIGSERIAL", "INTEGER");
723 let result = result.replace("bigserial", "INTEGER");
724 let result = result.replace("SMALLSERIAL", "INTEGER");
725 let result = result.replace("smallserial", "INTEGER");
726 let result = result.replace("SERIAL", "INTEGER");
727 result.replace("serial", "INTEGER")
728 }
729 (SqlDialect::Sqlite, SqlDialect::MySql) => {
730 stmt.to_string()
733 }
734 (SqlDialect::Sqlite, SqlDialect::Postgres) => {
735 stmt.to_string()
738 }
739 (SqlDialect::MySql, SqlDialect::Mssql) => {
741 use once_cell::sync::Lazy;
742 use regex::Regex;
743 static RE_BIGINT_AI: Lazy<Regex> =
748 Lazy::new(|| Regex::new(r"(?i)\bBIGINT\s+AUTO_INCREMENT").unwrap());
749 static RE_INT_AI: Lazy<Regex> =
750 Lazy::new(|| Regex::new(r"(?i)\bINT\s+AUTO_INCREMENT").unwrap());
751 static RE_BARE_AI: Lazy<Regex> =
754 Lazy::new(|| Regex::new(r"(?i)AUTO_INCREMENT\b").unwrap());
755 map_outside_string_literals(stmt, |seg| {
756 let seg = RE_BIGINT_AI.replace_all(seg, "BIGINT IDENTITY(1,1)");
757 let seg = RE_INT_AI.replace_all(&seg, "INT IDENTITY(1,1)");
758 RE_BARE_AI.replace_all(&seg, "IDENTITY(1,1)").into_owned()
759 })
760 }
761 (SqlDialect::Mssql, SqlDialect::MySql) => {
762 self.convert_identity_to_auto_increment(stmt)
764 }
765 (SqlDialect::Postgres, SqlDialect::Mssql) => {
766 stmt.to_string()
768 }
769 (SqlDialect::Mssql, SqlDialect::Postgres) => {
770 self.convert_identity_to_serial(stmt)
772 }
773 (SqlDialect::Sqlite, SqlDialect::Mssql) => {
774 stmt.to_string()
776 }
777 (SqlDialect::Mssql, SqlDialect::Sqlite) => {
778 self.strip_identity(stmt)
780 }
781 _ => stmt.to_string(),
782 }
783 }
784
785 fn convert_identity_to_auto_increment(&self, stmt: &str) -> String {
787 use once_cell::sync::Lazy;
788 use regex::Regex;
789
790 static RE_IDENTITY: Lazy<Regex> =
791 Lazy::new(|| Regex::new(r"(?i)\bIDENTITY\s*\(\s*\d+\s*,\s*\d+\s*\)").unwrap());
792
793 RE_IDENTITY.replace_all(stmt, "AUTO_INCREMENT").to_string()
794 }
795
796 fn convert_identity_to_serial(&self, stmt: &str) -> String {
798 use once_cell::sync::Lazy;
799 use regex::Regex;
800
801 static RE_BIGINT_IDENTITY: Lazy<Regex> =
803 Lazy::new(|| Regex::new(r"(?i)\bBIGINT\s+IDENTITY\s*\(\s*\d+\s*,\s*\d+\s*\)").unwrap());
804 static RE_INT_IDENTITY: Lazy<Regex> =
805 Lazy::new(|| Regex::new(r"(?i)\bINT\s+IDENTITY\s*\(\s*\d+\s*,\s*\d+\s*\)").unwrap());
806 static RE_SMALLINT_IDENTITY: Lazy<Regex> = Lazy::new(|| {
807 Regex::new(r"(?i)\bSMALLINT\s+IDENTITY\s*\(\s*\d+\s*,\s*\d+\s*\)").unwrap()
808 });
809
810 let result = RE_BIGINT_IDENTITY
811 .replace_all(stmt, "BIGSERIAL")
812 .to_string();
813 let result = RE_INT_IDENTITY.replace_all(&result, "SERIAL").to_string();
814 RE_SMALLINT_IDENTITY
815 .replace_all(&result, "SMALLSERIAL")
816 .to_string()
817 }
818
819 fn strip_identity(&self, stmt: &str) -> String {
821 use once_cell::sync::Lazy;
822 use regex::Regex;
823
824 static RE_IDENTITY: Lazy<Regex> =
825 Lazy::new(|| Regex::new(r"(?i)\s*IDENTITY\s*\(\s*\d+\s*,\s*\d+\s*\)").unwrap());
826
827 RE_IDENTITY.replace_all(stmt, "").to_string()
828 }
829
830 fn convert_string_escapes(&self, stmt: &str) -> String {
832 match (self.from, self.to) {
833 (SqlDialect::MySql, SqlDialect::Postgres | SqlDialect::Sqlite | SqlDialect::Mssql) => {
837 self.mysql_escapes_to_standard(stmt)
838 }
839 _ => stmt.to_string(),
840 }
841 }
842
843 fn mysql_escapes_to_standard(&self, stmt: &str) -> String {
845 let mut result = String::with_capacity(stmt.len());
846 let mut chars = stmt.chars().peekable();
847 let mut in_string = false;
848
849 while let Some(c) = chars.next() {
850 if c == '\'' {
851 in_string = !in_string;
852 result.push(c);
853 } else if c == '\\' && in_string {
854 match chars.next() {
859 Some(next) => match next {
860 '\'' => result.push_str("''"),
862 '"' => result.push('"'),
863 '\\' => result.push('\\'),
865 'n' => result.push('\n'),
866 'r' => result.push('\r'),
867 't' => result.push('\t'),
868 '0' => result.push('\0'),
869 'b' => result.push('\u{08}'),
870 'Z' => result.push('\u{1a}'),
871 '%' => result.push_str("\\%"),
873 '_' => result.push_str("\\_"),
874 other => result.push(other),
876 },
877 None => result.push('\\'),
879 }
880 } else {
881 result.push(c);
882 }
883 }
884 result
885 }
886
887 fn strip_conditional_comments(&self, stmt: &str) -> String {
889 let mut result = String::with_capacity(stmt.len());
890 let mut chars = stmt.chars().peekable();
891
892 while let Some(c) = chars.next() {
893 if c == '/' && chars.peek() == Some(&'*') {
894 chars.next(); if chars.peek() == Some(&'!') {
896 chars.next(); while chars.peek().map(|c| c.is_ascii_digit()).unwrap_or(false) {
900 chars.next();
901 }
902 let mut depth = 1;
904 while depth > 0 {
905 match chars.next() {
906 Some('*') if chars.peek() == Some(&'/') => {
907 chars.next();
908 depth -= 1;
909 }
910 Some('/') if chars.peek() == Some(&'*') => {
911 chars.next();
912 depth += 1;
913 }
914 None => break,
915 _ => {}
916 }
917 }
918 } else {
919 result.push('/');
921 result.push('*');
922 }
923 } else {
924 result.push(c);
925 }
926 }
927 result
928 }
929
930 fn strip_engine_clause(&self, stmt: &str) -> String {
932 use once_cell::sync::Lazy;
933 use regex::Regex;
934
935 if self.to == SqlDialect::MySql {
936 return stmt.to_string();
937 }
938
939 static RE_ENGINE: Lazy<Regex> =
941 Lazy::new(|| Regex::new(r"(?i)\s*ENGINE\s*=\s*\w+").unwrap());
942 RE_ENGINE.replace_all(stmt, "").to_string()
943 }
944
945 fn strip_charset_clauses(&self, stmt: &str) -> String {
947 use once_cell::sync::Lazy;
948 use regex::Regex;
949
950 if self.to == SqlDialect::MySql {
951 return stmt.to_string();
952 }
953
954 static RE_CHARSET: Lazy<Regex> =
955 Lazy::new(|| Regex::new(r"(?i)\s*(DEFAULT\s+)?CHARSET\s*=\s*\w+").unwrap());
956 static RE_COLLATE: Lazy<Regex> =
957 Lazy::new(|| Regex::new(r"(?i)\s*COLLATE\s*=?\s*\w+").unwrap());
958
959 let result = RE_CHARSET.replace_all(stmt, "").to_string();
960 RE_COLLATE.replace_all(&result, "").to_string()
961 }
962
963 fn match_keyword_ci(chars: &[char], pos: usize, keyword: &str) -> Option<usize> {
968 let kw_len = keyword.len();
969 if pos > 0 && (chars[pos - 1].is_alphanumeric() || chars[pos - 1] == '_') {
970 return None;
971 }
972 let end = pos + kw_len;
973 if end > chars.len() {
974 return None;
975 }
976 let candidate: String = chars[pos..end].iter().collect();
977 if !candidate.eq_ignore_ascii_case(keyword) {
978 return None;
979 }
980 if end < chars.len() && (chars[end].is_alphanumeric() || chars[end] == '_') {
981 return None;
982 }
983 Some(end)
984 }
985
986 fn trim_trailing_whitespace(result: &mut String) {
990 while result.ends_with(|c: char| c.is_whitespace()) {
991 result.pop();
992 }
993 }
994
995 fn strip_mysql_auto_increment_table_option(&self, stmt: &str) -> String {
1000 let chars: Vec<char> = stmt.chars().collect();
1001 let n = chars.len();
1002 let mut result = String::with_capacity(stmt.len());
1003 let mut in_string = false;
1004 let mut i = 0;
1005
1006 while i < n {
1007 let c = chars[i];
1008 if c == '\'' {
1009 in_string = !in_string;
1010 result.push(c);
1011 i += 1;
1012 continue;
1013 }
1014 if !in_string {
1015 if let Some(after_kw) = Self::match_keyword_ci(&chars, i, "AUTO_INCREMENT") {
1016 let mut j = after_kw;
1017 while j < n && chars[j].is_whitespace() {
1018 j += 1;
1019 }
1020 if j < n && chars[j] == '=' {
1021 j += 1;
1022 while j < n && chars[j].is_whitespace() {
1023 j += 1;
1024 }
1025 let digits_start = j;
1026 while j < n && chars[j].is_ascii_digit() {
1027 j += 1;
1028 }
1029 if j > digits_start {
1030 Self::trim_trailing_whitespace(&mut result);
1031 i = j;
1032 continue;
1033 }
1034 }
1035 }
1036 }
1037 result.push(c);
1038 i += 1;
1039 }
1040 result
1041 }
1042
1043 fn strip_mysql_comment_clauses(&self, stmt: &str) -> String {
1049 if self.to == SqlDialect::MySql {
1050 return stmt.to_string();
1051 }
1052
1053 let chars: Vec<char> = stmt.chars().collect();
1054 let n = chars.len();
1055 let mut result = String::with_capacity(stmt.len());
1056 let mut in_string = false;
1057 let mut i = 0;
1058
1059 while i < n {
1060 let c = chars[i];
1061 if c == '\'' {
1062 in_string = !in_string;
1063 result.push(c);
1064 i += 1;
1065 continue;
1066 }
1067 if !in_string {
1068 if let Some(after_kw) = Self::match_keyword_ci(&chars, i, "COMMENT") {
1069 let mut j = after_kw;
1070 while j < n && chars[j].is_whitespace() {
1071 j += 1;
1072 }
1073 if j < n && chars[j] == '=' {
1074 j += 1;
1075 while j < n && chars[j].is_whitespace() {
1076 j += 1;
1077 }
1078 }
1079 if j < n && chars[j] == '\'' {
1080 j += 1;
1083 loop {
1084 if j >= n {
1085 break;
1086 }
1087 if chars[j] == '\'' {
1088 if j + 1 < n && chars[j + 1] == '\'' {
1089 j += 2;
1090 continue;
1091 }
1092 j += 1;
1093 break;
1094 }
1095 j += 1;
1096 }
1097 Self::trim_trailing_whitespace(&mut result);
1098 i = j;
1099 continue;
1100 }
1101 }
1102 }
1103 result.push(c);
1104 i += 1;
1105 }
1106 result
1107 }
1108
1109 fn convert_mysql_auto_increment_keyword(&self, stmt: &str) -> String {
1115 let chars: Vec<char> = stmt.chars().collect();
1116 let n = chars.len();
1117 let mut result = String::with_capacity(stmt.len());
1118 let mut in_string = false;
1119 let mut i = 0;
1120
1121 while i < n {
1122 let c = chars[i];
1123 if c == '\'' {
1124 in_string = !in_string;
1125 result.push(c);
1126 i += 1;
1127 continue;
1128 }
1129 if !in_string {
1130 if let Some(after_type) = Self::match_keyword_ci(&chars, i, "BIGINT") {
1131 let mut j = after_type;
1132 while j < n && chars[j].is_whitespace() {
1133 j += 1;
1134 }
1135 if let Some(end) = Self::match_keyword_ci(&chars, j, "AUTO_INCREMENT") {
1136 result.push_str("BIGSERIAL");
1137 i = end;
1138 continue;
1139 }
1140 }
1141 if let Some(after_type) = Self::match_keyword_ci(&chars, i, "INT") {
1142 let mut j = after_type;
1143 while j < n && chars[j].is_whitespace() {
1144 j += 1;
1145 }
1146 if let Some(end) = Self::match_keyword_ci(&chars, j, "AUTO_INCREMENT") {
1147 result.push_str("SERIAL");
1148 i = end;
1149 continue;
1150 }
1151 }
1152 if let Some(end) = Self::match_keyword_ci(&chars, i, "AUTO_INCREMENT") {
1153 i = end;
1157 continue;
1158 }
1159 }
1160 result.push(c);
1161 i += 1;
1162 }
1163 result
1164 }
1165
1166 fn convert_unique_key_constraint(&self, stmt: &str) -> String {
1171 use once_cell::sync::Lazy;
1172 use regex::{Captures, Regex};
1173
1174 if self.to == SqlDialect::MySql {
1175 return stmt.to_string();
1176 }
1177
1178 static RE: Lazy<Regex> = Lazy::new(|| {
1182 Regex::new(
1183 r#"(?i)UNIQUE\s+KEY\s+(?:"[^"]*"\s+)?(\([^()]*(?:\(\d+\)[^()]*)*\))(?:\s*USING\s+(?:BTREE|HASH))?"#,
1184 )
1185 .unwrap()
1186 });
1187 static RE_PREFIX_LEN: Lazy<Regex> = Lazy::new(|| Regex::new(r"\(\d+\)").unwrap());
1188
1189 RE.replace_all(stmt, |caps: &Captures| {
1190 let cols = RE_PREFIX_LEN.replace_all(&caps[1], "");
1191 format!("UNIQUE {}", cols)
1192 })
1193 .to_string()
1194 }
1195
1196 fn strip_postgres_casts(&self, stmt: &str) -> String {
1198 use once_cell::sync::Lazy;
1199 use regex::Regex;
1200
1201 static RE_CAST: Lazy<Regex> = Lazy::new(|| {
1203 Regex::new(r"::[a-zA-Z_][a-zA-Z0-9_]*(?:\s+[a-zA-Z_][a-zA-Z0-9_]*)*").unwrap()
1204 });
1205
1206 map_outside_string_literals(stmt, |seg| RE_CAST.replace_all(seg, "").into_owned())
1209 }
1210
1211 fn convert_nextval(&self, stmt: &str) -> String {
1213 use once_cell::sync::Lazy;
1214 use regex::Regex;
1215
1216 static RE_NEXTVAL: Lazy<Regex> =
1219 Lazy::new(|| Regex::new(r"(?i)\s*DEFAULT\s+nextval\s*\([^)]+\)").unwrap());
1220
1221 RE_NEXTVAL.replace_all(stmt, "").to_string()
1222 }
1223
1224 fn convert_default_now(&self, stmt: &str) -> String {
1226 use once_cell::sync::Lazy;
1227 use regex::Regex;
1228
1229 static RE_NOW: Lazy<Regex> =
1230 Lazy::new(|| Regex::new(r"(?i)\bDEFAULT\s+now\s*\(\s*\)").unwrap());
1231
1232 RE_NOW
1233 .replace_all(stmt, "DEFAULT CURRENT_TIMESTAMP")
1234 .to_string()
1235 }
1236
1237 fn strip_schema_prefix(&self, stmt: &str) -> String {
1239 use once_cell::sync::Lazy;
1240 use regex::Regex;
1241
1242 static RE_SCHEMA: Lazy<Regex> =
1245 Lazy::new(|| Regex::new(r#"(?i)\b(public|pg_catalog|pg_temp)\s*\.\s*"#).unwrap());
1246
1247 map_outside_string_literals(stmt, |seg| RE_SCHEMA.replace_all(seg, "").into_owned())
1250 }
1251
1252 fn convert_mssql_getdate(&self, stmt: &str) -> String {
1254 use once_cell::sync::Lazy;
1255 use regex::Regex;
1256
1257 static RE_GETDATE: Lazy<Regex> =
1258 Lazy::new(|| Regex::new(r"(?i)\bGETDATE\s*\(\s*\)").unwrap());
1259 static RE_SYSDATETIME: Lazy<Regex> =
1260 Lazy::new(|| Regex::new(r"(?i)\bSYSDATETIME\s*\(\s*\)").unwrap());
1261 static RE_GETUTCDATE: Lazy<Regex> =
1262 Lazy::new(|| Regex::new(r"(?i)\bGETUTCDATE\s*\(\s*\)").unwrap());
1263
1264 let result = RE_GETDATE
1265 .replace_all(stmt, "CURRENT_TIMESTAMP")
1266 .to_string();
1267 let result = RE_SYSDATETIME
1268 .replace_all(&result, "CURRENT_TIMESTAMP")
1269 .to_string();
1270 RE_GETUTCDATE
1271 .replace_all(&result, "CURRENT_TIMESTAMP")
1272 .to_string()
1273 }
1274
1275 fn strip_mssql_on_filegroup(&self, stmt: &str) -> String {
1277 use once_cell::sync::Lazy;
1278 use regex::Regex;
1279
1280 static RE_ON_FILEGROUP: Lazy<Regex> =
1282 Lazy::new(|| Regex::new(r"(?i)\s+ON\s*\[\s*\w+\s*\]").unwrap());
1283
1284 RE_ON_FILEGROUP.replace_all(stmt, "").to_string()
1285 }
1286
1287 fn strip_mssql_clustered(&self, stmt: &str) -> String {
1289 use once_cell::sync::Lazy;
1290 use regex::Regex;
1291
1292 static RE_CLUSTERED: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bCLUSTERED\s+").unwrap());
1293 static RE_NONCLUSTERED: Lazy<Regex> =
1294 Lazy::new(|| Regex::new(r"(?i)\bNONCLUSTERED\s+").unwrap());
1295
1296 let result = RE_CLUSTERED.replace_all(stmt, "").to_string();
1297 RE_NONCLUSTERED.replace_all(&result, "").to_string()
1298 }
1299
1300 fn convert_mssql_unicode_strings(&self, stmt: &str) -> String {
1306 let bytes = stmt.as_bytes();
1307 let mut out = String::with_capacity(stmt.len());
1308 let mut i = 0;
1309 let mut copied = 0;
1311 while i < bytes.len() {
1312 if bytes[i] == b'\'' {
1313 i = skip_sql_string_literal(bytes, i);
1315 } else if matches!(bytes[i], b'N' | b'n')
1316 && bytes.get(i + 1) == Some(&b'\'')
1317 && (i == 0 || !(bytes[i - 1].is_ascii_alphanumeric() || bytes[i - 1] == b'_'))
1318 {
1319 out.push_str(&stmt[copied..i]);
1322 copied = i + 1;
1323 i += 1;
1324 } else {
1325 i += 1;
1326 }
1327 }
1328 out.push_str(&stmt[copied..]);
1329 out
1330 }
1331
1332 fn strip_mssql_schema_prefix(&self, stmt: &str) -> String {
1334 use once_cell::sync::Lazy;
1335 use regex::Regex;
1336
1337 static RE_MSSQL_SCHEMA: Lazy<Regex> =
1340 Lazy::new(|| Regex::new(r"(?i)\[?dbo\]?\s*\.\s*").unwrap());
1341
1342 map_outside_string_literals(stmt, |seg| {
1345 RE_MSSQL_SCHEMA.replace_all(seg, "").into_owned()
1346 })
1347 }
1348
1349 fn detect_unsupported_features(
1351 &mut self,
1352 stmt: &str,
1353 table_name: Option<&str>,
1354 ) -> Result<(), ConvertWarning> {
1355 let upper = stmt.to_uppercase();
1356
1357 if self.from == SqlDialect::MySql {
1359 if upper.contains("ENUM(") {
1361 let warning = ConvertWarning::UnsupportedFeature {
1362 feature: format!(
1363 "ENUM type{}",
1364 table_name
1365 .map(|t| format!(" in table {}", t))
1366 .unwrap_or_default()
1367 ),
1368 suggestion: Some(
1369 "Converted to VARCHAR - consider adding CHECK constraint".to_string(),
1370 ),
1371 };
1372 self.warnings.add(warning.clone());
1373 if self.strict {
1374 return Err(warning);
1375 }
1376 }
1377
1378 if upper.contains("SET(") {
1380 let warning = ConvertWarning::UnsupportedFeature {
1381 feature: format!(
1382 "SET type{}",
1383 table_name
1384 .map(|t| format!(" in table {}", t))
1385 .unwrap_or_default()
1386 ),
1387 suggestion: Some(
1388 "Converted to VARCHAR - SET semantics not preserved".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("UNSIGNED") {
1399 self.warnings.add(ConvertWarning::UnsupportedFeature {
1400 feature: "UNSIGNED modifier".to_string(),
1401 suggestion: Some(
1402 "Removed - consider adding CHECK constraint for non-negative values"
1403 .to_string(),
1404 ),
1405 });
1406 }
1407 }
1408
1409 if self.from == SqlDialect::Postgres {
1411 if upper.contains("[]") || upper.contains("ARRAY[") {
1413 let warning = ConvertWarning::UnsupportedFeature {
1414 feature: format!(
1415 "Array type{}",
1416 table_name
1417 .map(|t| format!(" in table {}", t))
1418 .unwrap_or_default()
1419 ),
1420 suggestion: Some(
1421 "Array types not supported in target dialect - consider using JSON"
1422 .to_string(),
1423 ),
1424 };
1425 self.warnings.add(warning.clone());
1426 if self.strict {
1427 return Err(warning);
1428 }
1429 }
1430
1431 if upper.contains("INHERITS") {
1433 let warning = ConvertWarning::UnsupportedFeature {
1434 feature: "Table inheritance (INHERITS)".to_string(),
1435 suggestion: Some(
1436 "PostgreSQL table inheritance not supported in target dialect".to_string(),
1437 ),
1438 };
1439 self.warnings.add(warning.clone());
1440 if self.strict {
1441 return Err(warning);
1442 }
1443 }
1444
1445 if upper.contains("PARTITION BY") && self.to == SqlDialect::Sqlite {
1447 let warning = ConvertWarning::UnsupportedFeature {
1448 feature: "Table partitioning".to_string(),
1449 suggestion: Some("Partitioning not supported in SQLite".to_string()),
1450 };
1451 self.warnings.add(warning.clone());
1452 if self.strict {
1453 return Err(warning);
1454 }
1455 }
1456 }
1457
1458 Ok(())
1459 }
1460
1461 pub fn warnings(&self) -> &[ConvertWarning] {
1463 self.warnings.warnings()
1464 }
1465}
1466
1467pub fn run(config: ConvertConfig) -> anyhow::Result<ConvertStats> {
1469 let mut stats = ConvertStats::default();
1470
1471 let from_dialect = if let Some(d) = config.from_dialect {
1473 d
1474 } else {
1475 let result = crate::parser::detect_dialect_from_file(&config.input)?;
1476 if config.progress {
1477 eprintln!(
1478 "Auto-detected source dialect: {} (confidence: {:?})",
1479 result.dialect, result.confidence
1480 );
1481 }
1482 result.dialect
1483 };
1484
1485 if from_dialect == config.to_dialect {
1487 anyhow::bail!(
1488 "Source and target dialects are the same ({}). No conversion needed.",
1489 from_dialect
1490 );
1491 }
1492
1493 let file_size = std::fs::metadata(&config.input)?.len();
1495
1496 let progress_bar = if config.progress {
1497 let pb = ProgressBar::new(file_size);
1498 pb.set_style(
1499 ProgressStyle::with_template(
1500 "{spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] {bytes}/{total_bytes} ({percent}%) {msg}",
1501 )
1502 .unwrap()
1503 .progress_chars("█▓▒░ ")
1504 .tick_chars("⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"),
1505 );
1506 pb.enable_steady_tick(std::time::Duration::from_millis(100));
1507 pb.set_message("Converting...");
1508 Some(pb)
1509 } else {
1510 None
1511 };
1512
1513 let mut converter = Converter::new(from_dialect, config.to_dialect).with_strict(config.strict);
1515
1516 let reader: Box<dyn Read> = if let Some(ref pb) = progress_bar {
1519 let pb_clone = pb.clone();
1520 open_input_with_progress(
1521 &config.input,
1522 Box::new(move |bytes| pb_clone.set_position(bytes)),
1523 )?
1524 } else {
1525 open_input(&config.input)?
1526 };
1527 let mut parser = Parser::with_dialect(reader, 64 * 1024, from_dialect);
1528
1529 let mut writer: Box<dyn Write> = if config.dry_run {
1531 Box::new(std::io::sink())
1532 } else {
1533 match &config.output {
1534 Some(path) => {
1535 if let Some(parent) = path.parent() {
1536 std::fs::create_dir_all(parent)?;
1537 }
1538 Box::new(BufWriter::with_capacity(256 * 1024, File::create(path)?))
1539 }
1540 None => Box::new(BufWriter::new(std::io::stdout())),
1541 }
1542 };
1543
1544 if !config.dry_run {
1546 write_header(&mut writer, &config, from_dialect)?;
1547 }
1548
1549 while let Some(stmt) = parser.read_statement()? {
1551 stats.statements_processed += 1;
1552
1553 if converter.has_pending_copy() {
1555 match converter.process_copy_data(&stmt) {
1557 Ok(inserts) => {
1558 for insert in inserts {
1559 if !insert.is_empty() {
1560 stats.statements_converted += 1;
1561 if !config.dry_run {
1562 writer.write_all(&insert)?;
1563 writer.write_all(b"\n")?;
1564 }
1565 }
1566 }
1567 }
1568 Err(warning) => {
1569 stats.warnings.push(warning);
1570 stats.statements_skipped += 1;
1571 }
1572 }
1573 continue;
1574 }
1575
1576 match converter.convert_statement(&stmt) {
1577 Ok(converted) => {
1578 if converted.is_empty() {
1579 stats.statements_skipped += 1;
1580 } else if converted == stmt {
1581 stats.statements_unchanged += 1;
1582 if !config.dry_run {
1583 writer.write_all(&converted)?;
1584 writer.write_all(b"\n")?;
1585 }
1586 } else {
1587 stats.statements_converted += 1;
1588 if !config.dry_run {
1589 writer.write_all(&converted)?;
1590 writer.write_all(b"\n")?;
1591 }
1592 }
1593 }
1594 Err(warning) => {
1595 stats.warnings.push(warning);
1596 stats.statements_skipped += 1;
1597 }
1598 }
1599 }
1600
1601 stats.warnings.extend(converter.warnings().iter().cloned());
1603
1604 if let Some(pb) = progress_bar {
1605 pb.finish_with_message("done");
1606 }
1607
1608 Ok(stats)
1609}
1610
1611fn write_header(
1613 writer: &mut dyn Write,
1614 config: &ConvertConfig,
1615 from: SqlDialect,
1616) -> std::io::Result<()> {
1617 writeln!(writer, "-- Converted by sql-splitter")?;
1618 writeln!(writer, "-- From: {} → To: {}", from, config.to_dialect)?;
1619 writeln!(writer, "-- Source: {}", config.input.display())?;
1620 writeln!(writer)?;
1621
1622 match config.to_dialect {
1624 SqlDialect::Postgres => {
1625 writeln!(writer, "SET client_encoding = 'UTF8';")?;
1626 writeln!(writer, "SET standard_conforming_strings = on;")?;
1627 }
1628 SqlDialect::Sqlite => {
1629 writeln!(writer, "PRAGMA foreign_keys = OFF;")?;
1630 }
1631 SqlDialect::MySql => {
1632 writeln!(writer, "SET NAMES utf8mb4;")?;
1633 writeln!(writer, "SET FOREIGN_KEY_CHECKS = 0;")?;
1634 }
1635 SqlDialect::Mssql => {
1636 writeln!(writer, "SET ANSI_NULLS ON;")?;
1637 writeln!(writer, "SET QUOTED_IDENTIFIER ON;")?;
1638 writeln!(writer, "SET NOCOUNT ON;")?;
1639 }
1640 }
1641 writeln!(writer)?;
1642
1643 Ok(())
1644}
1645
1646fn skip_sql_string_literal(bytes: &[u8], start: usize) -> usize {
1651 let mut i = start + 1;
1652 while i < bytes.len() {
1653 if bytes[i] == b'\'' {
1654 if bytes.get(i + 1) == Some(&b'\'') {
1655 i += 2; } else {
1657 return i + 1; }
1659 } else {
1660 i += 1;
1661 }
1662 }
1663 i
1664}
1665
1666fn map_outside_string_literals(stmt: &str, f: impl Fn(&str) -> String) -> String {
1670 let bytes = stmt.as_bytes();
1671 let mut out = String::with_capacity(stmt.len());
1672 let mut i = 0;
1673 let mut seg_start = 0;
1674 while i < bytes.len() {
1675 if bytes[i] == b'\'' {
1676 out.push_str(&f(&stmt[seg_start..i]));
1678 let lit_end = skip_sql_string_literal(bytes, i);
1679 out.push_str(&stmt[i..lit_end]); i = lit_end;
1681 seg_start = i;
1682 } else {
1683 i += 1;
1684 }
1685 }
1686 out.push_str(&f(&stmt[seg_start..]));
1687 out
1688}