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::progress::ProgressReader;
22use crate::splitter::Compression;
23use indicatif::{ProgressBar, ProgressStyle};
24use std::fs::File;
25use std::io::{BufWriter, Read, Write};
26use std::path::PathBuf;
27
28pub use types::TypeMapper;
29pub use warnings::{print_warnings_summary, ConvertWarning, WarningCollector};
30
31/// Configuration for the convert command
32#[derive(Debug)]
33pub struct ConvertConfig {
34    /// Input SQL file
35    pub input: PathBuf,
36    /// Output SQL file (None for stdout)
37    pub output: Option<PathBuf>,
38    /// Source dialect (auto-detected if None)
39    pub from_dialect: Option<SqlDialect>,
40    /// Target dialect
41    pub to_dialect: SqlDialect,
42    /// Dry run mode
43    pub dry_run: bool,
44    /// Show progress
45    pub progress: bool,
46    /// Strict mode (fail on any unsupported feature)
47    pub strict: bool,
48}
49
50impl Default for ConvertConfig {
51    fn default() -> Self {
52        Self {
53            input: PathBuf::new(),
54            output: None,
55            from_dialect: None,
56            to_dialect: SqlDialect::Postgres,
57            dry_run: false,
58            progress: false,
59            strict: false,
60        }
61    }
62}
63
64/// Statistics from convert operation
65#[derive(Debug, Default, serde::Serialize)]
66pub struct ConvertStats {
67    /// Total statements processed
68    pub statements_processed: u64,
69    /// Statements converted
70    pub statements_converted: u64,
71    /// Statements passed through unchanged
72    pub statements_unchanged: u64,
73    /// Statements skipped (unsupported)
74    pub statements_skipped: u64,
75    /// Warnings generated
76    pub warnings: Vec<ConvertWarning>,
77}
78
79/// Main converter that dispatches to specific dialect converters
80pub struct Converter {
81    from: SqlDialect,
82    to: SqlDialect,
83    warnings: WarningCollector,
84    strict: bool,
85    /// Pending COPY header for data block processing
86    pending_copy_header: Option<CopyHeader>,
87}
88
89impl Converter {
90    pub fn new(from: SqlDialect, to: SqlDialect) -> Self {
91        Self {
92            from,
93            to,
94            warnings: WarningCollector::new(),
95            strict: false,
96            pending_copy_header: None,
97        }
98    }
99
100    pub fn with_strict(mut self, strict: bool) -> Self {
101        self.strict = strict;
102        self
103    }
104
105    /// Check if we have a pending COPY header (waiting for data block)
106    pub fn has_pending_copy(&self) -> bool {
107        self.pending_copy_header.is_some()
108    }
109
110    /// Process a COPY data block using the pending header
111    pub fn process_copy_data(&mut self, data: &[u8]) -> Result<Vec<Vec<u8>>, ConvertWarning> {
112        if let Some(header) = self.pending_copy_header.take() {
113            if self.from == SqlDialect::Postgres && self.to != SqlDialect::Postgres {
114                // Convert COPY data to INSERT statements
115                let inserts = copy_to_inserts(&header, data, self.to);
116                return Ok(inserts);
117            }
118        }
119        // Pass through if same dialect or no pending header
120        Ok(vec![data.to_vec()])
121    }
122
123    /// Convert a single statement
124    pub fn convert_statement(&mut self, stmt: &[u8]) -> Result<Vec<u8>, ConvertWarning> {
125        let (stmt_type, table_name) =
126            Parser::<&[u8]>::parse_statement_with_dialect(stmt, self.from);
127
128        let table = if table_name.is_empty() {
129            None
130        } else {
131            Some(table_name.as_str())
132        };
133
134        match stmt_type {
135            StatementType::CreateTable => self.convert_create_table(stmt, table),
136            StatementType::Insert => self.convert_insert(stmt, table),
137            StatementType::CreateIndex => self.convert_create_index(stmt),
138            StatementType::AlterTable => self.convert_alter_table(stmt),
139            StatementType::DropTable => self.convert_drop_table(stmt),
140            StatementType::Copy => self.convert_copy(stmt, table),
141            StatementType::Unknown => self.convert_other(stmt),
142        }
143    }
144
145    /// Convert CREATE TABLE statement
146    fn convert_create_table(
147        &mut self,
148        stmt: &[u8],
149        table_name: Option<&str>,
150    ) -> Result<Vec<u8>, ConvertWarning> {
151        let stmt_str = String::from_utf8_lossy(stmt);
152        let mut result = stmt_str.to_string();
153
154        // Detect unsupported features BEFORE conversion (so we see original types)
155        self.detect_unsupported_features(&result, table_name)?;
156
157        // Convert MSSQL-specific syntax BEFORE identifier conversion
158        // (so we can strip [dbo]. schema prefix properly)
159        if self.from == SqlDialect::Mssql && self.to != SqlDialect::Mssql {
160            result = self.strip_mssql_schema_prefix(&result);
161            result = self.convert_mssql_getdate(&result);
162            result = self.strip_mssql_on_filegroup(&result);
163            result = self.strip_mssql_clustered(&result);
164            result = self.convert_mssql_unicode_strings(&result);
165        }
166
167        // Convert identifier quoting
168        result = self.convert_identifiers(&result);
169
170        // Convert data types
171        result = self.convert_data_types(&result);
172
173        // Convert AUTO_INCREMENT
174        result = self.convert_auto_increment(&result, table_name);
175
176        // Convert PostgreSQL-specific syntax
177        if self.from == SqlDialect::Postgres && self.to != SqlDialect::Postgres {
178            result = self.strip_postgres_casts(&result);
179            result = self.convert_nextval(&result);
180            result = self.convert_default_now(&result);
181            result = self.strip_schema_prefix(&result);
182        }
183
184        // Convert string escapes
185        result = self.convert_string_escapes(&result);
186
187        // Strip MySQL conditional comments
188        result = self.strip_conditional_comments(&result);
189
190        // Convert ENGINE clause
191        result = self.strip_engine_clause(&result);
192
193        // Convert CHARSET/COLLATE
194        result = self.strip_charset_clauses(&result);
195
196        // Strip MySQL inline column/table COMMENT annotations
197        result = self.strip_mysql_comment_clauses(&result);
198
199        // Convert UNIQUE KEY ... USING BTREE table constraints
200        result = self.convert_unique_key_constraint(&result);
201
202        Ok(result.into_bytes())
203    }
204
205    /// Convert INSERT statement
206    fn convert_insert(
207        &mut self,
208        stmt: &[u8],
209        _table_name: Option<&str>,
210    ) -> Result<Vec<u8>, ConvertWarning> {
211        let stmt_str = String::from_utf8_lossy(stmt);
212        let mut result = stmt_str.to_string();
213
214        // Convert MSSQL-specific syntax BEFORE identifier conversion
215        if self.from == SqlDialect::Mssql && self.to != SqlDialect::Mssql {
216            result = self.strip_mssql_schema_prefix(&result);
217            result = self.convert_mssql_unicode_strings(&result);
218        }
219
220        // Convert identifier quoting
221        result = self.convert_identifiers(&result);
222
223        // Convert PostgreSQL-specific syntax
224        if self.from == SqlDialect::Postgres && self.to != SqlDialect::Postgres {
225            result = self.strip_postgres_casts(&result);
226            result = self.strip_schema_prefix(&result);
227        }
228
229        // Convert string escapes (careful with data!)
230        result = self.convert_string_escapes(&result);
231
232        Ok(result.into_bytes())
233    }
234
235    /// Convert CREATE INDEX statement
236    fn convert_create_index(&mut self, stmt: &[u8]) -> Result<Vec<u8>, ConvertWarning> {
237        let stmt_str = String::from_utf8_lossy(stmt);
238        let mut result = stmt_str.to_string();
239
240        // Convert MSSQL-specific syntax BEFORE identifier conversion
241        if self.from == SqlDialect::Mssql && self.to != SqlDialect::Mssql {
242            result = self.strip_mssql_schema_prefix(&result);
243            result = self.strip_mssql_clustered(&result);
244        }
245
246        // Convert identifier quoting
247        result = self.convert_identifiers(&result);
248
249        // Convert PostgreSQL-specific syntax
250        if self.from == SqlDialect::Postgres && self.to != SqlDialect::Postgres {
251            result = self.strip_postgres_casts(&result);
252            result = self.strip_schema_prefix(&result);
253        }
254
255        // Detect FULLTEXT/SPATIAL
256        if result.contains("FULLTEXT") || result.contains("fulltext") {
257            self.warnings.add(ConvertWarning::UnsupportedFeature {
258                feature: "FULLTEXT INDEX".to_string(),
259                suggestion: Some("Use PostgreSQL GIN index or skip".to_string()),
260            });
261            if self.strict {
262                return Err(ConvertWarning::UnsupportedFeature {
263                    feature: "FULLTEXT INDEX".to_string(),
264                    suggestion: None,
265                });
266            }
267        }
268
269        Ok(result.into_bytes())
270    }
271
272    /// Convert ALTER TABLE statement
273    fn convert_alter_table(&mut self, stmt: &[u8]) -> Result<Vec<u8>, ConvertWarning> {
274        let stmt_str = String::from_utf8_lossy(stmt);
275        let mut result = stmt_str.to_string();
276
277        result = self.convert_identifiers(&result);
278        result = self.convert_data_types(&result);
279
280        // Convert PostgreSQL-specific syntax
281        if self.from == SqlDialect::Postgres && self.to != SqlDialect::Postgres {
282            result = self.strip_postgres_casts(&result);
283            result = self.convert_nextval(&result);
284            result = self.convert_default_now(&result);
285            result = self.strip_schema_prefix(&result);
286        }
287
288        Ok(result.into_bytes())
289    }
290
291    /// Convert DROP TABLE statement
292    fn convert_drop_table(&mut self, stmt: &[u8]) -> Result<Vec<u8>, ConvertWarning> {
293        let stmt_str = String::from_utf8_lossy(stmt);
294        let mut result = stmt_str.to_string();
295
296        result = self.convert_identifiers(&result);
297
298        // Strip PostgreSQL schema prefix
299        if self.from == SqlDialect::Postgres && self.to != SqlDialect::Postgres {
300            result = self.strip_schema_prefix(&result);
301        }
302
303        Ok(result.into_bytes())
304    }
305
306    /// Convert COPY statement (PostgreSQL-specific)
307    ///
308    /// This handles the COPY header. The data block is processed separately
309    /// via process_copy_data() when called from the run() function.
310    fn convert_copy(
311        &mut self,
312        stmt: &[u8],
313        _table_name: Option<&str>,
314    ) -> Result<Vec<u8>, ConvertWarning> {
315        let stmt_str = String::from_utf8_lossy(stmt);
316
317        // Check if this contains "FROM stdin" (COPY header) or is data
318        let upper = stmt_str.to_uppercase();
319        if upper.contains("FROM STDIN") {
320            // This is a COPY header - parse it and store for later
321            if let Some(header) = parse_copy_header(&stmt_str) {
322                if self.from == SqlDialect::Postgres && self.to != SqlDialect::Postgres {
323                    // Store the header, will convert data block in process_copy_data
324                    self.pending_copy_header = Some(header);
325                    // Return empty - the actual INSERT will be generated from data
326                    return Ok(Vec::new());
327                }
328            }
329        }
330
331        // If same dialect or couldn't parse, pass through
332        Ok(stmt.to_vec())
333    }
334
335    /// Convert other statements (comments, session settings, etc.)
336    fn convert_other(&mut self, stmt: &[u8]) -> Result<Vec<u8>, ConvertWarning> {
337        let stmt_str = String::from_utf8_lossy(stmt);
338        let result = stmt_str.to_string();
339        let trimmed = result.trim();
340
341        // Skip MySQL session commands when converting to other dialects
342        if self.from == SqlDialect::MySql
343            && self.to != SqlDialect::MySql
344            && self.is_mysql_session_command(&result)
345        {
346            return Ok(Vec::new()); // Skip
347        }
348
349        // Skip PostgreSQL session commands and unsupported features when converting to other dialects
350        if self.from == SqlDialect::Postgres
351            && self.to != SqlDialect::Postgres
352            && self.is_postgres_session_command(&result)
353        {
354            return Ok(Vec::new()); // Skip
355        }
356        if self.from == SqlDialect::Postgres
357            && self.to != SqlDialect::Postgres
358            && self.is_postgres_only_feature(trimmed)
359        {
360            self.warnings.add(ConvertWarning::SkippedStatement {
361                reason: "PostgreSQL-only feature".to_string(),
362                statement_preview: trimmed.chars().take(60).collect(),
363            });
364            return Ok(Vec::new()); // Skip
365        }
366
367        // Skip SQLite pragmas when converting to other dialects
368        if self.from == SqlDialect::Sqlite
369            && self.to != SqlDialect::Sqlite
370            && self.is_sqlite_pragma(&result)
371        {
372            return Ok(Vec::new()); // Skip
373        }
374
375        // Skip MSSQL session commands when converting to other dialects
376        if self.from == SqlDialect::Mssql
377            && self.to != SqlDialect::Mssql
378            && self.is_mssql_session_command(&result)
379        {
380            return Ok(Vec::new()); // Skip
381        }
382
383        // Strip conditional comments
384        if result.contains("/*!") {
385            let stripped = self.strip_conditional_comments(&result);
386            return Ok(stripped.into_bytes());
387        }
388
389        Ok(stmt.to_vec())
390    }
391
392    /// Check if statement is a MySQL session command
393    fn is_mysql_session_command(&self, stmt: &str) -> bool {
394        let upper = stmt.to_uppercase();
395        upper.contains("SET NAMES")
396            || upper.contains("SET CHARACTER")
397            || upper.contains("SET SQL_MODE")
398            || upper.contains("SET TIME_ZONE")
399            || upper.contains("SET FOREIGN_KEY_CHECKS")
400            || upper.contains("LOCK TABLES")
401            || upper.contains("UNLOCK TABLES")
402    }
403
404    /// Check if statement is a PostgreSQL session command or unsupported statement
405    fn is_postgres_session_command(&self, stmt: &str) -> bool {
406        let upper = stmt.to_uppercase();
407        // Session/transaction settings
408        upper.contains("SET CLIENT_ENCODING")
409            || upper.contains("SET STANDARD_CONFORMING_STRINGS")
410            || upper.contains("SET CHECK_FUNCTION_BODIES")
411            || upper.contains("SET SEARCH_PATH")
412            || upper.contains("SET DEFAULT_TABLESPACE")
413            || upper.contains("SET LOCK_TIMEOUT")
414            || upper.contains("SET IDLE_IN_TRANSACTION_SESSION_TIMEOUT")
415            || upper.contains("SET ROW_SECURITY")
416            || upper.contains("SET STATEMENT_TIMEOUT")
417            || upper.contains("SET XMLOPTION")
418            || upper.contains("SET CLIENT_MIN_MESSAGES")
419            || upper.contains("SET DEFAULT_TABLE_ACCESS_METHOD")
420            || upper.contains("SELECT PG_CATALOG")
421            // Ownership/permission statements
422            || upper.contains("OWNER TO")
423            || upper.contains("GRANT ")
424            || upper.contains("REVOKE ")
425    }
426
427    /// Check if statement is a PostgreSQL-only feature that should be skipped
428    fn is_postgres_only_feature(&self, stmt: &str) -> bool {
429        // Strip leading comments to find the actual statement
430        let stripped = self.strip_leading_sql_comments(stmt);
431        let upper = stripped.to_uppercase();
432
433        // These PostgreSQL features have no MySQL/SQLite equivalent
434        upper.starts_with("CREATE DOMAIN")
435            || upper.starts_with("CREATE TYPE")
436            || upper.starts_with("CREATE FUNCTION")
437            || upper.starts_with("CREATE PROCEDURE")
438            || upper.starts_with("CREATE AGGREGATE")
439            || upper.starts_with("CREATE OPERATOR")
440            || upper.starts_with("CREATE SEQUENCE")
441            || upper.starts_with("CREATE EXTENSION")
442            || upper.starts_with("CREATE SCHEMA")
443            || upper.starts_with("CREATE TRIGGER")
444            || upper.starts_with("ALTER DOMAIN")
445            || upper.starts_with("ALTER TYPE")
446            || upper.starts_with("ALTER FUNCTION")
447            || upper.starts_with("ALTER SEQUENCE")
448            || upper.starts_with("ALTER SCHEMA")
449            || upper.starts_with("COMMENT ON")
450    }
451
452    /// Strip leading SQL comments (-- and /* */) from a string
453    fn strip_leading_sql_comments(&self, stmt: &str) -> String {
454        let mut result = stmt.trim();
455        loop {
456            // Strip -- comments
457            if result.starts_with("--") {
458                if let Some(pos) = result.find('\n') {
459                    result = result[pos + 1..].trim();
460                    continue;
461                } else {
462                    return String::new();
463                }
464            }
465            // Strip /* */ comments
466            if result.starts_with("/*") {
467                if let Some(pos) = result.find("*/") {
468                    result = result[pos + 2..].trim();
469                    continue;
470                } else {
471                    return String::new();
472                }
473            }
474            break;
475        }
476        result.to_string()
477    }
478
479    /// Check if statement is a SQLite pragma
480    fn is_sqlite_pragma(&self, stmt: &str) -> bool {
481        let upper = stmt.to_uppercase();
482        upper.contains("PRAGMA")
483    }
484
485    /// Check if statement is an MSSQL session command
486    fn is_mssql_session_command(&self, stmt: &str) -> bool {
487        let upper = stmt.to_uppercase();
488        upper.contains("SET ANSI_NULLS")
489            || upper.contains("SET QUOTED_IDENTIFIER")
490            || upper.contains("SET NOCOUNT")
491            || upper.contains("SET XACT_ABORT")
492            || upper.contains("SET ARITHABORT")
493            || upper.contains("SET ANSI_WARNINGS")
494            || upper.contains("SET ANSI_PADDING")
495            || upper.contains("SET CONCAT_NULL_YIELDS_NULL")
496            || upper.contains("SET NUMERIC_ROUNDABORT")
497            || upper.contains("SET IDENTITY_INSERT")
498    }
499
500    /// Convert identifier quoting based on dialects
501    fn convert_identifiers(&self, stmt: &str) -> String {
502        match (self.from, self.to) {
503            (SqlDialect::MySql, SqlDialect::Postgres | SqlDialect::Sqlite) => {
504                // Backticks → double quotes
505                self.backticks_to_double_quotes(stmt)
506            }
507            (SqlDialect::MySql, SqlDialect::Mssql) => {
508                // Backticks → square brackets
509                self.backticks_to_square_brackets(stmt)
510            }
511            (SqlDialect::Postgres | SqlDialect::Sqlite, SqlDialect::MySql) => {
512                // Double quotes → backticks
513                self.double_quotes_to_backticks(stmt)
514            }
515            (SqlDialect::Postgres | SqlDialect::Sqlite, SqlDialect::Mssql) => {
516                // Double quotes → square brackets
517                self.double_quotes_to_square_brackets(stmt)
518            }
519            (SqlDialect::Mssql, SqlDialect::MySql) => {
520                // Square brackets → backticks
521                self.square_brackets_to_backticks(stmt)
522            }
523            (SqlDialect::Mssql, SqlDialect::Postgres | SqlDialect::Sqlite) => {
524                // Square brackets → double quotes
525                self.square_brackets_to_double_quotes(stmt)
526            }
527            _ => stmt.to_string(),
528        }
529    }
530
531    /// Convert backticks to double quotes
532    pub fn backticks_to_double_quotes(&self, stmt: &str) -> String {
533        let mut result = String::with_capacity(stmt.len());
534        let mut in_string = false;
535        let mut in_backtick = false;
536
537        for c in stmt.chars() {
538            if c == '\'' && !in_backtick {
539                in_string = !in_string;
540                result.push(c);
541            } else if c == '`' && !in_string {
542                in_backtick = !in_backtick;
543                result.push('"');
544            } else {
545                result.push(c);
546            }
547        }
548        result
549    }
550
551    /// Convert double quotes to backticks
552    pub fn double_quotes_to_backticks(&self, stmt: &str) -> String {
553        let mut result = String::with_capacity(stmt.len());
554        let mut in_string = false;
555        let mut in_dquote = false;
556        let chars = stmt.chars();
557
558        for c in chars {
559            if c == '\'' && !in_dquote {
560                in_string = !in_string;
561                result.push(c);
562            } else if c == '"' && !in_string {
563                in_dquote = !in_dquote;
564                result.push('`');
565            } else {
566                result.push(c);
567            }
568        }
569        result
570    }
571
572    /// Convert backticks to square brackets (for MSSQL)
573    pub fn backticks_to_square_brackets(&self, stmt: &str) -> String {
574        let mut result = String::with_capacity(stmt.len());
575        let mut in_string = false;
576        let mut in_backtick = false;
577
578        for c in stmt.chars() {
579            if c == '\'' && !in_backtick {
580                in_string = !in_string;
581                result.push(c);
582            } else if c == '`' && !in_string {
583                if !in_backtick {
584                    result.push('[');
585                } else {
586                    result.push(']');
587                }
588                in_backtick = !in_backtick;
589            } else {
590                result.push(c);
591            }
592        }
593        result
594    }
595
596    /// Convert double quotes to square brackets (for MSSQL)
597    pub fn double_quotes_to_square_brackets(&self, stmt: &str) -> String {
598        let mut result = String::with_capacity(stmt.len());
599        let mut in_string = false;
600        let mut in_dquote = false;
601
602        for c in stmt.chars() {
603            if c == '\'' && !in_dquote {
604                in_string = !in_string;
605                result.push(c);
606            } else if c == '"' && !in_string {
607                if !in_dquote {
608                    result.push('[');
609                } else {
610                    result.push(']');
611                }
612                in_dquote = !in_dquote;
613            } else {
614                result.push(c);
615            }
616        }
617        result
618    }
619
620    /// Convert square brackets to backticks (from MSSQL to MySQL)
621    pub fn square_brackets_to_backticks(&self, stmt: &str) -> String {
622        let mut result = String::with_capacity(stmt.len());
623        let mut in_string = false;
624
625        for c in stmt.chars() {
626            if c == '\'' {
627                in_string = !in_string;
628                result.push(c);
629            } else if !in_string && (c == '[' || c == ']') {
630                result.push('`');
631            } else {
632                result.push(c);
633            }
634        }
635        result
636    }
637
638    /// Convert square brackets to double quotes (from MSSQL to PostgreSQL/SQLite)
639    pub fn square_brackets_to_double_quotes(&self, stmt: &str) -> String {
640        let mut result = String::with_capacity(stmt.len());
641        let mut in_string = false;
642
643        for c in stmt.chars() {
644            if c == '\'' {
645                in_string = !in_string;
646                result.push(c);
647            } else if !in_string && (c == '[' || c == ']') {
648                result.push('"');
649            } else {
650                result.push(c);
651            }
652        }
653        result
654    }
655
656    /// Convert data types between dialects
657    fn convert_data_types(&self, stmt: &str) -> String {
658        TypeMapper::convert(stmt, self.from, self.to)
659    }
660
661    /// Convert AUTO_INCREMENT/SERIAL syntax
662    fn convert_auto_increment(&self, stmt: &str, _table_name: Option<&str>) -> String {
663        // Strip the MySQL table-level `AUTO_INCREMENT=N` option first (distinct from
664        // the column-level `AUTO_INCREMENT` keyword handled below). Otherwise the
665        // column-level replacements below strip the word "AUTO_INCREMENT" and leave
666        // a dangling "=N" behind, e.g. `) ENGINE=InnoDB AUTO_INCREMENT=2 ...` becomes
667        // `) =2 ...`. See https://github.com/HelgeSverre/sql-splitter/issues/64
668        let stmt = if self.from == SqlDialect::MySql && self.to != SqlDialect::MySql {
669            self.strip_mysql_auto_increment_table_option(stmt)
670        } else {
671            stmt.to_string()
672        };
673        let stmt = stmt.as_str();
674
675        match (self.from, self.to) {
676            (SqlDialect::MySql, SqlDialect::Postgres) => {
677                // INT AUTO_INCREMENT → SERIAL, BIGINT AUTO_INCREMENT → BIGSERIAL,
678                // case-insensitive (MySQL dumps commonly use lowercase
679                // `auto_increment`) and string-literal-aware (a DEFAULT value or
680                // CHECK expression containing the literal text "AUTO_INCREMENT"
681                // must not be touched).
682                self.convert_mysql_auto_increment_keyword(stmt)
683            }
684            (SqlDialect::MySql, SqlDialect::Sqlite) => {
685                // INT AUTO_INCREMENT PRIMARY KEY → INTEGER PRIMARY KEY
686                // The AUTOINCREMENT keyword is optional in SQLite
687                let result = stmt.replace("INT AUTO_INCREMENT", "INTEGER");
688                let result = result.replace("int AUTO_INCREMENT", "INTEGER");
689                result.replace("AUTO_INCREMENT", "")
690            }
691            (SqlDialect::Postgres, SqlDialect::MySql) => {
692                // SERIAL → INT AUTO_INCREMENT
693                // BIGSERIAL → BIGINT AUTO_INCREMENT
694                let result = stmt.replace("BIGSERIAL", "BIGINT AUTO_INCREMENT");
695                let result = result.replace("bigserial", "BIGINT AUTO_INCREMENT");
696                let result = result.replace("SMALLSERIAL", "SMALLINT AUTO_INCREMENT");
697                let result = result.replace("smallserial", "SMALLINT AUTO_INCREMENT");
698                let result = result.replace("SERIAL", "INT AUTO_INCREMENT");
699                result.replace("serial", "INT AUTO_INCREMENT")
700            }
701            (SqlDialect::Postgres, SqlDialect::Sqlite) => {
702                // SERIAL → INTEGER (SQLite auto-increments INTEGER PRIMARY KEY)
703                let result = stmt.replace("BIGSERIAL", "INTEGER");
704                let result = result.replace("bigserial", "INTEGER");
705                let result = result.replace("SMALLSERIAL", "INTEGER");
706                let result = result.replace("smallserial", "INTEGER");
707                let result = result.replace("SERIAL", "INTEGER");
708                result.replace("serial", "INTEGER")
709            }
710            (SqlDialect::Sqlite, SqlDialect::MySql) => {
711                // SQLite uses INTEGER PRIMARY KEY for auto-increment
712                // We can't easily detect this pattern, so just pass through
713                stmt.to_string()
714            }
715            (SqlDialect::Sqlite, SqlDialect::Postgres) => {
716                // SQLite uses INTEGER PRIMARY KEY for auto-increment
717                // We can't easily detect this pattern, so just pass through
718                stmt.to_string()
719            }
720            // MSSQL conversions
721            (SqlDialect::MySql, SqlDialect::Mssql) => {
722                // AUTO_INCREMENT → IDENTITY(1,1)
723                let result = stmt.replace("BIGINT AUTO_INCREMENT", "BIGINT IDENTITY(1,1)");
724                let result = result.replace("bigint AUTO_INCREMENT", "BIGINT IDENTITY(1,1)");
725                let result = result.replace("INT AUTO_INCREMENT", "INT IDENTITY(1,1)");
726                let result = result.replace("int AUTO_INCREMENT", "INT IDENTITY(1,1)");
727                result.replace("AUTO_INCREMENT", "IDENTITY(1,1)")
728            }
729            (SqlDialect::Mssql, SqlDialect::MySql) => {
730                // IDENTITY(1,1) → AUTO_INCREMENT
731                self.convert_identity_to_auto_increment(stmt)
732            }
733            (SqlDialect::Postgres, SqlDialect::Mssql) => {
734                // SERIAL → INT IDENTITY(1,1) (handled by type mapper)
735                stmt.to_string()
736            }
737            (SqlDialect::Mssql, SqlDialect::Postgres) => {
738                // IDENTITY(1,1) → SERIAL (need to add SERIAL instead)
739                self.convert_identity_to_serial(stmt)
740            }
741            (SqlDialect::Sqlite, SqlDialect::Mssql) => {
742                // SQLite → MSSQL: pass through
743                stmt.to_string()
744            }
745            (SqlDialect::Mssql, SqlDialect::Sqlite) => {
746                // IDENTITY → strip (SQLite uses INTEGER PRIMARY KEY)
747                self.strip_identity(stmt)
748            }
749            _ => stmt.to_string(),
750        }
751    }
752
753    /// Convert MSSQL IDENTITY to MySQL AUTO_INCREMENT
754    fn convert_identity_to_auto_increment(&self, stmt: &str) -> String {
755        use once_cell::sync::Lazy;
756        use regex::Regex;
757
758        static RE_IDENTITY: Lazy<Regex> =
759            Lazy::new(|| Regex::new(r"(?i)\bIDENTITY\s*\(\s*\d+\s*,\s*\d+\s*\)").unwrap());
760
761        RE_IDENTITY.replace_all(stmt, "AUTO_INCREMENT").to_string()
762    }
763
764    /// Convert MSSQL IDENTITY to PostgreSQL SERIAL
765    fn convert_identity_to_serial(&self, stmt: &str) -> String {
766        use once_cell::sync::Lazy;
767        use regex::Regex;
768
769        // Match INT IDENTITY(1,1) and replace with SERIAL
770        static RE_BIGINT_IDENTITY: Lazy<Regex> =
771            Lazy::new(|| Regex::new(r"(?i)\bBIGINT\s+IDENTITY\s*\(\s*\d+\s*,\s*\d+\s*\)").unwrap());
772        static RE_INT_IDENTITY: Lazy<Regex> =
773            Lazy::new(|| Regex::new(r"(?i)\bINT\s+IDENTITY\s*\(\s*\d+\s*,\s*\d+\s*\)").unwrap());
774        static RE_SMALLINT_IDENTITY: Lazy<Regex> = Lazy::new(|| {
775            Regex::new(r"(?i)\bSMALLINT\s+IDENTITY\s*\(\s*\d+\s*,\s*\d+\s*\)").unwrap()
776        });
777
778        let result = RE_BIGINT_IDENTITY
779            .replace_all(stmt, "BIGSERIAL")
780            .to_string();
781        let result = RE_INT_IDENTITY.replace_all(&result, "SERIAL").to_string();
782        RE_SMALLINT_IDENTITY
783            .replace_all(&result, "SMALLSERIAL")
784            .to_string()
785    }
786
787    /// Strip MSSQL IDENTITY clause for SQLite
788    fn strip_identity(&self, stmt: &str) -> String {
789        use once_cell::sync::Lazy;
790        use regex::Regex;
791
792        static RE_IDENTITY: Lazy<Regex> =
793            Lazy::new(|| Regex::new(r"(?i)\s*IDENTITY\s*\(\s*\d+\s*,\s*\d+\s*\)").unwrap());
794
795        RE_IDENTITY.replace_all(stmt, "").to_string()
796    }
797
798    /// Convert string escape sequences
799    fn convert_string_escapes(&self, stmt: &str) -> String {
800        match (self.from, self.to) {
801            (SqlDialect::MySql, SqlDialect::Postgres | SqlDialect::Sqlite) => {
802                // MySQL uses \' for escaping, PostgreSQL/SQLite use ''
803                self.mysql_escapes_to_standard(stmt)
804            }
805            _ => stmt.to_string(),
806        }
807    }
808
809    /// Convert MySQL backslash escapes to standard SQL double-quote escapes
810    fn mysql_escapes_to_standard(&self, stmt: &str) -> String {
811        let mut result = String::with_capacity(stmt.len());
812        let mut chars = stmt.chars().peekable();
813        let mut in_string = false;
814
815        while let Some(c) = chars.next() {
816            if c == '\'' {
817                in_string = !in_string;
818                result.push(c);
819            } else if c == '\\' && in_string {
820                // Check next character
821                if let Some(&next) = chars.peek() {
822                    match next {
823                        '\'' => {
824                            // \' → ''
825                            chars.next();
826                            result.push_str("''");
827                        }
828                        '\\' => {
829                            // \\ → keep as-is for data integrity
830                            chars.next();
831                            result.push_str("\\\\");
832                        }
833                        'n' | 'r' | 't' | '0' => {
834                            // Keep common escapes as-is
835                            result.push(c);
836                        }
837                        _ => {
838                            result.push(c);
839                        }
840                    }
841                } else {
842                    result.push(c);
843                }
844            } else {
845                result.push(c);
846            }
847        }
848        result
849    }
850
851    /// Strip MySQL conditional comments /*!40101 ... */
852    fn strip_conditional_comments(&self, stmt: &str) -> String {
853        let mut result = String::with_capacity(stmt.len());
854        let mut chars = stmt.chars().peekable();
855
856        while let Some(c) = chars.next() {
857            if c == '/' && chars.peek() == Some(&'*') {
858                chars.next(); // consume *
859                if chars.peek() == Some(&'!') {
860                    // Skip conditional comment
861                    chars.next(); // consume !
862                                  // Skip version number
863                    while chars.peek().map(|c| c.is_ascii_digit()).unwrap_or(false) {
864                        chars.next();
865                    }
866                    // Skip content until */
867                    let mut depth = 1;
868                    while depth > 0 {
869                        match chars.next() {
870                            Some('*') if chars.peek() == Some(&'/') => {
871                                chars.next();
872                                depth -= 1;
873                            }
874                            Some('/') if chars.peek() == Some(&'*') => {
875                                chars.next();
876                                depth += 1;
877                            }
878                            None => break,
879                            _ => {}
880                        }
881                    }
882                } else {
883                    // Regular comment, keep it
884                    result.push('/');
885                    result.push('*');
886                }
887            } else {
888                result.push(c);
889            }
890        }
891        result
892    }
893
894    /// Strip ENGINE clause
895    fn strip_engine_clause(&self, stmt: &str) -> String {
896        use once_cell::sync::Lazy;
897        use regex::Regex;
898
899        if self.to == SqlDialect::MySql {
900            return stmt.to_string();
901        }
902
903        // Remove ENGINE=InnoDB, ENGINE=MyISAM, etc.
904        static RE_ENGINE: Lazy<Regex> =
905            Lazy::new(|| Regex::new(r"(?i)\s*ENGINE\s*=\s*\w+").unwrap());
906        RE_ENGINE.replace_all(stmt, "").to_string()
907    }
908
909    /// Strip CHARSET/COLLATE clauses
910    fn strip_charset_clauses(&self, stmt: &str) -> String {
911        use once_cell::sync::Lazy;
912        use regex::Regex;
913
914        if self.to == SqlDialect::MySql {
915            return stmt.to_string();
916        }
917
918        static RE_CHARSET: Lazy<Regex> =
919            Lazy::new(|| Regex::new(r"(?i)\s*(DEFAULT\s+)?CHARSET\s*=\s*\w+").unwrap());
920        static RE_COLLATE: Lazy<Regex> =
921            Lazy::new(|| Regex::new(r"(?i)\s*COLLATE\s*=?\s*\w+").unwrap());
922
923        let result = RE_CHARSET.replace_all(stmt, "").to_string();
924        RE_COLLATE.replace_all(&result, "").to_string()
925    }
926
927    /// Case-insensitively checks whether `keyword` starts at `chars[pos]`, with
928    /// word boundaries on both sides (so e.g. "COMMENT" doesn't match inside
929    /// "COMMENTARY" or a preceding identifier char like "XCOMMENT"). Returns the
930    /// index just past the keyword on success.
931    fn match_keyword_ci(chars: &[char], pos: usize, keyword: &str) -> Option<usize> {
932        let kw_len = keyword.len();
933        if pos > 0 && (chars[pos - 1].is_alphanumeric() || chars[pos - 1] == '_') {
934            return None;
935        }
936        let end = pos + kw_len;
937        if end > chars.len() {
938            return None;
939        }
940        let candidate: String = chars[pos..end].iter().collect();
941        if !candidate.eq_ignore_ascii_case(keyword) {
942            return None;
943        }
944        if end < chars.len() && (chars[end].is_alphanumeric() || chars[end] == '_') {
945            return None;
946        }
947        Some(end)
948    }
949
950    /// Removes trailing whitespace already pushed into `result`, so that stripping
951    /// a clause also absorbs the whitespace that preceded it (matching the old
952    /// `\s*<keyword>...` regex behavior).
953    fn trim_trailing_whitespace(result: &mut String) {
954        while result.ends_with(|c: char| c.is_whitespace()) {
955            result.pop();
956        }
957    }
958
959    /// Strip MySQL table-level `AUTO_INCREMENT=N` option. String-literal-aware so
960    /// that a DEFAULT value or other string content containing the literal text
961    /// "AUTO_INCREMENT=N" is left untouched.
962    /// See https://github.com/HelgeSverre/sql-splitter/issues/64
963    fn strip_mysql_auto_increment_table_option(&self, stmt: &str) -> String {
964        let chars: Vec<char> = stmt.chars().collect();
965        let n = chars.len();
966        let mut result = String::with_capacity(stmt.len());
967        let mut in_string = false;
968        let mut i = 0;
969
970        while i < n {
971            let c = chars[i];
972            if c == '\'' {
973                in_string = !in_string;
974                result.push(c);
975                i += 1;
976                continue;
977            }
978            if !in_string {
979                if let Some(after_kw) = Self::match_keyword_ci(&chars, i, "AUTO_INCREMENT") {
980                    let mut j = after_kw;
981                    while j < n && chars[j].is_whitespace() {
982                        j += 1;
983                    }
984                    if j < n && chars[j] == '=' {
985                        j += 1;
986                        while j < n && chars[j].is_whitespace() {
987                            j += 1;
988                        }
989                        let digits_start = j;
990                        while j < n && chars[j].is_ascii_digit() {
991                            j += 1;
992                        }
993                        if j > digits_start {
994                            Self::trim_trailing_whitespace(&mut result);
995                            i = j;
996                            continue;
997                        }
998                    }
999                }
1000            }
1001            result.push(c);
1002            i += 1;
1003        }
1004        result
1005    }
1006
1007    /// Strip MySQL column/table `COMMENT 'text'` (or `COMMENT='text'`) annotations.
1008    /// Neither is valid inside a PostgreSQL column definition or as a CREATE TABLE
1009    /// table option, so they are removed entirely rather than translated.
1010    /// String-literal-aware: only matches a real `COMMENT` clause, never the word
1011    /// "comment" sitting inside an unrelated DEFAULT value or CHECK expression.
1012    fn strip_mysql_comment_clauses(&self, stmt: &str) -> String {
1013        if self.to == SqlDialect::MySql {
1014            return stmt.to_string();
1015        }
1016
1017        let chars: Vec<char> = stmt.chars().collect();
1018        let n = chars.len();
1019        let mut result = String::with_capacity(stmt.len());
1020        let mut in_string = false;
1021        let mut i = 0;
1022
1023        while i < n {
1024            let c = chars[i];
1025            if c == '\'' {
1026                in_string = !in_string;
1027                result.push(c);
1028                i += 1;
1029                continue;
1030            }
1031            if !in_string {
1032                if let Some(after_kw) = Self::match_keyword_ci(&chars, i, "COMMENT") {
1033                    let mut j = after_kw;
1034                    while j < n && chars[j].is_whitespace() {
1035                        j += 1;
1036                    }
1037                    if j < n && chars[j] == '=' {
1038                        j += 1;
1039                        while j < n && chars[j].is_whitespace() {
1040                            j += 1;
1041                        }
1042                    }
1043                    if j < n && chars[j] == '\'' {
1044                        // Consume the quoted comment text itself, honoring ''
1045                        // as an escaped quote, then drop the whole clause.
1046                        j += 1;
1047                        loop {
1048                            if j >= n {
1049                                break;
1050                            }
1051                            if chars[j] == '\'' {
1052                                if j + 1 < n && chars[j + 1] == '\'' {
1053                                    j += 2;
1054                                    continue;
1055                                }
1056                                j += 1;
1057                                break;
1058                            }
1059                            j += 1;
1060                        }
1061                        Self::trim_trailing_whitespace(&mut result);
1062                        i = j;
1063                        continue;
1064                    }
1065                }
1066            }
1067            result.push(c);
1068            i += 1;
1069        }
1070        result
1071    }
1072
1073    /// Convert MySQL's column-level `AUTO_INCREMENT` keyword to PostgreSQL's
1074    /// `SERIAL`/`BIGSERIAL`, case-insensitively and string-literal-aware (a
1075    /// DEFAULT value or CHECK expression containing the literal text
1076    /// "AUTO_INCREMENT" must not be touched — see finding in issue #64 follow-up
1077    /// review).
1078    fn convert_mysql_auto_increment_keyword(&self, stmt: &str) -> String {
1079        let chars: Vec<char> = stmt.chars().collect();
1080        let n = chars.len();
1081        let mut result = String::with_capacity(stmt.len());
1082        let mut in_string = false;
1083        let mut i = 0;
1084
1085        while i < n {
1086            let c = chars[i];
1087            if c == '\'' {
1088                in_string = !in_string;
1089                result.push(c);
1090                i += 1;
1091                continue;
1092            }
1093            if !in_string {
1094                if let Some(after_type) = Self::match_keyword_ci(&chars, i, "BIGINT") {
1095                    let mut j = after_type;
1096                    while j < n && chars[j].is_whitespace() {
1097                        j += 1;
1098                    }
1099                    if let Some(end) = Self::match_keyword_ci(&chars, j, "AUTO_INCREMENT") {
1100                        result.push_str("BIGSERIAL");
1101                        i = end;
1102                        continue;
1103                    }
1104                }
1105                if let Some(after_type) = Self::match_keyword_ci(&chars, i, "INT") {
1106                    let mut j = after_type;
1107                    while j < n && chars[j].is_whitespace() {
1108                        j += 1;
1109                    }
1110                    if let Some(end) = Self::match_keyword_ci(&chars, j, "AUTO_INCREMENT") {
1111                        result.push_str("SERIAL");
1112                        i = end;
1113                        continue;
1114                    }
1115                }
1116                if let Some(end) = Self::match_keyword_ci(&chars, i, "AUTO_INCREMENT") {
1117                    // Clean up any remaining standalone occurrence (e.g. when
1118                    // other modifiers like NOT NULL sit between the type and
1119                    // the keyword).
1120                    i = end;
1121                    continue;
1122                }
1123            }
1124            result.push(c);
1125            i += 1;
1126        }
1127        result
1128    }
1129
1130    /// Convert MySQL `UNIQUE KEY [name] (cols) [USING BTREE|HASH]` table constraint
1131    /// to standard `UNIQUE (cols)`, which is the closest PostgreSQL equivalent.
1132    /// Also strips MySQL prefix-length index annotations (e.g. `email(191)`),
1133    /// which have no PostgreSQL equivalent and aren't valid there.
1134    fn convert_unique_key_constraint(&self, stmt: &str) -> String {
1135        use once_cell::sync::Lazy;
1136        use regex::{Captures, Regex};
1137
1138        if self.to == SqlDialect::MySql {
1139            return stmt.to_string();
1140        }
1141
1142        // The column-list group allows one level of nested `(digits)` prefix-length
1143        // annotations (e.g. `("email"(191),"other")`), which are common in
1144        // real-world MySQL dumps using utf8mb4 prefix indexes.
1145        static RE: Lazy<Regex> = Lazy::new(|| {
1146            Regex::new(
1147                r#"(?i)UNIQUE\s+KEY\s+(?:"[^"]*"\s+)?(\([^()]*(?:\(\d+\)[^()]*)*\))(?:\s*USING\s+(?:BTREE|HASH))?"#,
1148            )
1149            .unwrap()
1150        });
1151        static RE_PREFIX_LEN: Lazy<Regex> = Lazy::new(|| Regex::new(r"\(\d+\)").unwrap());
1152
1153        RE.replace_all(stmt, |caps: &Captures| {
1154            let cols = RE_PREFIX_LEN.replace_all(&caps[1], "");
1155            format!("UNIQUE {}", cols)
1156        })
1157        .to_string()
1158    }
1159
1160    /// Strip PostgreSQL type casts (::type and ::regclass)
1161    fn strip_postgres_casts(&self, stmt: &str) -> String {
1162        use once_cell::sync::Lazy;
1163        use regex::Regex;
1164
1165        // Match ::regclass, ::text, ::integer, etc. (including complex types like character varying)
1166        static RE_CAST: Lazy<Regex> = Lazy::new(|| {
1167            Regex::new(r"::[a-zA-Z_][a-zA-Z0-9_]*(?:\s+[a-zA-Z_][a-zA-Z0-9_]*)*").unwrap()
1168        });
1169
1170        RE_CAST.replace_all(stmt, "").to_string()
1171    }
1172
1173    /// Convert nextval('sequence') to NULL or remove (AUTO_INCREMENT handles it)
1174    fn convert_nextval(&self, stmt: &str) -> String {
1175        use once_cell::sync::Lazy;
1176        use regex::Regex;
1177
1178        // Match nextval('sequence_name'::regclass) or nextval('sequence_name')
1179        // Remove the DEFAULT nextval(...) entirely - AUTO_INCREMENT is already applied
1180        static RE_NEXTVAL: Lazy<Regex> =
1181            Lazy::new(|| Regex::new(r"(?i)\s*DEFAULT\s+nextval\s*\([^)]+\)").unwrap());
1182
1183        RE_NEXTVAL.replace_all(stmt, "").to_string()
1184    }
1185
1186    /// Convert DEFAULT now() to DEFAULT CURRENT_TIMESTAMP
1187    fn convert_default_now(&self, stmt: &str) -> String {
1188        use once_cell::sync::Lazy;
1189        use regex::Regex;
1190
1191        static RE_NOW: Lazy<Regex> =
1192            Lazy::new(|| Regex::new(r"(?i)\bDEFAULT\s+now\s*\(\s*\)").unwrap());
1193
1194        RE_NOW
1195            .replace_all(stmt, "DEFAULT CURRENT_TIMESTAMP")
1196            .to_string()
1197    }
1198
1199    /// Strip schema prefix from table names (e.g., public.users -> users)
1200    fn strip_schema_prefix(&self, stmt: &str) -> String {
1201        use once_cell::sync::Lazy;
1202        use regex::Regex;
1203
1204        // Match schema.table patterns (with optional quotes)
1205        // Handle: public.table, "public"."table", public."table"
1206        static RE_SCHEMA: Lazy<Regex> =
1207            Lazy::new(|| Regex::new(r#"(?i)\b(public|pg_catalog|pg_temp)\s*\.\s*"#).unwrap());
1208
1209        RE_SCHEMA.replace_all(stmt, "").to_string()
1210    }
1211
1212    /// Convert MSSQL GETDATE() to CURRENT_TIMESTAMP
1213    fn convert_mssql_getdate(&self, stmt: &str) -> String {
1214        use once_cell::sync::Lazy;
1215        use regex::Regex;
1216
1217        static RE_GETDATE: Lazy<Regex> =
1218            Lazy::new(|| Regex::new(r"(?i)\bGETDATE\s*\(\s*\)").unwrap());
1219        static RE_SYSDATETIME: Lazy<Regex> =
1220            Lazy::new(|| Regex::new(r"(?i)\bSYSDATETIME\s*\(\s*\)").unwrap());
1221        static RE_GETUTCDATE: Lazy<Regex> =
1222            Lazy::new(|| Regex::new(r"(?i)\bGETUTCDATE\s*\(\s*\)").unwrap());
1223
1224        let result = RE_GETDATE
1225            .replace_all(stmt, "CURRENT_TIMESTAMP")
1226            .to_string();
1227        let result = RE_SYSDATETIME
1228            .replace_all(&result, "CURRENT_TIMESTAMP")
1229            .to_string();
1230        RE_GETUTCDATE
1231            .replace_all(&result, "CURRENT_TIMESTAMP")
1232            .to_string()
1233    }
1234
1235    /// Strip MSSQL ON [filegroup] clause
1236    fn strip_mssql_on_filegroup(&self, stmt: &str) -> String {
1237        use once_cell::sync::Lazy;
1238        use regex::Regex;
1239
1240        // Match ON [PRIMARY] or ON [filegroup_name]
1241        static RE_ON_FILEGROUP: Lazy<Regex> =
1242            Lazy::new(|| Regex::new(r"(?i)\s+ON\s*\[\s*\w+\s*\]").unwrap());
1243
1244        RE_ON_FILEGROUP.replace_all(stmt, "").to_string()
1245    }
1246
1247    /// Strip MSSQL CLUSTERED/NONCLUSTERED keywords
1248    fn strip_mssql_clustered(&self, stmt: &str) -> String {
1249        use once_cell::sync::Lazy;
1250        use regex::Regex;
1251
1252        static RE_CLUSTERED: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bCLUSTERED\s+").unwrap());
1253        static RE_NONCLUSTERED: Lazy<Regex> =
1254            Lazy::new(|| Regex::new(r"(?i)\bNONCLUSTERED\s+").unwrap());
1255
1256        let result = RE_CLUSTERED.replace_all(stmt, "").to_string();
1257        RE_NONCLUSTERED.replace_all(&result, "").to_string()
1258    }
1259
1260    /// Convert MSSQL N'unicode' strings to regular 'unicode' strings
1261    fn convert_mssql_unicode_strings(&self, stmt: &str) -> String {
1262        use once_cell::sync::Lazy;
1263        use regex::Regex;
1264
1265        // Match N'...' unicode strings, being careful not to match inside strings
1266        // This is a simplified version that handles most cases
1267        static RE_UNICODE_STRING: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bN'").unwrap());
1268
1269        RE_UNICODE_STRING.replace_all(stmt, "'").to_string()
1270    }
1271
1272    /// Strip MSSQL schema prefix (dbo., etc.) from table names
1273    fn strip_mssql_schema_prefix(&self, stmt: &str) -> String {
1274        use once_cell::sync::Lazy;
1275        use regex::Regex;
1276
1277        // Match [dbo].[table] or dbo.table and keep just [table] or table
1278        // We replace schema.table with just table, handling both bracketed and unbracketed forms
1279        static RE_MSSQL_SCHEMA: Lazy<Regex> =
1280            Lazy::new(|| Regex::new(r"(?i)\[?dbo\]?\s*\.\s*").unwrap());
1281
1282        RE_MSSQL_SCHEMA.replace_all(stmt, "").to_string()
1283    }
1284
1285    /// Detect unsupported features and add warnings
1286    fn detect_unsupported_features(
1287        &mut self,
1288        stmt: &str,
1289        table_name: Option<&str>,
1290    ) -> Result<(), ConvertWarning> {
1291        let upper = stmt.to_uppercase();
1292
1293        // MySQL-specific features
1294        if self.from == SqlDialect::MySql {
1295            // ENUM types
1296            if upper.contains("ENUM(") {
1297                let warning = ConvertWarning::UnsupportedFeature {
1298                    feature: format!(
1299                        "ENUM type{}",
1300                        table_name
1301                            .map(|t| format!(" in table {}", t))
1302                            .unwrap_or_default()
1303                    ),
1304                    suggestion: Some(
1305                        "Converted to VARCHAR - consider adding CHECK constraint".to_string(),
1306                    ),
1307                };
1308                self.warnings.add(warning.clone());
1309                if self.strict {
1310                    return Err(warning);
1311                }
1312            }
1313
1314            // SET types (MySQL)
1315            if upper.contains("SET(") {
1316                let warning = ConvertWarning::UnsupportedFeature {
1317                    feature: format!(
1318                        "SET type{}",
1319                        table_name
1320                            .map(|t| format!(" in table {}", t))
1321                            .unwrap_or_default()
1322                    ),
1323                    suggestion: Some(
1324                        "Converted to VARCHAR - SET semantics not preserved".to_string(),
1325                    ),
1326                };
1327                self.warnings.add(warning.clone());
1328                if self.strict {
1329                    return Err(warning);
1330                }
1331            }
1332
1333            // UNSIGNED
1334            if upper.contains("UNSIGNED") {
1335                self.warnings.add(ConvertWarning::UnsupportedFeature {
1336                    feature: "UNSIGNED modifier".to_string(),
1337                    suggestion: Some(
1338                        "Removed - consider adding CHECK constraint for non-negative values"
1339                            .to_string(),
1340                    ),
1341                });
1342            }
1343        }
1344
1345        // PostgreSQL-specific features
1346        if self.from == SqlDialect::Postgres {
1347            // Array types
1348            if upper.contains("[]") || upper.contains("ARRAY[") {
1349                let warning = ConvertWarning::UnsupportedFeature {
1350                    feature: format!(
1351                        "Array type{}",
1352                        table_name
1353                            .map(|t| format!(" in table {}", t))
1354                            .unwrap_or_default()
1355                    ),
1356                    suggestion: Some(
1357                        "Array types not supported in target dialect - consider using JSON"
1358                            .to_string(),
1359                    ),
1360                };
1361                self.warnings.add(warning.clone());
1362                if self.strict {
1363                    return Err(warning);
1364                }
1365            }
1366
1367            // INHERITS
1368            if upper.contains("INHERITS") {
1369                let warning = ConvertWarning::UnsupportedFeature {
1370                    feature: "Table inheritance (INHERITS)".to_string(),
1371                    suggestion: Some(
1372                        "PostgreSQL table inheritance not supported in target dialect".to_string(),
1373                    ),
1374                };
1375                self.warnings.add(warning.clone());
1376                if self.strict {
1377                    return Err(warning);
1378                }
1379            }
1380
1381            // PARTITION BY
1382            if upper.contains("PARTITION BY") && self.to == SqlDialect::Sqlite {
1383                let warning = ConvertWarning::UnsupportedFeature {
1384                    feature: "Table partitioning".to_string(),
1385                    suggestion: Some("Partitioning not supported in SQLite".to_string()),
1386                };
1387                self.warnings.add(warning.clone());
1388                if self.strict {
1389                    return Err(warning);
1390                }
1391            }
1392        }
1393
1394        Ok(())
1395    }
1396
1397    /// Get collected warnings
1398    pub fn warnings(&self) -> &[ConvertWarning] {
1399        self.warnings.warnings()
1400    }
1401}
1402
1403/// Run the convert command
1404pub fn run(config: ConvertConfig) -> anyhow::Result<ConvertStats> {
1405    let mut stats = ConvertStats::default();
1406
1407    // Detect or use specified source dialect
1408    let from_dialect = if let Some(d) = config.from_dialect {
1409        d
1410    } else {
1411        let result = crate::parser::detect_dialect_from_file(&config.input)?;
1412        if config.progress {
1413            eprintln!(
1414                "Auto-detected source dialect: {} (confidence: {:?})",
1415                result.dialect, result.confidence
1416            );
1417        }
1418        result.dialect
1419    };
1420
1421    // Check for same dialect
1422    if from_dialect == config.to_dialect {
1423        anyhow::bail!(
1424            "Source and target dialects are the same ({}). No conversion needed.",
1425            from_dialect
1426        );
1427    }
1428
1429    // Get file size for progress tracking
1430    let file_size = std::fs::metadata(&config.input)?.len();
1431
1432    let progress_bar = if config.progress {
1433        let pb = ProgressBar::new(file_size);
1434        pb.set_style(
1435            ProgressStyle::with_template(
1436                "{spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] {bytes}/{total_bytes} ({percent}%) {msg}",
1437            )
1438            .unwrap()
1439            .progress_chars("█▓▒░  ")
1440            .tick_chars("⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"),
1441        );
1442        pb.enable_steady_tick(std::time::Duration::from_millis(100));
1443        pb.set_message("Converting...");
1444        Some(pb)
1445    } else {
1446        None
1447    };
1448
1449    // Create converter
1450    let mut converter = Converter::new(from_dialect, config.to_dialect).with_strict(config.strict);
1451
1452    // Open input file with optional progress tracking
1453    let file = File::open(&config.input)?;
1454    let compression = Compression::from_path(&config.input);
1455    let reader: Box<dyn Read> = if let Some(ref pb) = progress_bar {
1456        let pb_clone = pb.clone();
1457        let progress_reader = ProgressReader::new(file, move |bytes| {
1458            pb_clone.set_position(bytes);
1459        });
1460        compression.wrap_reader(Box::new(progress_reader))?
1461    } else {
1462        compression.wrap_reader(Box::new(file))?
1463    };
1464    let mut parser = Parser::with_dialect(reader, 64 * 1024, from_dialect);
1465
1466    // Open output
1467    let mut writer: Box<dyn Write> = if config.dry_run {
1468        Box::new(std::io::sink())
1469    } else {
1470        match &config.output {
1471            Some(path) => {
1472                if let Some(parent) = path.parent() {
1473                    std::fs::create_dir_all(parent)?;
1474                }
1475                Box::new(BufWriter::with_capacity(256 * 1024, File::create(path)?))
1476            }
1477            None => Box::new(BufWriter::new(std::io::stdout())),
1478        }
1479    };
1480
1481    // Write header
1482    if !config.dry_run {
1483        write_header(&mut writer, &config, from_dialect)?;
1484    }
1485
1486    // Process statements
1487    while let Some(stmt) = parser.read_statement()? {
1488        stats.statements_processed += 1;
1489
1490        // Check if this is a COPY data block (follows a COPY header)
1491        if converter.has_pending_copy() {
1492            // This is a data block, convert it to INSERT statements
1493            match converter.process_copy_data(&stmt) {
1494                Ok(inserts) => {
1495                    for insert in inserts {
1496                        if !insert.is_empty() {
1497                            stats.statements_converted += 1;
1498                            if !config.dry_run {
1499                                writer.write_all(&insert)?;
1500                                writer.write_all(b"\n")?;
1501                            }
1502                        }
1503                    }
1504                }
1505                Err(warning) => {
1506                    stats.warnings.push(warning);
1507                    stats.statements_skipped += 1;
1508                }
1509            }
1510            continue;
1511        }
1512
1513        match converter.convert_statement(&stmt) {
1514            Ok(converted) => {
1515                if converted.is_empty() {
1516                    stats.statements_skipped += 1;
1517                } else if converted == stmt {
1518                    stats.statements_unchanged += 1;
1519                    if !config.dry_run {
1520                        writer.write_all(&converted)?;
1521                        writer.write_all(b"\n")?;
1522                    }
1523                } else {
1524                    stats.statements_converted += 1;
1525                    if !config.dry_run {
1526                        writer.write_all(&converted)?;
1527                        writer.write_all(b"\n")?;
1528                    }
1529                }
1530            }
1531            Err(warning) => {
1532                stats.warnings.push(warning);
1533                stats.statements_skipped += 1;
1534            }
1535        }
1536    }
1537
1538    // Collect warnings
1539    stats.warnings.extend(converter.warnings().iter().cloned());
1540
1541    if let Some(pb) = progress_bar {
1542        pb.finish_with_message("done");
1543    }
1544
1545    Ok(stats)
1546}
1547
1548/// Write output header
1549fn write_header(
1550    writer: &mut dyn Write,
1551    config: &ConvertConfig,
1552    from: SqlDialect,
1553) -> std::io::Result<()> {
1554    writeln!(writer, "-- Converted by sql-splitter")?;
1555    writeln!(writer, "-- From: {} → To: {}", from, config.to_dialect)?;
1556    writeln!(writer, "-- Source: {}", config.input.display())?;
1557    writeln!(writer)?;
1558
1559    // Write dialect-specific header
1560    match config.to_dialect {
1561        SqlDialect::Postgres => {
1562            writeln!(writer, "SET client_encoding = 'UTF8';")?;
1563            writeln!(writer, "SET standard_conforming_strings = on;")?;
1564        }
1565        SqlDialect::Sqlite => {
1566            writeln!(writer, "PRAGMA foreign_keys = OFF;")?;
1567        }
1568        SqlDialect::MySql => {
1569            writeln!(writer, "SET NAMES utf8mb4;")?;
1570            writeln!(writer, "SET FOREIGN_KEY_CHECKS = 0;")?;
1571        }
1572        SqlDialect::Mssql => {
1573            writeln!(writer, "SET ANSI_NULLS ON;")?;
1574            writeln!(writer, "SET QUOTED_IDENTIFIER ON;")?;
1575            writeln!(writer, "SET NOCOUNT ON;")?;
1576        }
1577    }
1578    writeln!(writer)?;
1579
1580    Ok(())
1581}