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                // INT AUTO_INCREMENT PRIMARY KEY → INTEGER PRIMARY KEY
690                // The AUTOINCREMENT keyword is optional in SQLite.
691                // Sized variants (BIGINT/MEDIUMINT/SMALLINT/TINYINT) must be
692                // handled before the bare INT replacement — otherwise the
693                // substring match inside e.g. "BIGINT" produces "BIGINTEGER".
694                let mut result = stmt.to_string();
695                for sized in [
696                    "BIGINT AUTO_INCREMENT",
697                    "bigint AUTO_INCREMENT",
698                    "MEDIUMINT AUTO_INCREMENT",
699                    "mediumint AUTO_INCREMENT",
700                    "SMALLINT AUTO_INCREMENT",
701                    "smallint AUTO_INCREMENT",
702                    "TINYINT AUTO_INCREMENT",
703                    "tinyint AUTO_INCREMENT",
704                ] {
705                    result = result.replace(sized, "INTEGER");
706                }
707                let result = result.replace("INT AUTO_INCREMENT", "INTEGER");
708                let result = result.replace("int AUTO_INCREMENT", "INTEGER");
709                result.replace("AUTO_INCREMENT", "")
710            }
711            (SqlDialect::Postgres, SqlDialect::MySql) => {
712                // SERIAL → INT AUTO_INCREMENT
713                // BIGSERIAL → BIGINT AUTO_INCREMENT
714                let result = stmt.replace("BIGSERIAL", "BIGINT AUTO_INCREMENT");
715                let result = result.replace("bigserial", "BIGINT AUTO_INCREMENT");
716                let result = result.replace("SMALLSERIAL", "SMALLINT AUTO_INCREMENT");
717                let result = result.replace("smallserial", "SMALLINT AUTO_INCREMENT");
718                let result = result.replace("SERIAL", "INT AUTO_INCREMENT");
719                result.replace("serial", "INT AUTO_INCREMENT")
720            }
721            (SqlDialect::Postgres, SqlDialect::Sqlite) => {
722                // SERIAL → INTEGER (SQLite auto-increments INTEGER PRIMARY KEY)
723                let result = stmt.replace("BIGSERIAL", "INTEGER");
724                let result = result.replace("bigserial", "INTEGER");
725                let result = result.replace("SMALLSERIAL", "INTEGER");
726                let result = result.replace("smallserial", "INTEGER");
727                let result = result.replace("SERIAL", "INTEGER");
728                result.replace("serial", "INTEGER")
729            }
730            (SqlDialect::Sqlite, SqlDialect::MySql) => {
731                // SQLite uses INTEGER PRIMARY KEY for auto-increment
732                // We can't easily detect this pattern, so just pass through
733                stmt.to_string()
734            }
735            (SqlDialect::Sqlite, SqlDialect::Postgres) => {
736                // SQLite uses INTEGER PRIMARY KEY for auto-increment
737                // We can't easily detect this pattern, so just pass through
738                stmt.to_string()
739            }
740            // MSSQL conversions
741            (SqlDialect::MySql, SqlDialect::Mssql) => {
742                // AUTO_INCREMENT → IDENTITY(1,1)
743                let result = stmt.replace("BIGINT AUTO_INCREMENT", "BIGINT IDENTITY(1,1)");
744                let result = result.replace("bigint AUTO_INCREMENT", "BIGINT IDENTITY(1,1)");
745                let result = result.replace("INT AUTO_INCREMENT", "INT IDENTITY(1,1)");
746                let result = result.replace("int AUTO_INCREMENT", "INT IDENTITY(1,1)");
747                result.replace("AUTO_INCREMENT", "IDENTITY(1,1)")
748            }
749            (SqlDialect::Mssql, SqlDialect::MySql) => {
750                // IDENTITY(1,1) → AUTO_INCREMENT
751                self.convert_identity_to_auto_increment(stmt)
752            }
753            (SqlDialect::Postgres, SqlDialect::Mssql) => {
754                // SERIAL → INT IDENTITY(1,1) (handled by type mapper)
755                stmt.to_string()
756            }
757            (SqlDialect::Mssql, SqlDialect::Postgres) => {
758                // IDENTITY(1,1) → SERIAL (need to add SERIAL instead)
759                self.convert_identity_to_serial(stmt)
760            }
761            (SqlDialect::Sqlite, SqlDialect::Mssql) => {
762                // SQLite → MSSQL: pass through
763                stmt.to_string()
764            }
765            (SqlDialect::Mssql, SqlDialect::Sqlite) => {
766                // IDENTITY → strip (SQLite uses INTEGER PRIMARY KEY)
767                self.strip_identity(stmt)
768            }
769            _ => stmt.to_string(),
770        }
771    }
772
773    /// Convert MSSQL IDENTITY to MySQL AUTO_INCREMENT
774    fn convert_identity_to_auto_increment(&self, stmt: &str) -> String {
775        use once_cell::sync::Lazy;
776        use regex::Regex;
777
778        static RE_IDENTITY: Lazy<Regex> =
779            Lazy::new(|| Regex::new(r"(?i)\bIDENTITY\s*\(\s*\d+\s*,\s*\d+\s*\)").unwrap());
780
781        RE_IDENTITY.replace_all(stmt, "AUTO_INCREMENT").to_string()
782    }
783
784    /// Convert MSSQL IDENTITY to PostgreSQL SERIAL
785    fn convert_identity_to_serial(&self, stmt: &str) -> String {
786        use once_cell::sync::Lazy;
787        use regex::Regex;
788
789        // Match INT IDENTITY(1,1) and replace with SERIAL
790        static RE_BIGINT_IDENTITY: Lazy<Regex> =
791            Lazy::new(|| Regex::new(r"(?i)\bBIGINT\s+IDENTITY\s*\(\s*\d+\s*,\s*\d+\s*\)").unwrap());
792        static RE_INT_IDENTITY: Lazy<Regex> =
793            Lazy::new(|| Regex::new(r"(?i)\bINT\s+IDENTITY\s*\(\s*\d+\s*,\s*\d+\s*\)").unwrap());
794        static RE_SMALLINT_IDENTITY: Lazy<Regex> = Lazy::new(|| {
795            Regex::new(r"(?i)\bSMALLINT\s+IDENTITY\s*\(\s*\d+\s*,\s*\d+\s*\)").unwrap()
796        });
797
798        let result = RE_BIGINT_IDENTITY
799            .replace_all(stmt, "BIGSERIAL")
800            .to_string();
801        let result = RE_INT_IDENTITY.replace_all(&result, "SERIAL").to_string();
802        RE_SMALLINT_IDENTITY
803            .replace_all(&result, "SMALLSERIAL")
804            .to_string()
805    }
806
807    /// Strip MSSQL IDENTITY clause for SQLite
808    fn strip_identity(&self, stmt: &str) -> String {
809        use once_cell::sync::Lazy;
810        use regex::Regex;
811
812        static RE_IDENTITY: Lazy<Regex> =
813            Lazy::new(|| Regex::new(r"(?i)\s*IDENTITY\s*\(\s*\d+\s*,\s*\d+\s*\)").unwrap());
814
815        RE_IDENTITY.replace_all(stmt, "").to_string()
816    }
817
818    /// Convert string escape sequences
819    fn convert_string_escapes(&self, stmt: &str) -> String {
820        match (self.from, self.to) {
821            (SqlDialect::MySql, SqlDialect::Postgres | SqlDialect::Sqlite) => {
822                // MySQL uses \' for escaping, PostgreSQL/SQLite use ''
823                self.mysql_escapes_to_standard(stmt)
824            }
825            _ => stmt.to_string(),
826        }
827    }
828
829    /// Convert MySQL backslash escapes to standard SQL double-quote escapes
830    fn mysql_escapes_to_standard(&self, stmt: &str) -> String {
831        let mut result = String::with_capacity(stmt.len());
832        let mut chars = stmt.chars().peekable();
833        let mut in_string = false;
834
835        while let Some(c) = chars.next() {
836            if c == '\'' {
837                in_string = !in_string;
838                result.push(c);
839            } else if c == '\\' && in_string {
840                // Check next character
841                if let Some(&next) = chars.peek() {
842                    match next {
843                        '\'' => {
844                            // \' → ''
845                            chars.next();
846                            result.push_str("''");
847                        }
848                        '\\' => {
849                            // \\ → keep as-is for data integrity
850                            chars.next();
851                            result.push_str("\\\\");
852                        }
853                        'n' | 'r' | 't' | '0' => {
854                            // Keep common escapes as-is
855                            result.push(c);
856                        }
857                        _ => {
858                            result.push(c);
859                        }
860                    }
861                } else {
862                    result.push(c);
863                }
864            } else {
865                result.push(c);
866            }
867        }
868        result
869    }
870
871    /// Strip MySQL conditional comments /*!40101 ... */
872    fn strip_conditional_comments(&self, stmt: &str) -> String {
873        let mut result = String::with_capacity(stmt.len());
874        let mut chars = stmt.chars().peekable();
875
876        while let Some(c) = chars.next() {
877            if c == '/' && chars.peek() == Some(&'*') {
878                chars.next(); // consume *
879                if chars.peek() == Some(&'!') {
880                    // Skip conditional comment
881                    chars.next(); // consume !
882                                  // Skip version number
883                    while chars.peek().map(|c| c.is_ascii_digit()).unwrap_or(false) {
884                        chars.next();
885                    }
886                    // Skip content until */
887                    let mut depth = 1;
888                    while depth > 0 {
889                        match chars.next() {
890                            Some('*') if chars.peek() == Some(&'/') => {
891                                chars.next();
892                                depth -= 1;
893                            }
894                            Some('/') if chars.peek() == Some(&'*') => {
895                                chars.next();
896                                depth += 1;
897                            }
898                            None => break,
899                            _ => {}
900                        }
901                    }
902                } else {
903                    // Regular comment, keep it
904                    result.push('/');
905                    result.push('*');
906                }
907            } else {
908                result.push(c);
909            }
910        }
911        result
912    }
913
914    /// Strip ENGINE clause
915    fn strip_engine_clause(&self, stmt: &str) -> String {
916        use once_cell::sync::Lazy;
917        use regex::Regex;
918
919        if self.to == SqlDialect::MySql {
920            return stmt.to_string();
921        }
922
923        // Remove ENGINE=InnoDB, ENGINE=MyISAM, etc.
924        static RE_ENGINE: Lazy<Regex> =
925            Lazy::new(|| Regex::new(r"(?i)\s*ENGINE\s*=\s*\w+").unwrap());
926        RE_ENGINE.replace_all(stmt, "").to_string()
927    }
928
929    /// Strip CHARSET/COLLATE clauses
930    fn strip_charset_clauses(&self, stmt: &str) -> String {
931        use once_cell::sync::Lazy;
932        use regex::Regex;
933
934        if self.to == SqlDialect::MySql {
935            return stmt.to_string();
936        }
937
938        static RE_CHARSET: Lazy<Regex> =
939            Lazy::new(|| Regex::new(r"(?i)\s*(DEFAULT\s+)?CHARSET\s*=\s*\w+").unwrap());
940        static RE_COLLATE: Lazy<Regex> =
941            Lazy::new(|| Regex::new(r"(?i)\s*COLLATE\s*=?\s*\w+").unwrap());
942
943        let result = RE_CHARSET.replace_all(stmt, "").to_string();
944        RE_COLLATE.replace_all(&result, "").to_string()
945    }
946
947    /// Case-insensitively checks whether `keyword` starts at `chars[pos]`, with
948    /// word boundaries on both sides (so e.g. "COMMENT" doesn't match inside
949    /// "COMMENTARY" or a preceding identifier char like "XCOMMENT"). Returns the
950    /// index just past the keyword on success.
951    fn match_keyword_ci(chars: &[char], pos: usize, keyword: &str) -> Option<usize> {
952        let kw_len = keyword.len();
953        if pos > 0 && (chars[pos - 1].is_alphanumeric() || chars[pos - 1] == '_') {
954            return None;
955        }
956        let end = pos + kw_len;
957        if end > chars.len() {
958            return None;
959        }
960        let candidate: String = chars[pos..end].iter().collect();
961        if !candidate.eq_ignore_ascii_case(keyword) {
962            return None;
963        }
964        if end < chars.len() && (chars[end].is_alphanumeric() || chars[end] == '_') {
965            return None;
966        }
967        Some(end)
968    }
969
970    /// Removes trailing whitespace already pushed into `result`, so that stripping
971    /// a clause also absorbs the whitespace that preceded it (matching the old
972    /// `\s*<keyword>...` regex behavior).
973    fn trim_trailing_whitespace(result: &mut String) {
974        while result.ends_with(|c: char| c.is_whitespace()) {
975            result.pop();
976        }
977    }
978
979    /// Strip MySQL table-level `AUTO_INCREMENT=N` option. String-literal-aware so
980    /// that a DEFAULT value or other string content containing the literal text
981    /// "AUTO_INCREMENT=N" is left untouched.
982    /// See https://github.com/HelgeSverre/sql-splitter/issues/64
983    fn strip_mysql_auto_increment_table_option(&self, stmt: &str) -> String {
984        let chars: Vec<char> = stmt.chars().collect();
985        let n = chars.len();
986        let mut result = String::with_capacity(stmt.len());
987        let mut in_string = false;
988        let mut i = 0;
989
990        while i < n {
991            let c = chars[i];
992            if c == '\'' {
993                in_string = !in_string;
994                result.push(c);
995                i += 1;
996                continue;
997            }
998            if !in_string {
999                if let Some(after_kw) = Self::match_keyword_ci(&chars, i, "AUTO_INCREMENT") {
1000                    let mut j = after_kw;
1001                    while j < n && chars[j].is_whitespace() {
1002                        j += 1;
1003                    }
1004                    if j < n && chars[j] == '=' {
1005                        j += 1;
1006                        while j < n && chars[j].is_whitespace() {
1007                            j += 1;
1008                        }
1009                        let digits_start = j;
1010                        while j < n && chars[j].is_ascii_digit() {
1011                            j += 1;
1012                        }
1013                        if j > digits_start {
1014                            Self::trim_trailing_whitespace(&mut result);
1015                            i = j;
1016                            continue;
1017                        }
1018                    }
1019                }
1020            }
1021            result.push(c);
1022            i += 1;
1023        }
1024        result
1025    }
1026
1027    /// Strip MySQL column/table `COMMENT 'text'` (or `COMMENT='text'`) annotations.
1028    /// Neither is valid inside a PostgreSQL column definition or as a CREATE TABLE
1029    /// table option, so they are removed entirely rather than translated.
1030    /// String-literal-aware: only matches a real `COMMENT` clause, never the word
1031    /// "comment" sitting inside an unrelated DEFAULT value or CHECK expression.
1032    fn strip_mysql_comment_clauses(&self, stmt: &str) -> String {
1033        if self.to == SqlDialect::MySql {
1034            return stmt.to_string();
1035        }
1036
1037        let chars: Vec<char> = stmt.chars().collect();
1038        let n = chars.len();
1039        let mut result = String::with_capacity(stmt.len());
1040        let mut in_string = false;
1041        let mut i = 0;
1042
1043        while i < n {
1044            let c = chars[i];
1045            if c == '\'' {
1046                in_string = !in_string;
1047                result.push(c);
1048                i += 1;
1049                continue;
1050            }
1051            if !in_string {
1052                if let Some(after_kw) = Self::match_keyword_ci(&chars, i, "COMMENT") {
1053                    let mut j = after_kw;
1054                    while j < n && chars[j].is_whitespace() {
1055                        j += 1;
1056                    }
1057                    if j < n && chars[j] == '=' {
1058                        j += 1;
1059                        while j < n && chars[j].is_whitespace() {
1060                            j += 1;
1061                        }
1062                    }
1063                    if j < n && chars[j] == '\'' {
1064                        // Consume the quoted comment text itself, honoring ''
1065                        // as an escaped quote, then drop the whole clause.
1066                        j += 1;
1067                        loop {
1068                            if j >= n {
1069                                break;
1070                            }
1071                            if chars[j] == '\'' {
1072                                if j + 1 < n && chars[j + 1] == '\'' {
1073                                    j += 2;
1074                                    continue;
1075                                }
1076                                j += 1;
1077                                break;
1078                            }
1079                            j += 1;
1080                        }
1081                        Self::trim_trailing_whitespace(&mut result);
1082                        i = j;
1083                        continue;
1084                    }
1085                }
1086            }
1087            result.push(c);
1088            i += 1;
1089        }
1090        result
1091    }
1092
1093    /// Convert MySQL's column-level `AUTO_INCREMENT` keyword to PostgreSQL's
1094    /// `SERIAL`/`BIGSERIAL`, case-insensitively and string-literal-aware (a
1095    /// DEFAULT value or CHECK expression containing the literal text
1096    /// "AUTO_INCREMENT" must not be touched — see finding in issue #64 follow-up
1097    /// review).
1098    fn convert_mysql_auto_increment_keyword(&self, stmt: &str) -> String {
1099        let chars: Vec<char> = stmt.chars().collect();
1100        let n = chars.len();
1101        let mut result = String::with_capacity(stmt.len());
1102        let mut in_string = false;
1103        let mut i = 0;
1104
1105        while i < n {
1106            let c = chars[i];
1107            if c == '\'' {
1108                in_string = !in_string;
1109                result.push(c);
1110                i += 1;
1111                continue;
1112            }
1113            if !in_string {
1114                if let Some(after_type) = Self::match_keyword_ci(&chars, i, "BIGINT") {
1115                    let mut j = after_type;
1116                    while j < n && chars[j].is_whitespace() {
1117                        j += 1;
1118                    }
1119                    if let Some(end) = Self::match_keyword_ci(&chars, j, "AUTO_INCREMENT") {
1120                        result.push_str("BIGSERIAL");
1121                        i = end;
1122                        continue;
1123                    }
1124                }
1125                if let Some(after_type) = Self::match_keyword_ci(&chars, i, "INT") {
1126                    let mut j = after_type;
1127                    while j < n && chars[j].is_whitespace() {
1128                        j += 1;
1129                    }
1130                    if let Some(end) = Self::match_keyword_ci(&chars, j, "AUTO_INCREMENT") {
1131                        result.push_str("SERIAL");
1132                        i = end;
1133                        continue;
1134                    }
1135                }
1136                if let Some(end) = Self::match_keyword_ci(&chars, i, "AUTO_INCREMENT") {
1137                    // Clean up any remaining standalone occurrence (e.g. when
1138                    // other modifiers like NOT NULL sit between the type and
1139                    // the keyword).
1140                    i = end;
1141                    continue;
1142                }
1143            }
1144            result.push(c);
1145            i += 1;
1146        }
1147        result
1148    }
1149
1150    /// Convert MySQL `UNIQUE KEY [name] (cols) [USING BTREE|HASH]` table constraint
1151    /// to standard `UNIQUE (cols)`, which is the closest PostgreSQL equivalent.
1152    /// Also strips MySQL prefix-length index annotations (e.g. `email(191)`),
1153    /// which have no PostgreSQL equivalent and aren't valid there.
1154    fn convert_unique_key_constraint(&self, stmt: &str) -> String {
1155        use once_cell::sync::Lazy;
1156        use regex::{Captures, Regex};
1157
1158        if self.to == SqlDialect::MySql {
1159            return stmt.to_string();
1160        }
1161
1162        // The column-list group allows one level of nested `(digits)` prefix-length
1163        // annotations (e.g. `("email"(191),"other")`), which are common in
1164        // real-world MySQL dumps using utf8mb4 prefix indexes.
1165        static RE: Lazy<Regex> = Lazy::new(|| {
1166            Regex::new(
1167                r#"(?i)UNIQUE\s+KEY\s+(?:"[^"]*"\s+)?(\([^()]*(?:\(\d+\)[^()]*)*\))(?:\s*USING\s+(?:BTREE|HASH))?"#,
1168            )
1169            .unwrap()
1170        });
1171        static RE_PREFIX_LEN: Lazy<Regex> = Lazy::new(|| Regex::new(r"\(\d+\)").unwrap());
1172
1173        RE.replace_all(stmt, |caps: &Captures| {
1174            let cols = RE_PREFIX_LEN.replace_all(&caps[1], "");
1175            format!("UNIQUE {}", cols)
1176        })
1177        .to_string()
1178    }
1179
1180    /// Strip PostgreSQL type casts (::type and ::regclass)
1181    fn strip_postgres_casts(&self, stmt: &str) -> String {
1182        use once_cell::sync::Lazy;
1183        use regex::Regex;
1184
1185        // Match ::regclass, ::text, ::integer, etc. (including complex types like character varying)
1186        static RE_CAST: Lazy<Regex> = Lazy::new(|| {
1187            Regex::new(r"::[a-zA-Z_][a-zA-Z0-9_]*(?:\s+[a-zA-Z_][a-zA-Z0-9_]*)*").unwrap()
1188        });
1189
1190        RE_CAST.replace_all(stmt, "").to_string()
1191    }
1192
1193    /// Convert nextval('sequence') to NULL or remove (AUTO_INCREMENT handles it)
1194    fn convert_nextval(&self, stmt: &str) -> String {
1195        use once_cell::sync::Lazy;
1196        use regex::Regex;
1197
1198        // Match nextval('sequence_name'::regclass) or nextval('sequence_name')
1199        // Remove the DEFAULT nextval(...) entirely - AUTO_INCREMENT is already applied
1200        static RE_NEXTVAL: Lazy<Regex> =
1201            Lazy::new(|| Regex::new(r"(?i)\s*DEFAULT\s+nextval\s*\([^)]+\)").unwrap());
1202
1203        RE_NEXTVAL.replace_all(stmt, "").to_string()
1204    }
1205
1206    /// Convert DEFAULT now() to DEFAULT CURRENT_TIMESTAMP
1207    fn convert_default_now(&self, stmt: &str) -> String {
1208        use once_cell::sync::Lazy;
1209        use regex::Regex;
1210
1211        static RE_NOW: Lazy<Regex> =
1212            Lazy::new(|| Regex::new(r"(?i)\bDEFAULT\s+now\s*\(\s*\)").unwrap());
1213
1214        RE_NOW
1215            .replace_all(stmt, "DEFAULT CURRENT_TIMESTAMP")
1216            .to_string()
1217    }
1218
1219    /// Strip schema prefix from table names (e.g., public.users -> users)
1220    fn strip_schema_prefix(&self, stmt: &str) -> String {
1221        use once_cell::sync::Lazy;
1222        use regex::Regex;
1223
1224        // Match schema.table patterns (with optional quotes)
1225        // Handle: public.table, "public"."table", public."table"
1226        static RE_SCHEMA: Lazy<Regex> =
1227            Lazy::new(|| Regex::new(r#"(?i)\b(public|pg_catalog|pg_temp)\s*\.\s*"#).unwrap());
1228
1229        RE_SCHEMA.replace_all(stmt, "").to_string()
1230    }
1231
1232    /// Convert MSSQL GETDATE() to CURRENT_TIMESTAMP
1233    fn convert_mssql_getdate(&self, stmt: &str) -> String {
1234        use once_cell::sync::Lazy;
1235        use regex::Regex;
1236
1237        static RE_GETDATE: Lazy<Regex> =
1238            Lazy::new(|| Regex::new(r"(?i)\bGETDATE\s*\(\s*\)").unwrap());
1239        static RE_SYSDATETIME: Lazy<Regex> =
1240            Lazy::new(|| Regex::new(r"(?i)\bSYSDATETIME\s*\(\s*\)").unwrap());
1241        static RE_GETUTCDATE: Lazy<Regex> =
1242            Lazy::new(|| Regex::new(r"(?i)\bGETUTCDATE\s*\(\s*\)").unwrap());
1243
1244        let result = RE_GETDATE
1245            .replace_all(stmt, "CURRENT_TIMESTAMP")
1246            .to_string();
1247        let result = RE_SYSDATETIME
1248            .replace_all(&result, "CURRENT_TIMESTAMP")
1249            .to_string();
1250        RE_GETUTCDATE
1251            .replace_all(&result, "CURRENT_TIMESTAMP")
1252            .to_string()
1253    }
1254
1255    /// Strip MSSQL ON [filegroup] clause
1256    fn strip_mssql_on_filegroup(&self, stmt: &str) -> String {
1257        use once_cell::sync::Lazy;
1258        use regex::Regex;
1259
1260        // Match ON [PRIMARY] or ON [filegroup_name]
1261        static RE_ON_FILEGROUP: Lazy<Regex> =
1262            Lazy::new(|| Regex::new(r"(?i)\s+ON\s*\[\s*\w+\s*\]").unwrap());
1263
1264        RE_ON_FILEGROUP.replace_all(stmt, "").to_string()
1265    }
1266
1267    /// Strip MSSQL CLUSTERED/NONCLUSTERED keywords
1268    fn strip_mssql_clustered(&self, stmt: &str) -> String {
1269        use once_cell::sync::Lazy;
1270        use regex::Regex;
1271
1272        static RE_CLUSTERED: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bCLUSTERED\s+").unwrap());
1273        static RE_NONCLUSTERED: Lazy<Regex> =
1274            Lazy::new(|| Regex::new(r"(?i)\bNONCLUSTERED\s+").unwrap());
1275
1276        let result = RE_CLUSTERED.replace_all(stmt, "").to_string();
1277        RE_NONCLUSTERED.replace_all(&result, "").to_string()
1278    }
1279
1280    /// Convert MSSQL N'unicode' strings to regular 'unicode' strings
1281    fn convert_mssql_unicode_strings(&self, stmt: &str) -> String {
1282        use once_cell::sync::Lazy;
1283        use regex::Regex;
1284
1285        // Match N'...' unicode strings, being careful not to match inside strings
1286        // This is a simplified version that handles most cases
1287        static RE_UNICODE_STRING: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bN'").unwrap());
1288
1289        RE_UNICODE_STRING.replace_all(stmt, "'").to_string()
1290    }
1291
1292    /// Strip MSSQL schema prefix (dbo., etc.) from table names
1293    fn strip_mssql_schema_prefix(&self, stmt: &str) -> String {
1294        use once_cell::sync::Lazy;
1295        use regex::Regex;
1296
1297        // Match [dbo].[table] or dbo.table and keep just [table] or table
1298        // We replace schema.table with just table, handling both bracketed and unbracketed forms
1299        static RE_MSSQL_SCHEMA: Lazy<Regex> =
1300            Lazy::new(|| Regex::new(r"(?i)\[?dbo\]?\s*\.\s*").unwrap());
1301
1302        RE_MSSQL_SCHEMA.replace_all(stmt, "").to_string()
1303    }
1304
1305    /// Detect unsupported features and add warnings
1306    fn detect_unsupported_features(
1307        &mut self,
1308        stmt: &str,
1309        table_name: Option<&str>,
1310    ) -> Result<(), ConvertWarning> {
1311        let upper = stmt.to_uppercase();
1312
1313        // MySQL-specific features
1314        if self.from == SqlDialect::MySql {
1315            // ENUM types
1316            if upper.contains("ENUM(") {
1317                let warning = ConvertWarning::UnsupportedFeature {
1318                    feature: format!(
1319                        "ENUM type{}",
1320                        table_name
1321                            .map(|t| format!(" in table {}", t))
1322                            .unwrap_or_default()
1323                    ),
1324                    suggestion: Some(
1325                        "Converted to VARCHAR - consider adding CHECK constraint".to_string(),
1326                    ),
1327                };
1328                self.warnings.add(warning.clone());
1329                if self.strict {
1330                    return Err(warning);
1331                }
1332            }
1333
1334            // SET types (MySQL)
1335            if upper.contains("SET(") {
1336                let warning = ConvertWarning::UnsupportedFeature {
1337                    feature: format!(
1338                        "SET type{}",
1339                        table_name
1340                            .map(|t| format!(" in table {}", t))
1341                            .unwrap_or_default()
1342                    ),
1343                    suggestion: Some(
1344                        "Converted to VARCHAR - SET semantics not preserved".to_string(),
1345                    ),
1346                };
1347                self.warnings.add(warning.clone());
1348                if self.strict {
1349                    return Err(warning);
1350                }
1351            }
1352
1353            // UNSIGNED
1354            if upper.contains("UNSIGNED") {
1355                self.warnings.add(ConvertWarning::UnsupportedFeature {
1356                    feature: "UNSIGNED modifier".to_string(),
1357                    suggestion: Some(
1358                        "Removed - consider adding CHECK constraint for non-negative values"
1359                            .to_string(),
1360                    ),
1361                });
1362            }
1363        }
1364
1365        // PostgreSQL-specific features
1366        if self.from == SqlDialect::Postgres {
1367            // Array types
1368            if upper.contains("[]") || upper.contains("ARRAY[") {
1369                let warning = ConvertWarning::UnsupportedFeature {
1370                    feature: format!(
1371                        "Array type{}",
1372                        table_name
1373                            .map(|t| format!(" in table {}", t))
1374                            .unwrap_or_default()
1375                    ),
1376                    suggestion: Some(
1377                        "Array types not supported in target dialect - consider using JSON"
1378                            .to_string(),
1379                    ),
1380                };
1381                self.warnings.add(warning.clone());
1382                if self.strict {
1383                    return Err(warning);
1384                }
1385            }
1386
1387            // INHERITS
1388            if upper.contains("INHERITS") {
1389                let warning = ConvertWarning::UnsupportedFeature {
1390                    feature: "Table inheritance (INHERITS)".to_string(),
1391                    suggestion: Some(
1392                        "PostgreSQL table inheritance not supported in target dialect".to_string(),
1393                    ),
1394                };
1395                self.warnings.add(warning.clone());
1396                if self.strict {
1397                    return Err(warning);
1398                }
1399            }
1400
1401            // PARTITION BY
1402            if upper.contains("PARTITION BY") && self.to == SqlDialect::Sqlite {
1403                let warning = ConvertWarning::UnsupportedFeature {
1404                    feature: "Table partitioning".to_string(),
1405                    suggestion: Some("Partitioning not supported in SQLite".to_string()),
1406                };
1407                self.warnings.add(warning.clone());
1408                if self.strict {
1409                    return Err(warning);
1410                }
1411            }
1412        }
1413
1414        Ok(())
1415    }
1416
1417    /// Get collected warnings
1418    pub fn warnings(&self) -> &[ConvertWarning] {
1419        self.warnings.warnings()
1420    }
1421}
1422
1423/// Run the convert command
1424pub fn run(config: ConvertConfig) -> anyhow::Result<ConvertStats> {
1425    let mut stats = ConvertStats::default();
1426
1427    // Detect or use specified source dialect
1428    let from_dialect = if let Some(d) = config.from_dialect {
1429        d
1430    } else {
1431        let result = crate::parser::detect_dialect_from_file(&config.input)?;
1432        if config.progress {
1433            eprintln!(
1434                "Auto-detected source dialect: {} (confidence: {:?})",
1435                result.dialect, result.confidence
1436            );
1437        }
1438        result.dialect
1439    };
1440
1441    // Check for same dialect
1442    if from_dialect == config.to_dialect {
1443        anyhow::bail!(
1444            "Source and target dialects are the same ({}). No conversion needed.",
1445            from_dialect
1446        );
1447    }
1448
1449    // Get file size for progress tracking
1450    let file_size = std::fs::metadata(&config.input)?.len();
1451
1452    let progress_bar = if config.progress {
1453        let pb = ProgressBar::new(file_size);
1454        pb.set_style(
1455            ProgressStyle::with_template(
1456                "{spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] {bytes}/{total_bytes} ({percent}%) {msg}",
1457            )
1458            .unwrap()
1459            .progress_chars("█▓▒░  ")
1460            .tick_chars("⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"),
1461        );
1462        pb.enable_steady_tick(std::time::Duration::from_millis(100));
1463        pb.set_message("Converting...");
1464        Some(pb)
1465    } else {
1466        None
1467    };
1468
1469    // Create converter
1470    let mut converter = Converter::new(from_dialect, config.to_dialect).with_strict(config.strict);
1471
1472    // Open input, transparently handling any supported compression format
1473    // (including zip archives), with optional progress tracking.
1474    let reader: Box<dyn Read> = if let Some(ref pb) = progress_bar {
1475        let pb_clone = pb.clone();
1476        open_input_with_progress(
1477            &config.input,
1478            Box::new(move |bytes| pb_clone.set_position(bytes)),
1479        )?
1480    } else {
1481        open_input(&config.input)?
1482    };
1483    let mut parser = Parser::with_dialect(reader, 64 * 1024, from_dialect);
1484
1485    // Open output
1486    let mut writer: Box<dyn Write> = if config.dry_run {
1487        Box::new(std::io::sink())
1488    } else {
1489        match &config.output {
1490            Some(path) => {
1491                if let Some(parent) = path.parent() {
1492                    std::fs::create_dir_all(parent)?;
1493                }
1494                Box::new(BufWriter::with_capacity(256 * 1024, File::create(path)?))
1495            }
1496            None => Box::new(BufWriter::new(std::io::stdout())),
1497        }
1498    };
1499
1500    // Write header
1501    if !config.dry_run {
1502        write_header(&mut writer, &config, from_dialect)?;
1503    }
1504
1505    // Process statements
1506    while let Some(stmt) = parser.read_statement()? {
1507        stats.statements_processed += 1;
1508
1509        // Check if this is a COPY data block (follows a COPY header)
1510        if converter.has_pending_copy() {
1511            // This is a data block, convert it to INSERT statements
1512            match converter.process_copy_data(&stmt) {
1513                Ok(inserts) => {
1514                    for insert in inserts {
1515                        if !insert.is_empty() {
1516                            stats.statements_converted += 1;
1517                            if !config.dry_run {
1518                                writer.write_all(&insert)?;
1519                                writer.write_all(b"\n")?;
1520                            }
1521                        }
1522                    }
1523                }
1524                Err(warning) => {
1525                    stats.warnings.push(warning);
1526                    stats.statements_skipped += 1;
1527                }
1528            }
1529            continue;
1530        }
1531
1532        match converter.convert_statement(&stmt) {
1533            Ok(converted) => {
1534                if converted.is_empty() {
1535                    stats.statements_skipped += 1;
1536                } else if converted == stmt {
1537                    stats.statements_unchanged += 1;
1538                    if !config.dry_run {
1539                        writer.write_all(&converted)?;
1540                        writer.write_all(b"\n")?;
1541                    }
1542                } else {
1543                    stats.statements_converted += 1;
1544                    if !config.dry_run {
1545                        writer.write_all(&converted)?;
1546                        writer.write_all(b"\n")?;
1547                    }
1548                }
1549            }
1550            Err(warning) => {
1551                stats.warnings.push(warning);
1552                stats.statements_skipped += 1;
1553            }
1554        }
1555    }
1556
1557    // Collect warnings
1558    stats.warnings.extend(converter.warnings().iter().cloned());
1559
1560    if let Some(pb) = progress_bar {
1561        pb.finish_with_message("done");
1562    }
1563
1564    Ok(stats)
1565}
1566
1567/// Write output header
1568fn write_header(
1569    writer: &mut dyn Write,
1570    config: &ConvertConfig,
1571    from: SqlDialect,
1572) -> std::io::Result<()> {
1573    writeln!(writer, "-- Converted by sql-splitter")?;
1574    writeln!(writer, "-- From: {} → To: {}", from, config.to_dialect)?;
1575    writeln!(writer, "-- Source: {}", config.input.display())?;
1576    writeln!(writer)?;
1577
1578    // Write dialect-specific header
1579    match config.to_dialect {
1580        SqlDialect::Postgres => {
1581            writeln!(writer, "SET client_encoding = 'UTF8';")?;
1582            writeln!(writer, "SET standard_conforming_strings = on;")?;
1583        }
1584        SqlDialect::Sqlite => {
1585            writeln!(writer, "PRAGMA foreign_keys = OFF;")?;
1586        }
1587        SqlDialect::MySql => {
1588            writeln!(writer, "SET NAMES utf8mb4;")?;
1589            writeln!(writer, "SET FOREIGN_KEY_CHECKS = 0;")?;
1590        }
1591        SqlDialect::Mssql => {
1592            writeln!(writer, "SET ANSI_NULLS ON;")?;
1593            writeln!(writer, "SET QUOTED_IDENTIFIER ON;")?;
1594            writeln!(writer, "SET NOCOUNT ON;")?;
1595        }
1596    }
1597    writeln!(writer)?;
1598
1599    Ok(())
1600}