Skip to main content

sql_splitter/convert/
mod.rs

1//! Convert command for translating SQL dumps between dialects.
2//!
3//! Supports conversion between MySQL, PostgreSQL, and SQLite dialects with:
4//! - Identifier quoting conversion (backticks ↔ double quotes)
5//! - String escape normalization (\' ↔ '')
6//! - Data type mapping (AUTO_INCREMENT ↔ SERIAL ↔ INTEGER PRIMARY KEY)
7//! - COPY FROM stdin → INSERT conversion
8//! - Session header conversion
9//! - Warning system for unsupported features
10
11pub 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// Only `render::ddl` (lib-only; see the `copy_to_insert` re-export above for
29// the same bin/lib split) calls this, so the `bin` target's parallel module
30// tree sees it as unused.
31#[allow(unused_imports)]
32pub(crate) use types::map_column_type;
33pub use warnings::{print_warnings_summary, ConvertWarning, WarningCollector};
34
35/// Configuration for the convert command
36#[derive(Debug)]
37pub struct ConvertConfig {
38    /// Input SQL file
39    pub input: PathBuf,
40    /// Output SQL file (None for stdout)
41    pub output: Option<PathBuf>,
42    /// Source dialect (auto-detected if None)
43    pub from_dialect: Option<SqlDialect>,
44    /// Target dialect
45    pub to_dialect: SqlDialect,
46    /// Dry run mode
47    pub dry_run: bool,
48    /// Show progress
49    pub progress: bool,
50    /// Strict mode (fail on any unsupported feature)
51    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/// Statistics from convert operation
69#[derive(Debug, Default, serde::Serialize)]
70pub struct ConvertStats {
71    /// Total statements processed
72    pub statements_processed: u64,
73    /// Statements converted
74    pub statements_converted: u64,
75    /// Statements passed through unchanged
76    pub statements_unchanged: u64,
77    /// Statements skipped (unsupported)
78    pub statements_skipped: u64,
79    /// Warnings generated
80    pub warnings: Vec<ConvertWarning>,
81}
82
83/// Main converter that dispatches to specific dialect converters
84pub struct Converter {
85    from: SqlDialect,
86    to: SqlDialect,
87    warnings: WarningCollector,
88    strict: bool,
89    /// Pending COPY header for data block processing
90    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    /// Check if we have a pending COPY header (waiting for data block)
110    pub fn has_pending_copy(&self) -> bool {
111        self.pending_copy_header.is_some()
112    }
113
114    /// Process a COPY data block using the pending header
115    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                // Convert COPY data to INSERT statements
119                let inserts = copy_to_inserts(&header, data, self.to);
120                return Ok(inserts);
121            }
122        }
123        // Pass through if same dialect or no pending header
124        Ok(vec![data.to_vec()])
125    }
126
127    /// Convert a single statement
128    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    /// Convert CREATE TABLE statement
150    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        // Detect unsupported features BEFORE conversion (so we see original types)
159        self.detect_unsupported_features(&result, table_name)?;
160
161        // Convert MSSQL-specific syntax BEFORE identifier conversion
162        // (so we can strip [dbo]. schema prefix properly)
163        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        // Convert identifier quoting
172        result = self.convert_identifiers(&result);
173
174        // Convert data types
175        result = self.convert_data_types(&result);
176
177        // Convert AUTO_INCREMENT
178        result = self.convert_auto_increment(&result, table_name);
179
180        // Convert PostgreSQL-specific syntax
181        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        // Convert string escapes
189        result = self.convert_string_escapes(&result);
190
191        // Strip MySQL conditional comments
192        result = self.strip_conditional_comments(&result);
193
194        // Convert ENGINE clause
195        result = self.strip_engine_clause(&result);
196
197        // Convert CHARSET/COLLATE
198        result = self.strip_charset_clauses(&result);
199
200        // Strip MySQL inline column/table COMMENT annotations
201        result = self.strip_mysql_comment_clauses(&result);
202
203        // Convert UNIQUE KEY ... USING BTREE table constraints
204        result = self.convert_unique_key_constraint(&result);
205
206        Ok(result.into_bytes())
207    }
208
209    /// Convert INSERT statement
210    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        // Convert MSSQL-specific syntax BEFORE identifier conversion
219        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        // Convert identifier quoting
225        result = self.convert_identifiers(&result);
226
227        // Convert PostgreSQL-specific syntax
228        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        // Convert string escapes (careful with data!)
234        result = self.convert_string_escapes(&result);
235
236        Ok(result.into_bytes())
237    }
238
239    /// Convert CREATE INDEX statement
240    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        // Convert MSSQL-specific syntax BEFORE identifier conversion
245        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        // Convert identifier quoting
251        result = self.convert_identifiers(&result);
252
253        // Convert PostgreSQL-specific syntax
254        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        // Detect FULLTEXT/SPATIAL
260        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    /// Convert ALTER TABLE statement
277    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        // Convert PostgreSQL-specific syntax
285        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    /// Convert DROP TABLE statement
296    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        // Strip PostgreSQL schema prefix
303        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    /// Convert COPY statement (PostgreSQL-specific)
311    ///
312    /// This handles the COPY header. The data block is processed separately
313    /// via process_copy_data() when called from the run() function.
314    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        // Check if this contains "FROM stdin" (COPY header) or is data
322        let upper = stmt_str.to_uppercase();
323        if upper.contains("FROM STDIN") {
324            // This is a COPY header - parse it and store for later
325            if let Some(header) = parse_copy_header(&stmt_str) {
326                if self.from == SqlDialect::Postgres && self.to != SqlDialect::Postgres {
327                    // Store the header, will convert data block in process_copy_data
328                    self.pending_copy_header = Some(header);
329                    // Return empty - the actual INSERT will be generated from data
330                    return Ok(Vec::new());
331                }
332            }
333        }
334
335        // If same dialect or couldn't parse, pass through
336        Ok(stmt.to_vec())
337    }
338
339    /// Convert other statements (comments, session settings, etc.)
340    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        // Skip MySQL session commands when converting to other dialects
346        if self.from == SqlDialect::MySql
347            && self.to != SqlDialect::MySql
348            && self.is_mysql_session_command(&result)
349        {
350            return Ok(Vec::new()); // Skip
351        }
352
353        // Skip PostgreSQL session commands and unsupported features when converting to other dialects
354        if self.from == SqlDialect::Postgres
355            && self.to != SqlDialect::Postgres
356            && self.is_postgres_session_command(&result)
357        {
358            return Ok(Vec::new()); // Skip
359        }
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()); // Skip
369        }
370
371        // Skip SQLite pragmas when converting to other dialects
372        if self.from == SqlDialect::Sqlite
373            && self.to != SqlDialect::Sqlite
374            && self.is_sqlite_pragma(&result)
375        {
376            return Ok(Vec::new()); // Skip
377        }
378
379        // Skip MSSQL session commands when converting to other dialects
380        if self.from == SqlDialect::Mssql
381            && self.to != SqlDialect::Mssql
382            && self.is_mssql_session_command(&result)
383        {
384            return Ok(Vec::new()); // Skip
385        }
386
387        // Strip conditional comments
388        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    /// Check if statement is a MySQL session command
397    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    /// Check if statement is a PostgreSQL session command or unsupported statement
409    fn is_postgres_session_command(&self, stmt: &str) -> bool {
410        let upper = stmt.to_uppercase();
411        // Session/transaction settings
412        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            // Ownership/permission statements
426            || upper.contains("OWNER TO")
427            || upper.contains("GRANT ")
428            || upper.contains("REVOKE ")
429    }
430
431    /// Check if statement is a PostgreSQL-only feature that should be skipped
432    fn is_postgres_only_feature(&self, stmt: &str) -> bool {
433        // Strip leading comments to find the actual statement
434        let stripped = self.strip_leading_sql_comments(stmt);
435        let upper = stripped.to_uppercase();
436
437        // These PostgreSQL features have no MySQL/SQLite equivalent
438        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    /// Strip leading SQL comments (-- and /* */) from a string
457    fn strip_leading_sql_comments(&self, stmt: &str) -> String {
458        let mut result = stmt.trim();
459        loop {
460            // Strip -- comments
461            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            // Strip /* */ comments
470            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    /// Check if statement is a SQLite pragma
484    fn is_sqlite_pragma(&self, stmt: &str) -> bool {
485        let upper = stmt.to_uppercase();
486        upper.contains("PRAGMA")
487    }
488
489    /// Check if statement is an MSSQL session command
490    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    /// Convert identifier quoting based on dialects
505    fn convert_identifiers(&self, stmt: &str) -> String {
506        match (self.from, self.to) {
507            (SqlDialect::MySql, SqlDialect::Postgres | SqlDialect::Sqlite) => {
508                // Backticks → double quotes
509                self.backticks_to_double_quotes(stmt)
510            }
511            (SqlDialect::MySql, SqlDialect::Mssql) => {
512                // Backticks → square brackets
513                self.backticks_to_square_brackets(stmt)
514            }
515            (SqlDialect::Postgres | SqlDialect::Sqlite, SqlDialect::MySql) => {
516                // Double quotes → backticks
517                self.double_quotes_to_backticks(stmt)
518            }
519            (SqlDialect::Postgres | SqlDialect::Sqlite, SqlDialect::Mssql) => {
520                // Double quotes → square brackets
521                self.double_quotes_to_square_brackets(stmt)
522            }
523            (SqlDialect::Mssql, SqlDialect::MySql) => {
524                // Square brackets → backticks
525                self.square_brackets_to_backticks(stmt)
526            }
527            (SqlDialect::Mssql, SqlDialect::Postgres | SqlDialect::Sqlite) => {
528                // Square brackets → double quotes
529                self.square_brackets_to_double_quotes(stmt)
530            }
531            _ => stmt.to_string(),
532        }
533    }
534
535    /// Convert backticks to double quotes
536    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    /// Convert double quotes to backticks
556    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    /// Convert backticks to square brackets (for MSSQL)
577    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    /// Convert double quotes to square brackets (for MSSQL)
601    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    /// Convert square brackets to backticks (from MSSQL to MySQL)
625    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    /// Convert square brackets to double quotes (from MSSQL to PostgreSQL/SQLite)
643    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    /// Convert data types between dialects
661    fn convert_data_types(&self, stmt: &str) -> String {
662        TypeMapper::convert(stmt, self.from, self.to)
663    }
664
665    /// Convert AUTO_INCREMENT/SERIAL syntax
666    fn convert_auto_increment(&self, stmt: &str, _table_name: Option<&str>) -> String {
667        // Strip the MySQL table-level `AUTO_INCREMENT=N` option first (distinct from
668        // the column-level `AUTO_INCREMENT` keyword handled below). Otherwise the
669        // column-level replacements below strip the word "AUTO_INCREMENT" and leave
670        // a dangling "=N" behind, e.g. `) ENGINE=InnoDB AUTO_INCREMENT=2 ...` becomes
671        // `) =2 ...`. See https://github.com/HelgeSverre/sql-splitter/issues/64
672        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                // INT AUTO_INCREMENT → SERIAL, BIGINT AUTO_INCREMENT → BIGSERIAL,
682                // case-insensitive (MySQL dumps commonly use lowercase
683                // `auto_increment`) and string-literal-aware (a DEFAULT value or
684                // CHECK expression containing the literal text "AUTO_INCREMENT"
685                // must not be touched).
686                self.convert_mysql_auto_increment_keyword(stmt)
687            }
688            (SqlDialect::MySql, SqlDialect::Sqlite) => {
689                use once_cell::sync::Lazy;
690                use regex::Regex;
691                // `<int type> AUTO_INCREMENT` → INTEGER, then any bare keyword
692                // dropped. Case-insensitive (MySQL dumps commonly lowercase
693                // `auto_increment`) and only outside string literals so a
694                // DEFAULT / value containing the text is left alone. Matching
695                // the whole `…INT AUTO_INCREMENT` unit avoids the "BIGINTEGER"
696                // substring hazard.
697                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                // Trailing boundary only: the integer type may already have been
701                // mapped and glued to the keyword (e.g. `INTEGERAUTO_INCREMENT`)
702                // by convert_data_types running first.
703                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                // SERIAL → INT AUTO_INCREMENT
712                // BIGSERIAL → BIGINT AUTO_INCREMENT
713                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                // SERIAL → INTEGER (SQLite auto-increments INTEGER PRIMARY KEY)
722                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                // SQLite uses INTEGER PRIMARY KEY for auto-increment
731                // We can't easily detect this pattern, so just pass through
732                stmt.to_string()
733            }
734            (SqlDialect::Sqlite, SqlDialect::Postgres) => {
735                // SQLite uses INTEGER PRIMARY KEY for auto-increment
736                // We can't easily detect this pattern, so just pass through
737                stmt.to_string()
738            }
739            // MSSQL conversions
740            (SqlDialect::MySql, SqlDialect::Mssql) => {
741                use once_cell::sync::Lazy;
742                use regex::Regex;
743                // AUTO_INCREMENT → IDENTITY(1,1), keeping the integer type.
744                // Case-insensitive and only outside string literals. BIGINT is
745                // handled before the bare INT rule; `\bINT` won't match the
746                // `INT` inside `BIGINT`.
747                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                // Trailing boundary only (the type may already be glued to the
752                // keyword by an earlier type mapping).
753                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                // IDENTITY(1,1) → AUTO_INCREMENT
763                self.convert_identity_to_auto_increment(stmt)
764            }
765            (SqlDialect::Postgres, SqlDialect::Mssql) => {
766                // SERIAL → INT IDENTITY(1,1) (handled by type mapper)
767                stmt.to_string()
768            }
769            (SqlDialect::Mssql, SqlDialect::Postgres) => {
770                // IDENTITY(1,1) → SERIAL (need to add SERIAL instead)
771                self.convert_identity_to_serial(stmt)
772            }
773            (SqlDialect::Sqlite, SqlDialect::Mssql) => {
774                // SQLite → MSSQL: pass through
775                stmt.to_string()
776            }
777            (SqlDialect::Mssql, SqlDialect::Sqlite) => {
778                // IDENTITY → strip (SQLite uses INTEGER PRIMARY KEY)
779                self.strip_identity(stmt)
780            }
781            _ => stmt.to_string(),
782        }
783    }
784
785    /// Convert MSSQL IDENTITY to MySQL AUTO_INCREMENT
786    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    /// Convert MSSQL IDENTITY to PostgreSQL SERIAL
797    fn convert_identity_to_serial(&self, stmt: &str) -> String {
798        use once_cell::sync::Lazy;
799        use regex::Regex;
800
801        // Match INT IDENTITY(1,1) and replace with SERIAL
802        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    /// Strip MSSQL IDENTITY clause for SQLite
820    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    /// Convert string escape sequences
831    fn convert_string_escapes(&self, stmt: &str) -> String {
832        match (self.from, self.to) {
833            // MySQL uses backslash escapes; PostgreSQL (standard strings),
834            // SQLite and MSSQL all treat backslash as a literal byte and escape
835            // a quote by doubling it, so the same decode applies to all three.
836            (SqlDialect::MySql, SqlDialect::Postgres | SqlDialect::Sqlite | SqlDialect::Mssql) => {
837                self.mysql_escapes_to_standard(stmt)
838            }
839            _ => stmt.to_string(),
840        }
841    }
842
843    /// Convert MySQL backslash escapes to standard SQL double-quote escapes
844    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                // Decode the MySQL escape to the byte it represents. The target
855                // dialects (Postgres standard strings, SQLite, MSSQL) treat
856                // backslash as a literal, so a passed-through `\\` or `\n` would
857                // be read as two literal characters and corrupt the data.
858                match chars.next() {
859                    Some(next) => match next {
860                        // Quote becomes a doubled '' (standard SQL escaping).
861                        '\'' => result.push_str("''"),
862                        '"' => result.push('"'),
863                        // One literal backslash.
864                        '\\' => 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                        // MySQL keeps the backslash for the LIKE metacharacters.
872                        '%' => result.push_str("\\%"),
873                        '_' => result.push_str("\\_"),
874                        // Any other escaped char is the char itself.
875                        other => result.push(other),
876                    },
877                    // Trailing backslash at end of input.
878                    None => result.push('\\'),
879                }
880            } else {
881                result.push(c);
882            }
883        }
884        result
885    }
886
887    /// Strip MySQL conditional comments /*!40101 ... */
888    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(); // consume *
895                if chars.peek() == Some(&'!') {
896                    // Skip conditional comment
897                    chars.next(); // consume !
898                                  // Skip version number
899                    while chars.peek().map(|c| c.is_ascii_digit()).unwrap_or(false) {
900                        chars.next();
901                    }
902                    // Skip content until */
903                    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                    // Regular comment, keep it
920                    result.push('/');
921                    result.push('*');
922                }
923            } else {
924                result.push(c);
925            }
926        }
927        result
928    }
929
930    /// Strip ENGINE clause
931    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        // Remove ENGINE=InnoDB, ENGINE=MyISAM, etc.
940        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    /// Strip CHARSET/COLLATE clauses
946    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    /// Case-insensitively checks whether `keyword` starts at `chars[pos]`, with
964    /// word boundaries on both sides (so e.g. "COMMENT" doesn't match inside
965    /// "COMMENTARY" or a preceding identifier char like "XCOMMENT"). Returns the
966    /// index just past the keyword on success.
967    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    /// Removes trailing whitespace already pushed into `result`, so that stripping
987    /// a clause also absorbs the whitespace that preceded it (matching the old
988    /// `\s*<keyword>...` regex behavior).
989    fn trim_trailing_whitespace(result: &mut String) {
990        while result.ends_with(|c: char| c.is_whitespace()) {
991            result.pop();
992        }
993    }
994
995    /// Strip MySQL table-level `AUTO_INCREMENT=N` option. String-literal-aware so
996    /// that a DEFAULT value or other string content containing the literal text
997    /// "AUTO_INCREMENT=N" is left untouched.
998    /// See https://github.com/HelgeSverre/sql-splitter/issues/64
999    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    /// Strip MySQL column/table `COMMENT 'text'` (or `COMMENT='text'`) annotations.
1044    /// Neither is valid inside a PostgreSQL column definition or as a CREATE TABLE
1045    /// table option, so they are removed entirely rather than translated.
1046    /// String-literal-aware: only matches a real `COMMENT` clause, never the word
1047    /// "comment" sitting inside an unrelated DEFAULT value or CHECK expression.
1048    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                        // Consume the quoted comment text itself, honoring ''
1081                        // as an escaped quote, then drop the whole clause.
1082                        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    /// Convert MySQL's column-level `AUTO_INCREMENT` keyword to PostgreSQL's
1110    /// `SERIAL`/`BIGSERIAL`, case-insensitively and string-literal-aware (a
1111    /// DEFAULT value or CHECK expression containing the literal text
1112    /// "AUTO_INCREMENT" must not be touched — see finding in issue #64 follow-up
1113    /// review).
1114    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                    // Clean up any remaining standalone occurrence (e.g. when
1154                    // other modifiers like NOT NULL sit between the type and
1155                    // the keyword).
1156                    i = end;
1157                    continue;
1158                }
1159            }
1160            result.push(c);
1161            i += 1;
1162        }
1163        result
1164    }
1165
1166    /// Convert MySQL `UNIQUE KEY [name] (cols) [USING BTREE|HASH]` table constraint
1167    /// to standard `UNIQUE (cols)`, which is the closest PostgreSQL equivalent.
1168    /// Also strips MySQL prefix-length index annotations (e.g. `email(191)`),
1169    /// which have no PostgreSQL equivalent and aren't valid there.
1170    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        // The column-list group allows one level of nested `(digits)` prefix-length
1179        // annotations (e.g. `("email"(191),"other")`), which are common in
1180        // real-world MySQL dumps using utf8mb4 prefix indexes.
1181        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    /// Strip PostgreSQL type casts (::type and ::regclass)
1197    fn strip_postgres_casts(&self, stmt: &str) -> String {
1198        use once_cell::sync::Lazy;
1199        use regex::Regex;
1200
1201        // Match ::regclass, ::text, ::integer, etc. (including complex types like character varying)
1202        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        // Only outside string literals: a value like '2001:db8::1' or
1207        // 'a::b text' must keep its ':: …' rather than have it stripped.
1208        map_outside_string_literals(stmt, |seg| RE_CAST.replace_all(seg, "").into_owned())
1209    }
1210
1211    /// Convert nextval('sequence') to NULL or remove (AUTO_INCREMENT handles it)
1212    fn convert_nextval(&self, stmt: &str) -> String {
1213        use once_cell::sync::Lazy;
1214        use regex::Regex;
1215
1216        // Match nextval('sequence_name'::regclass) or nextval('sequence_name')
1217        // Remove the DEFAULT nextval(...) entirely - AUTO_INCREMENT is already applied
1218        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    /// Convert DEFAULT now() to DEFAULT CURRENT_TIMESTAMP
1225    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    /// Strip schema prefix from table names (e.g., public.users -> users)
1238    fn strip_schema_prefix(&self, stmt: &str) -> String {
1239        use once_cell::sync::Lazy;
1240        use regex::Regex;
1241
1242        // Match schema.table patterns (with optional quotes)
1243        // Handle: public.table, "public"."table", public."table"
1244        static RE_SCHEMA: Lazy<Regex> =
1245            Lazy::new(|| Regex::new(r#"(?i)\b(public|pg_catalog|pg_temp)\s*\.\s*"#).unwrap());
1246
1247        // Only outside string literals so a value like 'see public.docs' keeps
1248        // its text.
1249        map_outside_string_literals(stmt, |seg| RE_SCHEMA.replace_all(seg, "").into_owned())
1250    }
1251
1252    /// Convert MSSQL GETDATE() to CURRENT_TIMESTAMP
1253    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    /// Strip MSSQL ON [filegroup] clause
1276    fn strip_mssql_on_filegroup(&self, stmt: &str) -> String {
1277        use once_cell::sync::Lazy;
1278        use regex::Regex;
1279
1280        // Match ON [PRIMARY] or ON [filegroup_name]
1281        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    /// Strip MSSQL CLUSTERED/NONCLUSTERED keywords
1288    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    /// Convert MSSQL `N'unicode'` string literals to regular `'unicode'`
1301    /// strings by dropping the `N` prefix. Only a genuine prefix — an `N`
1302    /// immediately before a string-opening quote and not itself inside a string
1303    /// — is converted, so an `N'` sequence appearing inside string data (e.g.
1304    /// `'season N''4'`) is left untouched.
1305    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        // Everything in `stmt[..copied]` has already been emitted to `out`.
1310        let mut copied = 0;
1311        while i < bytes.len() {
1312            if bytes[i] == b'\'' {
1313                // A string literal: skip it whole so its contents are preserved.
1314                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                // A genuine `N'` string prefix: emit up to it, drop the `N`, and
1320                // resume at the opening quote (copied to the literal-skip path).
1321                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    /// Strip MSSQL schema prefix (dbo., etc.) from table names
1333    fn strip_mssql_schema_prefix(&self, stmt: &str) -> String {
1334        use once_cell::sync::Lazy;
1335        use regex::Regex;
1336
1337        // Match [dbo].[table] or dbo.table and keep just [table] or table
1338        // We replace schema.table with just table, handling both bracketed and unbracketed forms
1339        static RE_MSSQL_SCHEMA: Lazy<Regex> =
1340            Lazy::new(|| Regex::new(r"(?i)\[?dbo\]?\s*\.\s*").unwrap());
1341
1342        // Only outside string literals so a value like 'user dbo.smith' keeps
1343        // its text.
1344        map_outside_string_literals(stmt, |seg| {
1345            RE_MSSQL_SCHEMA.replace_all(seg, "").into_owned()
1346        })
1347    }
1348
1349    /// Detect unsupported features and add warnings
1350    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        // MySQL-specific features
1358        if self.from == SqlDialect::MySql {
1359            // ENUM types
1360            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            // SET types (MySQL)
1379            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            // UNSIGNED
1398            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        // PostgreSQL-specific features
1410        if self.from == SqlDialect::Postgres {
1411            // Array types
1412            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            // INHERITS
1432            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            // PARTITION BY
1446            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    /// Get collected warnings
1462    pub fn warnings(&self) -> &[ConvertWarning] {
1463        self.warnings.warnings()
1464    }
1465}
1466
1467/// Run the convert command
1468pub fn run(config: ConvertConfig) -> anyhow::Result<ConvertStats> {
1469    let mut stats = ConvertStats::default();
1470
1471    // Detect or use specified source dialect
1472    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    // Check for same dialect
1486    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    // Get file size for progress tracking
1494    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    // Create converter
1514    let mut converter = Converter::new(from_dialect, config.to_dialect).with_strict(config.strict);
1515
1516    // Open input, transparently handling any supported compression format
1517    // (including zip archives), with optional progress tracking.
1518    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    // Open output
1530    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    // Write header
1545    if !config.dry_run {
1546        write_header(&mut writer, &config, from_dialect)?;
1547    }
1548
1549    // Process statements
1550    while let Some(stmt) = parser.read_statement()? {
1551        stats.statements_processed += 1;
1552
1553        // Check if this is a COPY data block (follows a COPY header)
1554        if converter.has_pending_copy() {
1555            // This is a data block, convert it to INSERT statements
1556            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    // Collect warnings
1602    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
1611/// Write output header
1612fn 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    // Write dialect-specific header
1623    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
1646/// Advance past a single-quoted SQL string literal starting at `start` (the
1647/// opening quote), returning the index just past the closing quote. A doubled
1648/// `''` is an escaped quote that keeps the string open. An unterminated literal
1649/// consumes to the end. `bytes[start]` must be `'`.
1650fn 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; // escaped quote, stay inside the string
1656            } else {
1657                return i + 1; // closing quote
1658            }
1659        } else {
1660            i += 1;
1661        }
1662    }
1663    i
1664}
1665
1666/// Apply `f` to every span of `stmt` that lies outside a single-quoted string
1667/// literal, copying the literals through verbatim. Used to keep statement-level
1668/// rewrites (cast/schema-prefix stripping) from mangling string *data*.
1669fn 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            // Flush the preceding non-string span through `f`.
1677            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]); // literal, verbatim
1680            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}