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