Skip to main content

sql_splitter/convert/
mod.rs

1//! Convert command for translating SQL dumps between dialects.
2//!
3//! Supports conversion between MySQL, PostgreSQL, and SQLite dialects with:
4//! - Identifier quoting conversion (backticks ↔ double quotes)
5//! - String escape normalization (\' ↔ '')
6//! - Data type mapping (AUTO_INCREMENT ↔ SERIAL ↔ INTEGER PRIMARY KEY)
7//! - COPY FROM stdin → INSERT conversion
8//! - Session header conversion
9//! - Warning system for unsupported features
10
11pub mod copy_to_insert;
12mod types;
13mod warnings;
14
15#[allow(unused_imports)]
16pub use copy_to_insert::{
17    copy_to_inserts, parse_copy_data, parse_copy_header, CopyHeader, CopyValue,
18};
19
20use crate::parser::{Parser, SqlDialect, StatementType};
21use crate::splitter::{open_input, open_input_with_progress};
22use indicatif::{ProgressBar, ProgressStyle};
23use std::collections::HashMap;
24use std::fs::File;
25use std::io::{BufWriter, Read, Write};
26use std::path::PathBuf;
27
28pub use types::TypeMapper;
29// Only `render::ddl` (lib-only; see the `copy_to_insert` re-export above for
30// the same bin/lib split) calls this, so the `bin` target's parallel module
31// tree sees it as unused.
32#[allow(unused_imports)]
33pub(crate) use types::map_column_type;
34pub use warnings::{print_warnings_summary, ConvertWarning, WarningCollector};
35
36/// Configuration for the convert command
37#[derive(Debug)]
38pub struct ConvertConfig {
39    /// Input SQL file
40    pub input: PathBuf,
41    /// Output SQL file (None for stdout)
42    pub output: Option<PathBuf>,
43    /// Source dialect (auto-detected if None)
44    pub from_dialect: Option<SqlDialect>,
45    /// Target dialect
46    pub to_dialect: SqlDialect,
47    /// Dry run mode
48    pub dry_run: bool,
49    /// Show progress
50    pub progress: bool,
51    /// Strict mode (fail on any unsupported feature)
52    pub strict: bool,
53}
54
55impl Default for ConvertConfig {
56    fn default() -> Self {
57        Self {
58            input: PathBuf::new(),
59            output: None,
60            from_dialect: None,
61            to_dialect: SqlDialect::Postgres,
62            dry_run: false,
63            progress: false,
64            strict: false,
65        }
66    }
67}
68
69/// Statistics from convert operation
70#[derive(Debug, Default, serde::Serialize)]
71pub struct ConvertStats {
72    /// Total statements processed
73    pub statements_processed: u64,
74    /// Statements converted
75    pub statements_converted: u64,
76    /// Statements passed through unchanged
77    pub statements_unchanged: u64,
78    /// Statements skipped (unsupported)
79    pub statements_skipped: u64,
80    /// Warnings generated
81    pub warnings: Vec<ConvertWarning>,
82}
83
84/// Main converter that dispatches to specific dialect converters
85pub struct Converter {
86    from: SqlDialect,
87    to: SqlDialect,
88    warnings: WarningCollector,
89    strict: bool,
90    /// Pending COPY header for data block processing
91    pending_copy_header: Option<CopyHeader>,
92    /// Converted `CREATE TABLE` text, keyed by [`table_key`]. Only retained when
93    /// the target needs to re-declare a column later (MySQL's `MODIFY COLUMN`
94    /// takes a full definition), so this holds DDL for the schema and never row
95    /// data.
96    created_tables: HashMap<String, String>,
97    /// Statements that only become valid once the rest of the dump has been
98    /// applied; drained by [`Converter::take_deferred_statements`].
99    deferred: Vec<String>,
100}
101
102/// Normalise a table name for lookup: unquoted, unqualified, lowercased, so
103/// `public."Posts"` and `` `posts` `` resolve to the same entry.
104fn table_key(name: &str) -> String {
105    name.rsplit('.')
106        .next()
107        .unwrap_or(name)
108        .trim_matches(|c| c == '"' || c == '`' || c == '[' || c == ']')
109        .to_lowercase()
110}
111
112/// The type `column` was declared with in a converted `CREATE TABLE`, e.g.
113/// `"integer"` for `  id integer NOT NULL,`.
114///
115/// Anchored on the column-list delimiter (`(` or `,`) rather than start-of-line,
116/// so it reads a definition whether the DDL is formatted one column per line or
117/// collapsed onto one. Captures a single word plus an optional length: callers
118/// re-declare integer columns, and a greedier pattern would swallow the
119/// trailing `NOT NULL`. A key clause such as `PRIMARY KEY (id)` cannot match,
120/// since a type has to follow the name.
121fn declared_column_type(create_table: &str, column: &str) -> Option<String> {
122    use regex::Regex;
123
124    let pattern = format!(
125        r#"(?i)[(,]\s*[`"\[]?{}[`"\]]?\s+(?P<type>[A-Za-z]+(?:\s*\(\s*\d+\s*\))?)"#,
126        regex::escape(column)
127    );
128    let captures = Regex::new(&pattern).ok()?.captures(create_table)?;
129    Some(captures.name("type")?.as_str().trim().to_string())
130}
131
132impl Converter {
133    pub fn new(from: SqlDialect, to: SqlDialect) -> Self {
134        Self {
135            from,
136            to,
137            warnings: WarningCollector::new(),
138            strict: false,
139            pending_copy_header: None,
140            created_tables: HashMap::new(),
141            deferred: Vec::new(),
142        }
143    }
144
145    /// Statements held back until the whole dump has been applied, in the order
146    /// they were queued. Callers must append these to the output after the last
147    /// converted statement; draining leaves the converter reusable.
148    pub fn take_deferred_statements(&mut self) -> Vec<String> {
149        std::mem::take(&mut self.deferred)
150    }
151
152    pub fn with_strict(mut self, strict: bool) -> Self {
153        self.strict = strict;
154        self
155    }
156
157    /// Check if we have a pending COPY header (waiting for data block)
158    pub fn has_pending_copy(&self) -> bool {
159        self.pending_copy_header.is_some()
160    }
161
162    /// Process a COPY data block using the pending header
163    pub fn process_copy_data(&mut self, data: &[u8]) -> Result<Vec<Vec<u8>>, ConvertWarning> {
164        if let Some(header) = self.pending_copy_header.take() {
165            if self.from == SqlDialect::Postgres && self.to != SqlDialect::Postgres {
166                // Convert COPY data to INSERT statements
167                let inserts = copy_to_inserts(&header, data, self.to);
168                return Ok(inserts);
169            }
170        }
171        // Pass through if same dialect or no pending header
172        Ok(vec![data.to_vec()])
173    }
174
175    /// Convert a single statement
176    pub fn convert_statement(&mut self, stmt: &[u8]) -> Result<Vec<u8>, ConvertWarning> {
177        let (stmt_type, table_name) =
178            Parser::<&[u8]>::parse_statement_with_dialect(stmt, self.from);
179
180        let table = if table_name.is_empty() {
181            None
182        } else {
183            Some(table_name.as_str())
184        };
185
186        match stmt_type {
187            StatementType::CreateTable => self.convert_create_table(stmt, table),
188            StatementType::Insert => self.convert_insert(stmt, table),
189            StatementType::CreateIndex => self.convert_create_index(stmt),
190            StatementType::AlterTable => self.convert_alter_table(stmt),
191            StatementType::DropTable => self.convert_drop_table(stmt),
192            StatementType::Copy => self.convert_copy(stmt, table),
193            StatementType::Unknown => self.convert_other(stmt),
194        }
195    }
196
197    /// Convert CREATE TABLE statement
198    fn convert_create_table(
199        &mut self,
200        stmt: &[u8],
201        table_name: Option<&str>,
202    ) -> Result<Vec<u8>, ConvertWarning> {
203        let stmt_str = String::from_utf8_lossy(stmt);
204        let mut result = stmt_str.to_string();
205
206        // Detect unsupported features BEFORE conversion (so we see original types)
207        self.detect_unsupported_features(&result, table_name)?;
208
209        // Convert MSSQL-specific syntax BEFORE identifier conversion
210        // (so we can strip [dbo]. schema prefix properly)
211        if self.from == SqlDialect::Mssql && self.to != SqlDialect::Mssql {
212            result = self.strip_mssql_schema_prefix(&result);
213            result = self.convert_mssql_getdate(&result);
214            result = self.strip_mssql_on_filegroup(&result);
215            result = self.strip_mssql_clustered(&result);
216            result = self.convert_mssql_unicode_strings(&result);
217        }
218
219        // Convert identifier quoting
220        result = self.convert_identifiers(&result);
221
222        // Convert data types
223        result = self.convert_data_types(&result);
224
225        // Convert AUTO_INCREMENT
226        result = self.convert_auto_increment(&result, table_name);
227
228        // Convert PostgreSQL-specific syntax
229        if self.from == SqlDialect::Postgres && self.to != SqlDialect::Postgres {
230            result = self.strip_postgres_casts(&result);
231            result = self.convert_nextval(&result);
232            result = self.convert_default_now(&result);
233            result = self.strip_schema_prefix(&result);
234        }
235
236        // Convert string escapes
237        result = self.convert_string_escapes(&result);
238
239        // Strip MySQL conditional comments
240        result = self.strip_conditional_comments(&result);
241
242        // Convert ENGINE clause
243        result = self.strip_engine_clause(&result);
244
245        // Convert CHARSET/COLLATE
246        result = self.strip_charset_clauses(&result);
247
248        // Strip MySQL inline column/table COMMENT annotations
249        result = self.strip_mysql_comment_clauses(&result);
250
251        // Convert UNIQUE KEY ... USING BTREE table constraints
252        result = self.convert_unique_key_constraint(&result);
253
254        // MySQL is the only target that has to re-declare a column after the
255        // fact (to restore AUTO_INCREMENT), and that needs the column's
256        // converted type. Retained only for that target so no other conversion
257        // pays for the bookkeeping.
258        if self.to == SqlDialect::MySql {
259            if let Some(name) = table_name {
260                self.created_tables.insert(table_key(name), result.clone());
261            }
262        }
263
264        Ok(result.into_bytes())
265    }
266
267    /// Convert INSERT statement
268    fn convert_insert(
269        &mut self,
270        stmt: &[u8],
271        _table_name: Option<&str>,
272    ) -> Result<Vec<u8>, ConvertWarning> {
273        let stmt_str = String::from_utf8_lossy(stmt);
274        let mut result = stmt_str.to_string();
275
276        // Convert MSSQL-specific syntax BEFORE identifier conversion
277        if self.from == SqlDialect::Mssql && self.to != SqlDialect::Mssql {
278            result = self.strip_mssql_schema_prefix(&result);
279            result = self.convert_mssql_unicode_strings(&result);
280        }
281
282        // Convert identifier quoting
283        result = self.convert_identifiers(&result);
284
285        // Convert PostgreSQL-specific syntax
286        if self.from == SqlDialect::Postgres && self.to != SqlDialect::Postgres {
287            result = self.strip_postgres_casts(&result);
288            result = self.strip_schema_prefix(&result);
289        }
290
291        // Convert string escapes (careful with data!)
292        result = self.convert_string_escapes(&result);
293
294        Ok(result.into_bytes())
295    }
296
297    /// Convert CREATE INDEX statement
298    fn convert_create_index(&mut self, stmt: &[u8]) -> Result<Vec<u8>, ConvertWarning> {
299        let stmt_str = String::from_utf8_lossy(stmt);
300        let mut result = stmt_str.to_string();
301
302        // Convert MSSQL-specific syntax BEFORE identifier conversion
303        if self.from == SqlDialect::Mssql && self.to != SqlDialect::Mssql {
304            result = self.strip_mssql_schema_prefix(&result);
305            result = self.strip_mssql_clustered(&result);
306        }
307
308        // Convert identifier quoting
309        result = self.convert_identifiers(&result);
310
311        // Convert PostgreSQL-specific syntax
312        if self.from == SqlDialect::Postgres && self.to != SqlDialect::Postgres {
313            result = self.strip_postgres_casts(&result);
314            result = self.strip_schema_prefix(&result);
315        }
316
317        // Detect FULLTEXT/SPATIAL
318        if result.contains("FULLTEXT") || result.contains("fulltext") {
319            self.warnings.add(ConvertWarning::UnsupportedFeature {
320                feature: "FULLTEXT INDEX".to_string(),
321                suggestion: Some("Use PostgreSQL GIN index or skip".to_string()),
322            });
323            if self.strict {
324                return Err(ConvertWarning::UnsupportedFeature {
325                    feature: "FULLTEXT INDEX".to_string(),
326                    suggestion: None,
327                });
328            }
329        }
330
331        Ok(result.into_bytes())
332    }
333
334    /// Convert ALTER TABLE statement
335    fn convert_alter_table(&mut self, stmt: &[u8]) -> Result<Vec<u8>, ConvertWarning> {
336        let stmt_str = String::from_utf8_lossy(stmt);
337        let mut result = stmt_str.to_string();
338
339        // pg_dump expands `serial` into a plain integer column plus a separate
340        // `ALTER COLUMN ... SET DEFAULT nextval(...)`. Removing just the
341        // `DEFAULT nextval(...)` would leave a dangling `ALTER COLUMN id SET`,
342        // so the statement never survives as-is. MySQL can restore the
343        // auto-increment separately; every other target loses it.
344        if self.from == SqlDialect::Postgres
345            && self.to != SqlDialect::Postgres
346            && self.is_sequence_default_alter(&result)
347        {
348            if let Some(restored) = self.defer_mysql_auto_increment(&result) {
349                self.deferred.push(restored);
350                return Ok(Vec::new());
351            }
352            let preview = self.strip_leading_sql_comments(&result);
353            self.warnings.add(ConvertWarning::SkippedStatement {
354                reason: "sequence-backed column default has no equivalent".to_string(),
355                statement_preview: preview.trim().chars().take(60).collect(),
356            });
357            return Ok(Vec::new());
358        }
359
360        result = self.convert_identifiers(&result);
361        result = self.convert_data_types(&result);
362
363        // Convert PostgreSQL-specific syntax
364        if self.from == SqlDialect::Postgres && self.to != SqlDialect::Postgres {
365            result = self.strip_postgres_casts(&result);
366            result = self.convert_nextval(&result);
367            result = self.convert_default_now(&result);
368            result = self.strip_schema_prefix(&result);
369            result = self.strip_postgres_only(&result);
370        }
371
372        // SQLite's ALTER TABLE understands only RENAME / ADD COLUMN /
373        // DROP COLUMN, so a constraint attached after the table exists has to be
374        // re-expressed as an index or dropped. Runs last: the rewrite reads the
375        // table name out of the statement, which the steps above normalise.
376        if self.to == SqlDialect::Sqlite {
377            if let Some(rewritten) = self.rewrite_add_constraint_for_sqlite(&result) {
378                return Ok(rewritten.into_bytes());
379            }
380        }
381
382        Ok(result.into_bytes())
383    }
384
385    /// Re-express an `ALTER TABLE ... ADD CONSTRAINT` for SQLite, which has no
386    /// such statement.
387    ///
388    /// `UNIQUE` and `PRIMARY KEY` become a unique index — SQLite enforces the
389    /// same guarantee, though a re-expressed primary key is no longer a rowid
390    /// alias and, unlike a real primary key, does not itself imply NOT NULL.
391    /// A foreign key or check constraint cannot be attached to an existing
392    /// SQLite table by any syntax, so it is dropped with a warning.
393    ///
394    /// Returns `None` for the ALTER forms SQLite already accepts (`ADD COLUMN`,
395    /// `RENAME`, `DROP COLUMN`), which pass through untouched.
396    fn rewrite_add_constraint_for_sqlite(&mut self, stmt: &str) -> Option<String> {
397        use once_cell::sync::Lazy;
398        use regex::Regex;
399
400        static RE_ADD_CONSTRAINT: Lazy<Regex> = Lazy::new(|| {
401            Regex::new(
402                r"(?is)^\s*ALTER\s+TABLE\s+(?P<table>\S+)\s+ADD\s+CONSTRAINT\s+(?P<name>[^\s(]+)\s+(?P<kind>UNIQUE|PRIMARY\s+KEY|FOREIGN\s+KEY|CHECK)\b(?P<rest>.*)$",
403            )
404            .unwrap()
405        });
406        static RE_LEADING_COLUMNS: Lazy<Regex> =
407            Lazy::new(|| Regex::new(r"(?s)^\s*\(([^)]*)\)").unwrap());
408
409        // pg_dump prefixes each statement with a comment banner; the constraint
410        // itself is what has to be matched.
411        let body = self.strip_leading_sql_comments(stmt);
412        let caps = RE_ADD_CONSTRAINT.captures(&body)?;
413        let kind = caps["kind"]
414            .split_whitespace()
415            .collect::<Vec<_>>()
416            .join(" ");
417        let kind = kind.to_uppercase();
418
419        if kind == "UNIQUE" || kind == "PRIMARY KEY" {
420            if let Some(columns) = RE_LEADING_COLUMNS.captures(&caps["rest"]) {
421                if kind == "PRIMARY KEY" {
422                    self.warnings.add(ConvertWarning::UnsupportedFeature {
423                        feature: format!("PRIMARY KEY added to existing table {}", &caps["table"]),
424                        suggestion: Some(
425                            "re-expressed as a UNIQUE INDEX; SQLite only accepts a \
426                             primary key inside CREATE TABLE"
427                                .to_string(),
428                        ),
429                    });
430                }
431                return Some(format!(
432                    "CREATE UNIQUE INDEX {} ON {} ({});",
433                    &caps["name"],
434                    &caps["table"],
435                    columns[1].trim()
436                ));
437            }
438        }
439
440        self.warnings.add(ConvertWarning::SkippedStatement {
441            reason: format!("SQLite cannot add a {kind} constraint to an existing table"),
442            statement_preview: body.trim().chars().take(60).collect(),
443        });
444        Some(String::new())
445    }
446
447    /// Convert DROP TABLE statement
448    fn convert_drop_table(&mut self, stmt: &[u8]) -> Result<Vec<u8>, ConvertWarning> {
449        let stmt_str = String::from_utf8_lossy(stmt);
450        let mut result = stmt_str.to_string();
451
452        result = self.convert_identifiers(&result);
453
454        // Strip PostgreSQL schema prefix
455        if self.from == SqlDialect::Postgres && self.to != SqlDialect::Postgres {
456            result = self.strip_schema_prefix(&result);
457        }
458
459        Ok(result.into_bytes())
460    }
461
462    /// Convert COPY statement (PostgreSQL-specific)
463    ///
464    /// This handles the COPY header. The data block is processed separately
465    /// via process_copy_data() when called from the run() function.
466    fn convert_copy(
467        &mut self,
468        stmt: &[u8],
469        _table_name: Option<&str>,
470    ) -> Result<Vec<u8>, ConvertWarning> {
471        let stmt_str = String::from_utf8_lossy(stmt);
472
473        // Check if this contains "FROM stdin" (COPY header) or is data
474        let upper = stmt_str.to_uppercase();
475        if upper.contains("FROM STDIN") {
476            // This is a COPY header - parse it and store for later
477            if let Some(header) = parse_copy_header(&stmt_str) {
478                if self.from == SqlDialect::Postgres && self.to != SqlDialect::Postgres {
479                    // Store the header, will convert data block in process_copy_data
480                    self.pending_copy_header = Some(header);
481                    // Return empty - the actual INSERT will be generated from data
482                    return Ok(Vec::new());
483                }
484            }
485        }
486
487        // If same dialect or couldn't parse, pass through
488        Ok(stmt.to_vec())
489    }
490
491    /// Convert other statements (comments, session settings, etc.)
492    fn convert_other(&mut self, stmt: &[u8]) -> Result<Vec<u8>, ConvertWarning> {
493        let stmt_str = String::from_utf8_lossy(stmt);
494        let result = stmt_str.to_string();
495        let trimmed = result.trim();
496
497        // Skip MySQL session commands when converting to other dialects
498        if self.from == SqlDialect::MySql
499            && self.to != SqlDialect::MySql
500            && self.is_mysql_session_command(&result)
501        {
502            return Ok(Vec::new()); // Skip
503        }
504
505        // Skip PostgreSQL session commands and unsupported features when converting to other dialects
506        if self.from == SqlDialect::Postgres
507            && self.to != SqlDialect::Postgres
508            && self.is_postgres_session_command(&result)
509        {
510            return Ok(Vec::new()); // Skip
511        }
512        // psql meta-commands are client directives, not SQL. pg_dump 16.6+ wraps
513        // its output in `\restrict` / `\unrestrict`; fed to the mysql client,
514        // `\u` is read as its "use database" shorthand and the import dies with
515        // ERROR 1049.
516        if self.from == SqlDialect::Postgres
517            && self.to != SqlDialect::Postgres
518            && self.is_psql_meta_command(trimmed)
519        {
520            return Ok(Vec::new()); // Skip
521        }
522        if self.from == SqlDialect::Postgres
523            && self.to != SqlDialect::Postgres
524            && self.is_postgres_only_feature(trimmed)
525        {
526            self.warnings.add(ConvertWarning::SkippedStatement {
527                reason: "PostgreSQL-only feature".to_string(),
528                statement_preview: trimmed.chars().take(60).collect(),
529            });
530            return Ok(Vec::new()); // Skip
531        }
532
533        // Skip SQLite pragmas when converting to other dialects
534        if self.from == SqlDialect::Sqlite
535            && self.to != SqlDialect::Sqlite
536            && self.is_sqlite_pragma(&result)
537        {
538            return Ok(Vec::new()); // Skip
539        }
540
541        // Skip MSSQL session commands when converting to other dialects
542        if self.from == SqlDialect::Mssql
543            && self.to != SqlDialect::Mssql
544            && self.is_mssql_session_command(&result)
545        {
546            return Ok(Vec::new()); // Skip
547        }
548
549        // Strip conditional comments
550        if result.contains("/*!") {
551            let stripped = self.strip_conditional_comments(&result);
552            return Ok(stripped.into_bytes());
553        }
554
555        Ok(stmt.to_vec())
556    }
557
558    /// Check if statement is a MySQL session command
559    fn is_mysql_session_command(&self, stmt: &str) -> bool {
560        let upper = stmt.to_uppercase();
561        upper.contains("SET NAMES")
562            || upper.contains("SET CHARACTER")
563            || upper.contains("SET SQL_MODE")
564            || upper.contains("SET TIME_ZONE")
565            || upper.contains("SET FOREIGN_KEY_CHECKS")
566            || upper.contains("LOCK TABLES")
567            || upper.contains("UNLOCK TABLES")
568    }
569
570    /// Check if statement is a PostgreSQL session command or unsupported statement
571    fn is_postgres_session_command(&self, stmt: &str) -> bool {
572        let upper = stmt.to_uppercase();
573        // Session/transaction settings
574        upper.contains("SET CLIENT_ENCODING")
575            || upper.contains("SET STANDARD_CONFORMING_STRINGS")
576            || upper.contains("SET CHECK_FUNCTION_BODIES")
577            || upper.contains("SET SEARCH_PATH")
578            || upper.contains("SET DEFAULT_TABLESPACE")
579            || upper.contains("SET LOCK_TIMEOUT")
580            || upper.contains("SET IDLE_IN_TRANSACTION_SESSION_TIMEOUT")
581            || upper.contains("SET ROW_SECURITY")
582            || upper.contains("SET STATEMENT_TIMEOUT")
583            || upper.contains("SET XMLOPTION")
584            || upper.contains("SET CLIENT_MIN_MESSAGES")
585            || upper.contains("SET DEFAULT_TABLE_ACCESS_METHOD")
586            || upper.contains("SELECT PG_CATALOG")
587            // Ownership/permission statements
588            || upper.contains("OWNER TO")
589            || upper.contains("GRANT ")
590            || upper.contains("REVOKE ")
591    }
592
593    /// Check if statement is a PostgreSQL-only feature that should be skipped
594    fn is_postgres_only_feature(&self, stmt: &str) -> bool {
595        // Strip leading comments to find the actual statement
596        let stripped = self.strip_leading_sql_comments(stmt);
597        let upper = stripped.to_uppercase();
598
599        // These PostgreSQL features have no MySQL/SQLite equivalent
600        upper.starts_with("CREATE DOMAIN")
601            || upper.starts_with("CREATE TYPE")
602            || upper.starts_with("CREATE FUNCTION")
603            || upper.starts_with("CREATE PROCEDURE")
604            || upper.starts_with("CREATE AGGREGATE")
605            || upper.starts_with("CREATE OPERATOR")
606            || upper.starts_with("CREATE SEQUENCE")
607            || upper.starts_with("CREATE EXTENSION")
608            || upper.starts_with("CREATE SCHEMA")
609            || upper.starts_with("CREATE TRIGGER")
610            || upper.starts_with("ALTER DOMAIN")
611            || upper.starts_with("ALTER TYPE")
612            || upper.starts_with("ALTER FUNCTION")
613            || upper.starts_with("ALTER SEQUENCE")
614            || upper.starts_with("ALTER SCHEMA")
615            || upper.starts_with("COMMENT ON")
616    }
617
618    /// Strip leading SQL comments (-- and /* */) from a string
619    fn strip_leading_sql_comments(&self, stmt: &str) -> String {
620        let mut result = stmt.trim();
621        loop {
622            // Strip -- comments
623            if result.starts_with("--") {
624                if let Some(pos) = result.find('\n') {
625                    result = result[pos + 1..].trim();
626                    continue;
627                } else {
628                    return String::new();
629                }
630            }
631            // Strip /* */ comments
632            if result.starts_with("/*") {
633                if let Some(pos) = result.find("*/") {
634                    result = result[pos + 2..].trim();
635                    continue;
636                } else {
637                    return String::new();
638                }
639            }
640            break;
641        }
642        result.to_string()
643    }
644
645    /// Check if statement is a SQLite pragma
646    fn is_sqlite_pragma(&self, stmt: &str) -> bool {
647        let upper = stmt.to_uppercase();
648        upper.contains("PRAGMA")
649    }
650
651    /// Check if statement is an MSSQL session command
652    fn is_mssql_session_command(&self, stmt: &str) -> bool {
653        let upper = stmt.to_uppercase();
654        upper.contains("SET ANSI_NULLS")
655            || upper.contains("SET QUOTED_IDENTIFIER")
656            || upper.contains("SET NOCOUNT")
657            || upper.contains("SET XACT_ABORT")
658            || upper.contains("SET ARITHABORT")
659            || upper.contains("SET ANSI_WARNINGS")
660            || upper.contains("SET ANSI_PADDING")
661            || upper.contains("SET CONCAT_NULL_YIELDS_NULL")
662            || upper.contains("SET NUMERIC_ROUNDABORT")
663            || upper.contains("SET IDENTITY_INSERT")
664    }
665
666    /// Convert identifier quoting based on dialects
667    fn convert_identifiers(&self, stmt: &str) -> String {
668        match (self.from, self.to) {
669            (SqlDialect::MySql, SqlDialect::Postgres | SqlDialect::Sqlite) => {
670                // Backticks → double quotes
671                self.backticks_to_double_quotes(stmt)
672            }
673            (SqlDialect::MySql, SqlDialect::Mssql) => {
674                // Backticks → square brackets
675                self.backticks_to_square_brackets(stmt)
676            }
677            (SqlDialect::Postgres | SqlDialect::Sqlite, SqlDialect::MySql) => {
678                // Double quotes → backticks
679                self.double_quotes_to_backticks(stmt)
680            }
681            (SqlDialect::Postgres | SqlDialect::Sqlite, SqlDialect::Mssql) => {
682                // Double quotes → square brackets
683                self.double_quotes_to_square_brackets(stmt)
684            }
685            (SqlDialect::Mssql, SqlDialect::MySql) => {
686                // Square brackets → backticks
687                self.square_brackets_to_backticks(stmt)
688            }
689            (SqlDialect::Mssql, SqlDialect::Postgres | SqlDialect::Sqlite) => {
690                // Square brackets → double quotes
691                self.square_brackets_to_double_quotes(stmt)
692            }
693            _ => stmt.to_string(),
694        }
695    }
696
697    /// Convert backticks to double quotes
698    pub fn backticks_to_double_quotes(&self, stmt: &str) -> String {
699        let mut result = String::with_capacity(stmt.len());
700        let mut in_string = false;
701        let mut in_backtick = false;
702
703        for c in stmt.chars() {
704            if c == '\'' && !in_backtick {
705                in_string = !in_string;
706                result.push(c);
707            } else if c == '`' && !in_string {
708                in_backtick = !in_backtick;
709                result.push('"');
710            } else {
711                result.push(c);
712            }
713        }
714        result
715    }
716
717    /// Convert double quotes to backticks
718    pub fn double_quotes_to_backticks(&self, stmt: &str) -> String {
719        let mut result = String::with_capacity(stmt.len());
720        let mut in_string = false;
721        let mut in_dquote = false;
722        let chars = stmt.chars();
723
724        for c in chars {
725            if c == '\'' && !in_dquote {
726                in_string = !in_string;
727                result.push(c);
728            } else if c == '"' && !in_string {
729                in_dquote = !in_dquote;
730                result.push('`');
731            } else {
732                result.push(c);
733            }
734        }
735        result
736    }
737
738    /// Convert backticks to square brackets (for MSSQL)
739    pub fn backticks_to_square_brackets(&self, stmt: &str) -> String {
740        let mut result = String::with_capacity(stmt.len());
741        let mut in_string = false;
742        let mut in_backtick = false;
743
744        for c in stmt.chars() {
745            if c == '\'' && !in_backtick {
746                in_string = !in_string;
747                result.push(c);
748            } else if c == '`' && !in_string {
749                if !in_backtick {
750                    result.push('[');
751                } else {
752                    result.push(']');
753                }
754                in_backtick = !in_backtick;
755            } else {
756                result.push(c);
757            }
758        }
759        result
760    }
761
762    /// Convert double quotes to square brackets (for MSSQL)
763    pub fn double_quotes_to_square_brackets(&self, stmt: &str) -> String {
764        let mut result = String::with_capacity(stmt.len());
765        let mut in_string = false;
766        let mut in_dquote = false;
767
768        for c in stmt.chars() {
769            if c == '\'' && !in_dquote {
770                in_string = !in_string;
771                result.push(c);
772            } else if c == '"' && !in_string {
773                if !in_dquote {
774                    result.push('[');
775                } else {
776                    result.push(']');
777                }
778                in_dquote = !in_dquote;
779            } else {
780                result.push(c);
781            }
782        }
783        result
784    }
785
786    /// Convert square brackets to backticks (from MSSQL to MySQL)
787    pub fn square_brackets_to_backticks(&self, stmt: &str) -> String {
788        let mut result = String::with_capacity(stmt.len());
789        let mut in_string = false;
790
791        for c in stmt.chars() {
792            if c == '\'' {
793                in_string = !in_string;
794                result.push(c);
795            } else if !in_string && (c == '[' || c == ']') {
796                result.push('`');
797            } else {
798                result.push(c);
799            }
800        }
801        result
802    }
803
804    /// Convert square brackets to double quotes (from MSSQL to PostgreSQL/SQLite)
805    pub fn square_brackets_to_double_quotes(&self, stmt: &str) -> String {
806        let mut result = String::with_capacity(stmt.len());
807        let mut in_string = false;
808
809        for c in stmt.chars() {
810            if c == '\'' {
811                in_string = !in_string;
812                result.push(c);
813            } else if !in_string && (c == '[' || c == ']') {
814                result.push('"');
815            } else {
816                result.push(c);
817            }
818        }
819        result
820    }
821
822    /// Convert data types between dialects
823    fn convert_data_types(&self, stmt: &str) -> String {
824        TypeMapper::convert(stmt, self.from, self.to)
825    }
826
827    /// Convert AUTO_INCREMENT/SERIAL syntax
828    fn convert_auto_increment(&self, stmt: &str, _table_name: Option<&str>) -> String {
829        // Strip the MySQL table-level `AUTO_INCREMENT=N` option first (distinct from
830        // the column-level `AUTO_INCREMENT` keyword handled below). Otherwise the
831        // column-level replacements below strip the word "AUTO_INCREMENT" and leave
832        // a dangling "=N" behind, e.g. `) ENGINE=InnoDB AUTO_INCREMENT=2 ...` becomes
833        // `) =2 ...`. See https://github.com/HelgeSverre/sql-splitter/issues/64
834        let stmt = if self.from == SqlDialect::MySql && self.to != SqlDialect::MySql {
835            self.strip_mysql_auto_increment_table_option(stmt)
836        } else {
837            stmt.to_string()
838        };
839        let stmt = stmt.as_str();
840
841        match (self.from, self.to) {
842            (SqlDialect::MySql, SqlDialect::Postgres) => {
843                // INT AUTO_INCREMENT → SERIAL, BIGINT AUTO_INCREMENT → BIGSERIAL,
844                // case-insensitive (MySQL dumps commonly use lowercase
845                // `auto_increment`) and string-literal-aware (a DEFAULT value or
846                // CHECK expression containing the literal text "AUTO_INCREMENT"
847                // must not be touched).
848                self.convert_mysql_auto_increment_keyword(stmt)
849            }
850            (SqlDialect::MySql, SqlDialect::Sqlite) => {
851                use once_cell::sync::Lazy;
852                use regex::Regex;
853                // `<int type> AUTO_INCREMENT` → INTEGER, then any bare keyword
854                // dropped. Case-insensitive (MySQL dumps commonly lowercase
855                // `auto_increment`) and only outside string literals so a
856                // DEFAULT / value containing the text is left alone. Matching
857                // the whole `…INT AUTO_INCREMENT` unit avoids the "BIGINTEGER"
858                // substring hazard.
859                static RE_SIZED_AI: Lazy<Regex> = Lazy::new(|| {
860                    Regex::new(r"(?i)\b(?:BIG|MEDIUM|SMALL|TINY)?INT\s+AUTO_INCREMENT").unwrap()
861                });
862                // Trailing boundary only: the integer type may already have been
863                // mapped and glued to the keyword (e.g. `INTEGERAUTO_INCREMENT`)
864                // by convert_data_types running first.
865                static RE_BARE_AI: Lazy<Regex> =
866                    Lazy::new(|| Regex::new(r"(?i)AUTO_INCREMENT\b").unwrap());
867                map_outside_string_literals(stmt, |seg| {
868                    let seg = RE_SIZED_AI.replace_all(seg, "INTEGER");
869                    RE_BARE_AI.replace_all(&seg, "").into_owned()
870                })
871            }
872            (SqlDialect::Postgres, SqlDialect::MySql) => {
873                // SERIAL → INT AUTO_INCREMENT
874                // BIGSERIAL → BIGINT AUTO_INCREMENT
875                let result = stmt.replace("BIGSERIAL", "BIGINT AUTO_INCREMENT");
876                let result = result.replace("bigserial", "BIGINT AUTO_INCREMENT");
877                let result = result.replace("SMALLSERIAL", "SMALLINT AUTO_INCREMENT");
878                let result = result.replace("smallserial", "SMALLINT AUTO_INCREMENT");
879                let result = result.replace("SERIAL", "INT AUTO_INCREMENT");
880                result.replace("serial", "INT AUTO_INCREMENT")
881            }
882            (SqlDialect::Postgres, SqlDialect::Sqlite) => {
883                // SERIAL → INTEGER (SQLite auto-increments INTEGER PRIMARY KEY)
884                let result = stmt.replace("BIGSERIAL", "INTEGER");
885                let result = result.replace("bigserial", "INTEGER");
886                let result = result.replace("SMALLSERIAL", "INTEGER");
887                let result = result.replace("smallserial", "INTEGER");
888                let result = result.replace("SERIAL", "INTEGER");
889                result.replace("serial", "INTEGER")
890            }
891            (SqlDialect::Sqlite, SqlDialect::MySql) => {
892                // SQLite uses INTEGER PRIMARY KEY for auto-increment
893                // We can't easily detect this pattern, so just pass through
894                stmt.to_string()
895            }
896            (SqlDialect::Sqlite, SqlDialect::Postgres) => {
897                // SQLite uses INTEGER PRIMARY KEY for auto-increment
898                // We can't easily detect this pattern, so just pass through
899                stmt.to_string()
900            }
901            // MSSQL conversions
902            (SqlDialect::MySql, SqlDialect::Mssql) => {
903                use once_cell::sync::Lazy;
904                use regex::Regex;
905                // AUTO_INCREMENT → IDENTITY(1,1), keeping the integer type.
906                // Case-insensitive and only outside string literals. BIGINT is
907                // handled before the bare INT rule; `\bINT` won't match the
908                // `INT` inside `BIGINT`.
909                static RE_BIGINT_AI: Lazy<Regex> =
910                    Lazy::new(|| Regex::new(r"(?i)\bBIGINT\s+AUTO_INCREMENT").unwrap());
911                static RE_INT_AI: Lazy<Regex> =
912                    Lazy::new(|| Regex::new(r"(?i)\bINT\s+AUTO_INCREMENT").unwrap());
913                // Trailing boundary only (the type may already be glued to the
914                // keyword by an earlier type mapping).
915                static RE_BARE_AI: Lazy<Regex> =
916                    Lazy::new(|| Regex::new(r"(?i)AUTO_INCREMENT\b").unwrap());
917                map_outside_string_literals(stmt, |seg| {
918                    let seg = RE_BIGINT_AI.replace_all(seg, "BIGINT IDENTITY(1,1)");
919                    let seg = RE_INT_AI.replace_all(&seg, "INT IDENTITY(1,1)");
920                    RE_BARE_AI.replace_all(&seg, "IDENTITY(1,1)").into_owned()
921                })
922            }
923            (SqlDialect::Mssql, SqlDialect::MySql) => {
924                // IDENTITY(1,1) → AUTO_INCREMENT
925                self.convert_identity_to_auto_increment(stmt)
926            }
927            (SqlDialect::Postgres, SqlDialect::Mssql) => {
928                // SERIAL → INT IDENTITY(1,1) (handled by type mapper)
929                stmt.to_string()
930            }
931            (SqlDialect::Mssql, SqlDialect::Postgres) => {
932                // IDENTITY(1,1) → SERIAL (need to add SERIAL instead)
933                self.convert_identity_to_serial(stmt)
934            }
935            (SqlDialect::Sqlite, SqlDialect::Mssql) => {
936                // SQLite → MSSQL: pass through
937                stmt.to_string()
938            }
939            (SqlDialect::Mssql, SqlDialect::Sqlite) => {
940                // IDENTITY → strip (SQLite uses INTEGER PRIMARY KEY)
941                self.strip_identity(stmt)
942            }
943            _ => stmt.to_string(),
944        }
945    }
946
947    /// Convert MSSQL IDENTITY to MySQL AUTO_INCREMENT
948    fn convert_identity_to_auto_increment(&self, stmt: &str) -> String {
949        use once_cell::sync::Lazy;
950        use regex::Regex;
951
952        static RE_IDENTITY: Lazy<Regex> =
953            Lazy::new(|| Regex::new(r"(?i)\bIDENTITY\s*\(\s*\d+\s*,\s*\d+\s*\)").unwrap());
954
955        RE_IDENTITY.replace_all(stmt, "AUTO_INCREMENT").to_string()
956    }
957
958    /// Convert MSSQL IDENTITY to PostgreSQL SERIAL
959    fn convert_identity_to_serial(&self, stmt: &str) -> String {
960        use once_cell::sync::Lazy;
961        use regex::Regex;
962
963        // Match INT IDENTITY(1,1) and replace with SERIAL
964        static RE_BIGINT_IDENTITY: Lazy<Regex> =
965            Lazy::new(|| Regex::new(r"(?i)\bBIGINT\s+IDENTITY\s*\(\s*\d+\s*,\s*\d+\s*\)").unwrap());
966        static RE_INT_IDENTITY: Lazy<Regex> =
967            Lazy::new(|| Regex::new(r"(?i)\bINT\s+IDENTITY\s*\(\s*\d+\s*,\s*\d+\s*\)").unwrap());
968        static RE_SMALLINT_IDENTITY: Lazy<Regex> = Lazy::new(|| {
969            Regex::new(r"(?i)\bSMALLINT\s+IDENTITY\s*\(\s*\d+\s*,\s*\d+\s*\)").unwrap()
970        });
971
972        let result = RE_BIGINT_IDENTITY
973            .replace_all(stmt, "BIGSERIAL")
974            .to_string();
975        let result = RE_INT_IDENTITY.replace_all(&result, "SERIAL").to_string();
976        RE_SMALLINT_IDENTITY
977            .replace_all(&result, "SMALLSERIAL")
978            .to_string()
979    }
980
981    /// Strip MSSQL IDENTITY clause for SQLite
982    fn strip_identity(&self, stmt: &str) -> String {
983        use once_cell::sync::Lazy;
984        use regex::Regex;
985
986        static RE_IDENTITY: Lazy<Regex> =
987            Lazy::new(|| Regex::new(r"(?i)\s*IDENTITY\s*\(\s*\d+\s*,\s*\d+\s*\)").unwrap());
988
989        RE_IDENTITY.replace_all(stmt, "").to_string()
990    }
991
992    /// Convert string escape sequences
993    fn convert_string_escapes(&self, stmt: &str) -> String {
994        match (self.from, self.to) {
995            // MySQL uses backslash escapes; PostgreSQL (standard strings),
996            // SQLite and MSSQL all treat backslash as a literal byte and escape
997            // a quote by doubling it, so the same decode applies to all three.
998            (SqlDialect::MySql, SqlDialect::Postgres | SqlDialect::Sqlite | SqlDialect::Mssql) => {
999                self.mysql_escapes_to_standard(stmt)
1000            }
1001            _ => stmt.to_string(),
1002        }
1003    }
1004
1005    /// Convert MySQL backslash escapes to standard SQL double-quote escapes
1006    fn mysql_escapes_to_standard(&self, stmt: &str) -> String {
1007        let mut result = String::with_capacity(stmt.len());
1008        let mut chars = stmt.chars().peekable();
1009        let mut in_string = false;
1010
1011        while let Some(c) = chars.next() {
1012            if c == '\'' {
1013                in_string = !in_string;
1014                result.push(c);
1015            } else if c == '\\' && in_string {
1016                // Decode the MySQL escape to the byte it represents. The target
1017                // dialects (Postgres standard strings, SQLite, MSSQL) treat
1018                // backslash as a literal, so a passed-through `\\` or `\n` would
1019                // be read as two literal characters and corrupt the data.
1020                match chars.next() {
1021                    Some(next) => match next {
1022                        // Quote becomes a doubled '' (standard SQL escaping).
1023                        '\'' => result.push_str("''"),
1024                        '"' => result.push('"'),
1025                        // One literal backslash.
1026                        '\\' => result.push('\\'),
1027                        'n' => result.push('\n'),
1028                        'r' => result.push('\r'),
1029                        't' => result.push('\t'),
1030                        '0' => result.push('\0'),
1031                        'b' => result.push('\u{08}'),
1032                        'Z' => result.push('\u{1a}'),
1033                        // MySQL keeps the backslash for the LIKE metacharacters.
1034                        '%' => result.push_str("\\%"),
1035                        '_' => result.push_str("\\_"),
1036                        // Any other escaped char is the char itself.
1037                        other => result.push(other),
1038                    },
1039                    // Trailing backslash at end of input.
1040                    None => result.push('\\'),
1041                }
1042            } else {
1043                result.push(c);
1044            }
1045        }
1046        result
1047    }
1048
1049    /// Strip MySQL conditional comments /*!40101 ... */
1050    fn strip_conditional_comments(&self, stmt: &str) -> String {
1051        let mut result = String::with_capacity(stmt.len());
1052        let mut chars = stmt.chars().peekable();
1053
1054        while let Some(c) = chars.next() {
1055            if c == '/' && chars.peek() == Some(&'*') {
1056                chars.next(); // consume *
1057                if chars.peek() == Some(&'!') {
1058                    // Skip conditional comment
1059                    chars.next(); // consume !
1060                                  // Skip version number
1061                    while chars.peek().map(|c| c.is_ascii_digit()).unwrap_or(false) {
1062                        chars.next();
1063                    }
1064                    // Skip content until */
1065                    let mut depth = 1;
1066                    while depth > 0 {
1067                        match chars.next() {
1068                            Some('*') if chars.peek() == Some(&'/') => {
1069                                chars.next();
1070                                depth -= 1;
1071                            }
1072                            Some('/') if chars.peek() == Some(&'*') => {
1073                                chars.next();
1074                                depth += 1;
1075                            }
1076                            None => break,
1077                            _ => {}
1078                        }
1079                    }
1080                } else {
1081                    // Regular comment, keep it
1082                    result.push('/');
1083                    result.push('*');
1084                }
1085            } else {
1086                result.push(c);
1087            }
1088        }
1089        result
1090    }
1091
1092    /// Strip ENGINE clause
1093    fn strip_engine_clause(&self, stmt: &str) -> String {
1094        use once_cell::sync::Lazy;
1095        use regex::Regex;
1096
1097        if self.to == SqlDialect::MySql {
1098            return stmt.to_string();
1099        }
1100
1101        // Remove ENGINE=InnoDB, ENGINE=MyISAM, etc.
1102        static RE_ENGINE: Lazy<Regex> =
1103            Lazy::new(|| Regex::new(r"(?i)\s*ENGINE\s*=\s*\w+").unwrap());
1104        RE_ENGINE.replace_all(stmt, "").to_string()
1105    }
1106
1107    /// Strip CHARSET/COLLATE clauses
1108    fn strip_charset_clauses(&self, stmt: &str) -> String {
1109        use once_cell::sync::Lazy;
1110        use regex::Regex;
1111
1112        if self.to == SqlDialect::MySql {
1113            return stmt.to_string();
1114        }
1115
1116        static RE_CHARSET: Lazy<Regex> =
1117            Lazy::new(|| Regex::new(r"(?i)\s*(DEFAULT\s+)?CHARSET\s*=\s*\w+").unwrap());
1118        static RE_COLLATE: Lazy<Regex> =
1119            Lazy::new(|| Regex::new(r"(?i)\s*COLLATE\s*=?\s*\w+").unwrap());
1120
1121        let result = RE_CHARSET.replace_all(stmt, "").to_string();
1122        RE_COLLATE.replace_all(&result, "").to_string()
1123    }
1124
1125    /// Case-insensitively checks whether `keyword` starts at `chars[pos]`, with
1126    /// word boundaries on both sides (so e.g. "COMMENT" doesn't match inside
1127    /// "COMMENTARY" or a preceding identifier char like "XCOMMENT"). Returns the
1128    /// index just past the keyword on success.
1129    fn match_keyword_ci(chars: &[char], pos: usize, keyword: &str) -> Option<usize> {
1130        let kw_len = keyword.len();
1131        if pos > 0 && (chars[pos - 1].is_alphanumeric() || chars[pos - 1] == '_') {
1132            return None;
1133        }
1134        let end = pos + kw_len;
1135        if end > chars.len() {
1136            return None;
1137        }
1138        let candidate: String = chars[pos..end].iter().collect();
1139        if !candidate.eq_ignore_ascii_case(keyword) {
1140            return None;
1141        }
1142        if end < chars.len() && (chars[end].is_alphanumeric() || chars[end] == '_') {
1143            return None;
1144        }
1145        Some(end)
1146    }
1147
1148    /// Removes trailing whitespace already pushed into `result`, so that stripping
1149    /// a clause also absorbs the whitespace that preceded it (matching the old
1150    /// `\s*<keyword>...` regex behavior).
1151    fn trim_trailing_whitespace(result: &mut String) {
1152        while result.ends_with(|c: char| c.is_whitespace()) {
1153            result.pop();
1154        }
1155    }
1156
1157    /// Strip MySQL table-level `AUTO_INCREMENT=N` option. String-literal-aware so
1158    /// that a DEFAULT value or other string content containing the literal text
1159    /// "AUTO_INCREMENT=N" is left untouched.
1160    /// See https://github.com/HelgeSverre/sql-splitter/issues/64
1161    fn strip_mysql_auto_increment_table_option(&self, stmt: &str) -> String {
1162        let chars: Vec<char> = stmt.chars().collect();
1163        let n = chars.len();
1164        let mut result = String::with_capacity(stmt.len());
1165        let mut in_string = false;
1166        let mut i = 0;
1167
1168        while i < n {
1169            let c = chars[i];
1170            if c == '\'' {
1171                in_string = !in_string;
1172                result.push(c);
1173                i += 1;
1174                continue;
1175            }
1176            if !in_string {
1177                if let Some(after_kw) = Self::match_keyword_ci(&chars, i, "AUTO_INCREMENT") {
1178                    let mut j = after_kw;
1179                    while j < n && chars[j].is_whitespace() {
1180                        j += 1;
1181                    }
1182                    if j < n && chars[j] == '=' {
1183                        j += 1;
1184                        while j < n && chars[j].is_whitespace() {
1185                            j += 1;
1186                        }
1187                        let digits_start = j;
1188                        while j < n && chars[j].is_ascii_digit() {
1189                            j += 1;
1190                        }
1191                        if j > digits_start {
1192                            Self::trim_trailing_whitespace(&mut result);
1193                            i = j;
1194                            continue;
1195                        }
1196                    }
1197                }
1198            }
1199            result.push(c);
1200            i += 1;
1201        }
1202        result
1203    }
1204
1205    /// Strip MySQL column/table `COMMENT 'text'` (or `COMMENT='text'`) annotations.
1206    /// Neither is valid inside a PostgreSQL column definition or as a CREATE TABLE
1207    /// table option, so they are removed entirely rather than translated.
1208    /// String-literal-aware: only matches a real `COMMENT` clause, never the word
1209    /// "comment" sitting inside an unrelated DEFAULT value or CHECK expression.
1210    fn strip_mysql_comment_clauses(&self, stmt: &str) -> String {
1211        if self.to == SqlDialect::MySql {
1212            return stmt.to_string();
1213        }
1214
1215        let chars: Vec<char> = stmt.chars().collect();
1216        let n = chars.len();
1217        let mut result = String::with_capacity(stmt.len());
1218        let mut in_string = false;
1219        let mut i = 0;
1220
1221        while i < n {
1222            let c = chars[i];
1223            if c == '\'' {
1224                in_string = !in_string;
1225                result.push(c);
1226                i += 1;
1227                continue;
1228            }
1229            if !in_string {
1230                if let Some(after_kw) = Self::match_keyword_ci(&chars, i, "COMMENT") {
1231                    let mut j = after_kw;
1232                    while j < n && chars[j].is_whitespace() {
1233                        j += 1;
1234                    }
1235                    if j < n && chars[j] == '=' {
1236                        j += 1;
1237                        while j < n && chars[j].is_whitespace() {
1238                            j += 1;
1239                        }
1240                    }
1241                    if j < n && chars[j] == '\'' {
1242                        // Consume the quoted comment text itself, honoring ''
1243                        // as an escaped quote, then drop the whole clause.
1244                        j += 1;
1245                        loop {
1246                            if j >= n {
1247                                break;
1248                            }
1249                            if chars[j] == '\'' {
1250                                if j + 1 < n && chars[j + 1] == '\'' {
1251                                    j += 2;
1252                                    continue;
1253                                }
1254                                j += 1;
1255                                break;
1256                            }
1257                            j += 1;
1258                        }
1259                        Self::trim_trailing_whitespace(&mut result);
1260                        i = j;
1261                        continue;
1262                    }
1263                }
1264            }
1265            result.push(c);
1266            i += 1;
1267        }
1268        result
1269    }
1270
1271    /// Convert MySQL's column-level `AUTO_INCREMENT` keyword to PostgreSQL's
1272    /// `SERIAL`/`BIGSERIAL`, case-insensitively and string-literal-aware (a
1273    /// DEFAULT value or CHECK expression containing the literal text
1274    /// "AUTO_INCREMENT" must not be touched — see finding in issue #64 follow-up
1275    /// review).
1276    fn convert_mysql_auto_increment_keyword(&self, stmt: &str) -> String {
1277        let chars: Vec<char> = stmt.chars().collect();
1278        let n = chars.len();
1279        let mut result = String::with_capacity(stmt.len());
1280        let mut in_string = false;
1281        let mut i = 0;
1282
1283        while i < n {
1284            let c = chars[i];
1285            if c == '\'' {
1286                in_string = !in_string;
1287                result.push(c);
1288                i += 1;
1289                continue;
1290            }
1291            if !in_string {
1292                if let Some(after_type) = Self::match_keyword_ci(&chars, i, "BIGINT") {
1293                    let mut j = after_type;
1294                    while j < n && chars[j].is_whitespace() {
1295                        j += 1;
1296                    }
1297                    if let Some(end) = Self::match_keyword_ci(&chars, j, "AUTO_INCREMENT") {
1298                        result.push_str("BIGSERIAL");
1299                        i = end;
1300                        continue;
1301                    }
1302                }
1303                if let Some(after_type) = Self::match_keyword_ci(&chars, i, "INT") {
1304                    let mut j = after_type;
1305                    while j < n && chars[j].is_whitespace() {
1306                        j += 1;
1307                    }
1308                    if let Some(end) = Self::match_keyword_ci(&chars, j, "AUTO_INCREMENT") {
1309                        result.push_str("SERIAL");
1310                        i = end;
1311                        continue;
1312                    }
1313                }
1314                if let Some(end) = Self::match_keyword_ci(&chars, i, "AUTO_INCREMENT") {
1315                    // Clean up any remaining standalone occurrence (e.g. when
1316                    // other modifiers like NOT NULL sit between the type and
1317                    // the keyword).
1318                    i = end;
1319                    continue;
1320                }
1321            }
1322            result.push(c);
1323            i += 1;
1324        }
1325        result
1326    }
1327
1328    /// Convert MySQL `UNIQUE KEY [name] (cols) [USING BTREE|HASH]` table constraint
1329    /// to standard `UNIQUE (cols)`, which is the closest PostgreSQL equivalent.
1330    /// Also strips MySQL prefix-length index annotations (e.g. `email(191)`),
1331    /// which have no PostgreSQL equivalent and aren't valid there.
1332    fn convert_unique_key_constraint(&self, stmt: &str) -> String {
1333        use once_cell::sync::Lazy;
1334        use regex::{Captures, Regex};
1335
1336        if self.to == SqlDialect::MySql {
1337            return stmt.to_string();
1338        }
1339
1340        // The column-list group allows one level of nested `(digits)` prefix-length
1341        // annotations (e.g. `("email"(191),"other")`), which are common in
1342        // real-world MySQL dumps using utf8mb4 prefix indexes.
1343        static RE: Lazy<Regex> = Lazy::new(|| {
1344            Regex::new(
1345                r#"(?i)UNIQUE\s+KEY\s+(?:"[^"]*"\s+)?(\([^()]*(?:\(\d+\)[^()]*)*\))(?:\s*USING\s+(?:BTREE|HASH))?"#,
1346            )
1347            .unwrap()
1348        });
1349        static RE_PREFIX_LEN: Lazy<Regex> = Lazy::new(|| Regex::new(r"\(\d+\)").unwrap());
1350
1351        RE.replace_all(stmt, |caps: &Captures| {
1352            let cols = RE_PREFIX_LEN.replace_all(&caps[1], "");
1353            format!("UNIQUE {}", cols)
1354        })
1355        .to_string()
1356    }
1357
1358    /// Strip PostgreSQL type casts (::type and ::regclass)
1359    fn strip_postgres_casts(&self, stmt: &str) -> String {
1360        use once_cell::sync::Lazy;
1361        use regex::Regex;
1362
1363        // Match ::regclass, ::text, ::integer, etc. (including complex types like character varying)
1364        static RE_CAST: Lazy<Regex> = Lazy::new(|| {
1365            Regex::new(r"::[a-zA-Z_][a-zA-Z0-9_]*(?:\s+[a-zA-Z_][a-zA-Z0-9_]*)*").unwrap()
1366        });
1367
1368        // Only outside string literals: a value like '2001:db8::1' or
1369        // 'a::b text' must keep its ':: …' rather than have it stripped.
1370        map_outside_string_literals(stmt, |seg| RE_CAST.replace_all(seg, "").into_owned())
1371    }
1372
1373    /// Convert nextval('sequence') to NULL or remove (AUTO_INCREMENT handles it)
1374    fn convert_nextval(&self, stmt: &str) -> String {
1375        use once_cell::sync::Lazy;
1376        use regex::Regex;
1377
1378        // Match nextval('sequence_name'::regclass) or nextval('sequence_name')
1379        // Remove the DEFAULT nextval(...) entirely - AUTO_INCREMENT is already applied
1380        static RE_NEXTVAL: Lazy<Regex> =
1381            Lazy::new(|| Regex::new(r"(?i)\s*DEFAULT\s+nextval\s*\([^)]+\)").unwrap());
1382
1383        RE_NEXTVAL.replace_all(stmt, "").to_string()
1384    }
1385
1386    /// Rebuild a PostgreSQL sequence-backed default as a MySQL AUTO_INCREMENT
1387    /// column, returned as a statement to emit once the dump is fully applied.
1388    ///
1389    /// MySQL rejects an AUTO_INCREMENT column that is not a key, and pg_dump
1390    /// emits the primary key after the table data, so this cannot be applied in
1391    /// place — it has to run last. `MODIFY COLUMN` also takes a full column
1392    /// definition, so the type is read back from the `CREATE TABLE` this
1393    /// converter already emitted.
1394    ///
1395    /// Returns `None` when the target is not MySQL, when the table was never
1396    /// seen, or when the column's type does not read as an integer — in every
1397    /// one of those cases the caller drops the statement with a warning rather
1398    /// than emit a half-formed `MODIFY`.
1399    fn defer_mysql_auto_increment(&self, stmt: &str) -> Option<String> {
1400        use once_cell::sync::Lazy;
1401        use regex::Regex;
1402
1403        static RE_SEQUENCE_TARGET: Lazy<Regex> = Lazy::new(|| {
1404            Regex::new(
1405                r"(?is)\bALTER\s+TABLE\s+(?:ONLY\s+)?(?P<table>\S+)\s+ALTER\s+COLUMN\s+(?P<column>[^\s]+)\s+SET\s+DEFAULT\s+nextval",
1406            )
1407            .unwrap()
1408        });
1409
1410        if self.to != SqlDialect::MySql {
1411            return None;
1412        }
1413
1414        let caps = RE_SEQUENCE_TARGET.captures(stmt)?;
1415        let table = table_key(&caps["table"]);
1416        let column = caps["column"].trim_matches(|c| c == '"' || c == '`');
1417        let create_table = self.created_tables.get(&table)?;
1418        let column_type = declared_column_type(create_table, column)?;
1419
1420        // A sequence always backs an integer column. Anything else means the
1421        // type was misread, and a wrong MODIFY would rewrite the column.
1422        if !matches!(
1423            column_type.to_uppercase().as_str(),
1424            "INT" | "INTEGER" | "BIGINT" | "SMALLINT" | "MEDIUMINT" | "TINYINT"
1425        ) {
1426            return None;
1427        }
1428
1429        Some(format!(
1430            "ALTER TABLE `{table}` MODIFY COLUMN `{column}` {column_type} NOT NULL AUTO_INCREMENT;"
1431        ))
1432    }
1433
1434    /// Strip PostgreSQL's `ONLY` inheritance qualifier from `ALTER TABLE ONLY t`.
1435    /// pg_dump attaches every constraint and column default that way, and no
1436    /// other engine accepts the keyword.
1437    fn strip_postgres_only(&self, stmt: &str) -> String {
1438        use once_cell::sync::Lazy;
1439        use regex::Regex;
1440
1441        static RE_ALTER_ONLY: Lazy<Regex> =
1442            Lazy::new(|| Regex::new(r"(?i)\b(ALTER\s+TABLE)\s+ONLY\s+").unwrap());
1443
1444        RE_ALTER_ONLY.replace_all(stmt, "$1 ").to_string()
1445    }
1446
1447    /// Whether an `ALTER TABLE` exists only to attach a sequence-backed default
1448    /// (`ALTER COLUMN x SET DEFAULT nextval(...)`) — pg_dump's expansion of a
1449    /// `serial` column.
1450    fn is_sequence_default_alter(&self, stmt: &str) -> bool {
1451        use once_cell::sync::Lazy;
1452        use regex::Regex;
1453
1454        static RE_SEQUENCE_DEFAULT: Lazy<Regex> = Lazy::new(|| {
1455            Regex::new(r"(?is)\bALTER\s+COLUMN\b.*?\bSET\s+DEFAULT\s+nextval\s*\(").unwrap()
1456        });
1457
1458        RE_SEQUENCE_DEFAULT.is_match(stmt)
1459    }
1460
1461    /// Whether the statement is a psql client meta-command rather than SQL.
1462    /// `\.` is excluded: it terminates a COPY data block and belongs to the
1463    /// COPY path.
1464    fn is_psql_meta_command(&self, stmt: &str) -> bool {
1465        let stripped = self.strip_leading_sql_comments(stmt);
1466        let trimmed = stripped.trim_start();
1467        trimmed.starts_with('\\') && !trimmed.starts_with("\\.")
1468    }
1469
1470    /// Convert DEFAULT now() to DEFAULT CURRENT_TIMESTAMP
1471    fn convert_default_now(&self, stmt: &str) -> String {
1472        use once_cell::sync::Lazy;
1473        use regex::Regex;
1474
1475        static RE_NOW: Lazy<Regex> =
1476            Lazy::new(|| Regex::new(r"(?i)\bDEFAULT\s+now\s*\(\s*\)").unwrap());
1477
1478        RE_NOW
1479            .replace_all(stmt, "DEFAULT CURRENT_TIMESTAMP")
1480            .to_string()
1481    }
1482
1483    /// Strip schema prefix from table names (e.g., public.users -> users)
1484    fn strip_schema_prefix(&self, stmt: &str) -> String {
1485        use once_cell::sync::Lazy;
1486        use regex::Regex;
1487
1488        // Match schema.table patterns (with optional quotes)
1489        // Handle: public.table, "public"."table", public."table"
1490        static RE_SCHEMA: Lazy<Regex> =
1491            Lazy::new(|| Regex::new(r#"(?i)\b(public|pg_catalog|pg_temp)\s*\.\s*"#).unwrap());
1492
1493        // Only outside string literals so a value like 'see public.docs' keeps
1494        // its text.
1495        map_outside_string_literals(stmt, |seg| RE_SCHEMA.replace_all(seg, "").into_owned())
1496    }
1497
1498    /// Convert MSSQL GETDATE() to CURRENT_TIMESTAMP
1499    fn convert_mssql_getdate(&self, stmt: &str) -> String {
1500        use once_cell::sync::Lazy;
1501        use regex::Regex;
1502
1503        static RE_GETDATE: Lazy<Regex> =
1504            Lazy::new(|| Regex::new(r"(?i)\bGETDATE\s*\(\s*\)").unwrap());
1505        static RE_SYSDATETIME: Lazy<Regex> =
1506            Lazy::new(|| Regex::new(r"(?i)\bSYSDATETIME\s*\(\s*\)").unwrap());
1507        static RE_GETUTCDATE: Lazy<Regex> =
1508            Lazy::new(|| Regex::new(r"(?i)\bGETUTCDATE\s*\(\s*\)").unwrap());
1509
1510        let result = RE_GETDATE
1511            .replace_all(stmt, "CURRENT_TIMESTAMP")
1512            .to_string();
1513        let result = RE_SYSDATETIME
1514            .replace_all(&result, "CURRENT_TIMESTAMP")
1515            .to_string();
1516        RE_GETUTCDATE
1517            .replace_all(&result, "CURRENT_TIMESTAMP")
1518            .to_string()
1519    }
1520
1521    /// Strip MSSQL ON [filegroup] clause
1522    fn strip_mssql_on_filegroup(&self, stmt: &str) -> String {
1523        use once_cell::sync::Lazy;
1524        use regex::Regex;
1525
1526        // Match ON [PRIMARY] or ON [filegroup_name]
1527        static RE_ON_FILEGROUP: Lazy<Regex> =
1528            Lazy::new(|| Regex::new(r"(?i)\s+ON\s*\[\s*\w+\s*\]").unwrap());
1529
1530        RE_ON_FILEGROUP.replace_all(stmt, "").to_string()
1531    }
1532
1533    /// Strip MSSQL CLUSTERED/NONCLUSTERED keywords
1534    fn strip_mssql_clustered(&self, stmt: &str) -> String {
1535        use once_cell::sync::Lazy;
1536        use regex::Regex;
1537
1538        static RE_CLUSTERED: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bCLUSTERED\s+").unwrap());
1539        static RE_NONCLUSTERED: Lazy<Regex> =
1540            Lazy::new(|| Regex::new(r"(?i)\bNONCLUSTERED\s+").unwrap());
1541
1542        let result = RE_CLUSTERED.replace_all(stmt, "").to_string();
1543        RE_NONCLUSTERED.replace_all(&result, "").to_string()
1544    }
1545
1546    /// Convert MSSQL `N'unicode'` string literals to regular `'unicode'`
1547    /// strings by dropping the `N` prefix. Only a genuine prefix — an `N`
1548    /// immediately before a string-opening quote and not itself inside a string
1549    /// — is converted, so an `N'` sequence appearing inside string data (e.g.
1550    /// `'season N''4'`) is left untouched.
1551    fn convert_mssql_unicode_strings(&self, stmt: &str) -> String {
1552        let bytes = stmt.as_bytes();
1553        let mut out = String::with_capacity(stmt.len());
1554        let mut i = 0;
1555        // Everything in `stmt[..copied]` has already been emitted to `out`.
1556        let mut copied = 0;
1557        while i < bytes.len() {
1558            if bytes[i] == b'\'' {
1559                // A string literal: skip it whole so its contents are preserved.
1560                i = skip_sql_string_literal(bytes, i);
1561            } else if matches!(bytes[i], b'N' | b'n')
1562                && bytes.get(i + 1) == Some(&b'\'')
1563                && (i == 0 || !(bytes[i - 1].is_ascii_alphanumeric() || bytes[i - 1] == b'_'))
1564            {
1565                // A genuine `N'` string prefix: emit up to it, drop the `N`, and
1566                // resume at the opening quote (copied to the literal-skip path).
1567                out.push_str(&stmt[copied..i]);
1568                copied = i + 1;
1569                i += 1;
1570            } else {
1571                i += 1;
1572            }
1573        }
1574        out.push_str(&stmt[copied..]);
1575        out
1576    }
1577
1578    /// Strip MSSQL schema prefix (dbo., etc.) from table names
1579    fn strip_mssql_schema_prefix(&self, stmt: &str) -> String {
1580        use once_cell::sync::Lazy;
1581        use regex::Regex;
1582
1583        // Match [dbo].[table] or dbo.table and keep just [table] or table
1584        // We replace schema.table with just table, handling both bracketed and unbracketed forms
1585        static RE_MSSQL_SCHEMA: Lazy<Regex> =
1586            Lazy::new(|| Regex::new(r"(?i)\[?dbo\]?\s*\.\s*").unwrap());
1587
1588        // Only outside string literals so a value like 'user dbo.smith' keeps
1589        // its text.
1590        map_outside_string_literals(stmt, |seg| {
1591            RE_MSSQL_SCHEMA.replace_all(seg, "").into_owned()
1592        })
1593    }
1594
1595    /// Detect unsupported features and add warnings
1596    fn detect_unsupported_features(
1597        &mut self,
1598        stmt: &str,
1599        table_name: Option<&str>,
1600    ) -> Result<(), ConvertWarning> {
1601        let upper = stmt.to_uppercase();
1602
1603        // MySQL-specific features
1604        if self.from == SqlDialect::MySql {
1605            // ENUM types
1606            if upper.contains("ENUM(") {
1607                let warning = ConvertWarning::UnsupportedFeature {
1608                    feature: format!(
1609                        "ENUM type{}",
1610                        table_name
1611                            .map(|t| format!(" in table {}", t))
1612                            .unwrap_or_default()
1613                    ),
1614                    suggestion: Some(
1615                        "Converted to VARCHAR - consider adding CHECK constraint".to_string(),
1616                    ),
1617                };
1618                self.warnings.add(warning.clone());
1619                if self.strict {
1620                    return Err(warning);
1621                }
1622            }
1623
1624            // SET types (MySQL)
1625            if upper.contains("SET(") {
1626                let warning = ConvertWarning::UnsupportedFeature {
1627                    feature: format!(
1628                        "SET type{}",
1629                        table_name
1630                            .map(|t| format!(" in table {}", t))
1631                            .unwrap_or_default()
1632                    ),
1633                    suggestion: Some(
1634                        "Converted to VARCHAR - SET semantics not preserved".to_string(),
1635                    ),
1636                };
1637                self.warnings.add(warning.clone());
1638                if self.strict {
1639                    return Err(warning);
1640                }
1641            }
1642
1643            // UNSIGNED
1644            if upper.contains("UNSIGNED") {
1645                self.warnings.add(ConvertWarning::UnsupportedFeature {
1646                    feature: "UNSIGNED modifier".to_string(),
1647                    suggestion: Some(
1648                        "Removed - consider adding CHECK constraint for non-negative values"
1649                            .to_string(),
1650                    ),
1651                });
1652            }
1653        }
1654
1655        // PostgreSQL-specific features
1656        if self.from == SqlDialect::Postgres {
1657            // Array types
1658            if upper.contains("[]") || upper.contains("ARRAY[") {
1659                let warning = ConvertWarning::UnsupportedFeature {
1660                    feature: format!(
1661                        "Array type{}",
1662                        table_name
1663                            .map(|t| format!(" in table {}", t))
1664                            .unwrap_or_default()
1665                    ),
1666                    suggestion: Some(
1667                        "Array types not supported in target dialect - consider using JSON"
1668                            .to_string(),
1669                    ),
1670                };
1671                self.warnings.add(warning.clone());
1672                if self.strict {
1673                    return Err(warning);
1674                }
1675            }
1676
1677            // INHERITS
1678            if upper.contains("INHERITS") {
1679                let warning = ConvertWarning::UnsupportedFeature {
1680                    feature: "Table inheritance (INHERITS)".to_string(),
1681                    suggestion: Some(
1682                        "PostgreSQL table inheritance not supported in target dialect".to_string(),
1683                    ),
1684                };
1685                self.warnings.add(warning.clone());
1686                if self.strict {
1687                    return Err(warning);
1688                }
1689            }
1690
1691            // PARTITION BY
1692            if upper.contains("PARTITION BY") && self.to == SqlDialect::Sqlite {
1693                let warning = ConvertWarning::UnsupportedFeature {
1694                    feature: "Table partitioning".to_string(),
1695                    suggestion: Some("Partitioning not supported in SQLite".to_string()),
1696                };
1697                self.warnings.add(warning.clone());
1698                if self.strict {
1699                    return Err(warning);
1700                }
1701            }
1702        }
1703
1704        Ok(())
1705    }
1706
1707    /// Get collected warnings
1708    pub fn warnings(&self) -> &[ConvertWarning] {
1709        self.warnings.warnings()
1710    }
1711}
1712
1713/// Run the convert command
1714pub fn run(config: ConvertConfig) -> anyhow::Result<ConvertStats> {
1715    let mut stats = ConvertStats::default();
1716
1717    // Detect or use specified source dialect
1718    let from_dialect = if let Some(d) = config.from_dialect {
1719        d
1720    } else {
1721        let result = crate::parser::detect_dialect_from_file(&config.input)?;
1722        if config.progress {
1723            eprintln!(
1724                "Auto-detected source dialect: {} (confidence: {:?})",
1725                result.dialect, result.confidence
1726            );
1727        }
1728        result.dialect
1729    };
1730
1731    // Check for same dialect
1732    if from_dialect == config.to_dialect {
1733        anyhow::bail!(
1734            "Source and target dialects are the same ({}). No conversion needed.",
1735            from_dialect
1736        );
1737    }
1738
1739    // Get file size for progress tracking
1740    let file_size = std::fs::metadata(&config.input)?.len();
1741
1742    let progress_bar = if config.progress {
1743        let pb = ProgressBar::new(file_size);
1744        pb.set_style(
1745            ProgressStyle::with_template(
1746                "{spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] {bytes}/{total_bytes} ({percent}%) {msg}",
1747            )
1748            .unwrap()
1749            .progress_chars("█▓▒░  ")
1750            .tick_chars("⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"),
1751        );
1752        pb.enable_steady_tick(std::time::Duration::from_millis(100));
1753        pb.set_message("Converting...");
1754        Some(pb)
1755    } else {
1756        None
1757    };
1758
1759    // Create converter
1760    let mut converter = Converter::new(from_dialect, config.to_dialect).with_strict(config.strict);
1761
1762    // Open input, transparently handling any supported compression format
1763    // (including zip archives), with optional progress tracking.
1764    let reader: Box<dyn Read> = if let Some(ref pb) = progress_bar {
1765        let pb_clone = pb.clone();
1766        open_input_with_progress(
1767            &config.input,
1768            Box::new(move |bytes| pb_clone.set_position(bytes)),
1769        )?
1770    } else {
1771        open_input(&config.input)?
1772    };
1773    let mut parser = Parser::with_dialect(reader, 64 * 1024, from_dialect);
1774
1775    // Open output
1776    let mut writer: Box<dyn Write> = if config.dry_run {
1777        Box::new(std::io::sink())
1778    } else {
1779        match &config.output {
1780            Some(path) => {
1781                if let Some(parent) = path.parent() {
1782                    std::fs::create_dir_all(parent)?;
1783                }
1784                Box::new(BufWriter::with_capacity(256 * 1024, File::create(path)?))
1785            }
1786            None => Box::new(BufWriter::new(std::io::stdout())),
1787        }
1788    };
1789
1790    // Write header
1791    if !config.dry_run {
1792        write_header(&mut writer, &config, from_dialect)?;
1793    }
1794
1795    // Process statements
1796    while let Some(stmt) = parser.read_statement()? {
1797        stats.statements_processed += 1;
1798
1799        // Check if this is a COPY data block (follows a COPY header)
1800        if converter.has_pending_copy() {
1801            // This is a data block, convert it to INSERT statements
1802            match converter.process_copy_data(&stmt) {
1803                Ok(inserts) => {
1804                    for insert in inserts {
1805                        if !insert.is_empty() {
1806                            stats.statements_converted += 1;
1807                            if !config.dry_run {
1808                                writer.write_all(&insert)?;
1809                                writer.write_all(b"\n")?;
1810                            }
1811                        }
1812                    }
1813                }
1814                Err(warning) => {
1815                    stats.warnings.push(warning);
1816                    stats.statements_skipped += 1;
1817                }
1818            }
1819            continue;
1820        }
1821
1822        match converter.convert_statement(&stmt) {
1823            Ok(converted) => {
1824                if converted.is_empty() {
1825                    stats.statements_skipped += 1;
1826                } else if converted == stmt {
1827                    stats.statements_unchanged += 1;
1828                    if !config.dry_run {
1829                        writer.write_all(&converted)?;
1830                        writer.write_all(b"\n")?;
1831                    }
1832                } else {
1833                    stats.statements_converted += 1;
1834                    if !config.dry_run {
1835                        writer.write_all(&converted)?;
1836                        writer.write_all(b"\n")?;
1837                    }
1838                }
1839            }
1840            Err(warning) => {
1841                stats.warnings.push(warning);
1842                stats.statements_skipped += 1;
1843            }
1844        }
1845    }
1846
1847    // Statements that only become valid once everything else has been applied
1848    // (a MySQL AUTO_INCREMENT column has to be a key first, and pg_dump adds the
1849    // primary key after the data).
1850    for statement in converter.take_deferred_statements() {
1851        stats.statements_converted += 1;
1852        if !config.dry_run {
1853            writer.write_all(statement.as_bytes())?;
1854            writer.write_all(b"\n")?;
1855        }
1856    }
1857
1858    // Collect warnings
1859    stats.warnings.extend(converter.warnings().iter().cloned());
1860
1861    if let Some(pb) = progress_bar {
1862        pb.finish_with_message("done");
1863    }
1864
1865    Ok(stats)
1866}
1867
1868/// Write output header
1869fn write_header(
1870    writer: &mut dyn Write,
1871    config: &ConvertConfig,
1872    from: SqlDialect,
1873) -> std::io::Result<()> {
1874    writeln!(writer, "-- Converted by sql-splitter")?;
1875    writeln!(writer, "-- From: {} → To: {}", from, config.to_dialect)?;
1876    writeln!(writer, "-- Source: {}", config.input.display())?;
1877    writeln!(writer)?;
1878
1879    // Write dialect-specific header
1880    match config.to_dialect {
1881        SqlDialect::Postgres => {
1882            writeln!(writer, "SET client_encoding = 'UTF8';")?;
1883            writeln!(writer, "SET standard_conforming_strings = on;")?;
1884        }
1885        SqlDialect::Sqlite => {
1886            writeln!(writer, "PRAGMA foreign_keys = OFF;")?;
1887        }
1888        SqlDialect::MySql => {
1889            writeln!(writer, "SET NAMES utf8mb4;")?;
1890            writeln!(writer, "SET FOREIGN_KEY_CHECKS = 0;")?;
1891        }
1892        SqlDialect::Mssql => {
1893            writeln!(writer, "SET ANSI_NULLS ON;")?;
1894            writeln!(writer, "SET QUOTED_IDENTIFIER ON;")?;
1895            writeln!(writer, "SET NOCOUNT ON;")?;
1896        }
1897    }
1898    writeln!(writer)?;
1899
1900    Ok(())
1901}
1902
1903/// Advance past a single-quoted SQL string literal starting at `start` (the
1904/// opening quote), returning the index just past the closing quote. A doubled
1905/// `''` is an escaped quote that keeps the string open. An unterminated literal
1906/// consumes to the end. `bytes[start]` must be `'`.
1907fn skip_sql_string_literal(bytes: &[u8], start: usize) -> usize {
1908    let mut i = start + 1;
1909    while i < bytes.len() {
1910        if bytes[i] == b'\'' {
1911            if bytes.get(i + 1) == Some(&b'\'') {
1912                i += 2; // escaped quote, stay inside the string
1913            } else {
1914                return i + 1; // closing quote
1915            }
1916        } else {
1917            i += 1;
1918        }
1919    }
1920    i
1921}
1922
1923/// Apply `f` to every span of `stmt` that lies outside a single-quoted string
1924/// literal, copying the literals through verbatim. Used to keep statement-level
1925/// rewrites (cast/schema-prefix stripping) from mangling string *data*.
1926fn map_outside_string_literals(stmt: &str, f: impl Fn(&str) -> String) -> String {
1927    let bytes = stmt.as_bytes();
1928    let mut out = String::with_capacity(stmt.len());
1929    let mut i = 0;
1930    let mut seg_start = 0;
1931    while i < bytes.len() {
1932        if bytes[i] == b'\'' {
1933            // Flush the preceding non-string span through `f`.
1934            out.push_str(&f(&stmt[seg_start..i]));
1935            let lit_end = skip_sql_string_literal(bytes, i);
1936            out.push_str(&stmt[i..lit_end]); // literal, verbatim
1937            i = lit_end;
1938            seg_start = i;
1939        } else {
1940            i += 1;
1941        }
1942    }
1943    out.push_str(&f(&stmt[seg_start..]));
1944    out
1945}