sql-splitter 1.13.1

High-performance CLI tool for splitting large SQL dump files into individual table files
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
//! Convert command for translating SQL dumps between dialects.
//!
//! Supports conversion between MySQL, PostgreSQL, and SQLite dialects with:
//! - Identifier quoting conversion (backticks ↔ double quotes)
//! - String escape normalization (\' ↔ '')
//! - Data type mapping (AUTO_INCREMENT ↔ SERIAL ↔ INTEGER PRIMARY KEY)
//! - COPY FROM stdin → INSERT conversion
//! - Session header conversion
//! - Warning system for unsupported features

pub mod copy_to_insert;
mod types;
mod warnings;

#[allow(unused_imports)]
pub use copy_to_insert::{
    copy_to_inserts, parse_copy_data, parse_copy_header, CopyHeader, CopyValue,
};

use crate::parser::{Parser, SqlDialect, StatementType};
use crate::progress::ProgressReader;
use crate::splitter::Compression;
use indicatif::{ProgressBar, ProgressStyle};
use std::fs::File;
use std::io::{BufWriter, Read, Write};
use std::path::PathBuf;

pub use types::TypeMapper;
pub use warnings::{print_warnings_summary, ConvertWarning, WarningCollector};

/// Configuration for the convert command
#[derive(Debug)]
pub struct ConvertConfig {
    /// Input SQL file
    pub input: PathBuf,
    /// Output SQL file (None for stdout)
    pub output: Option<PathBuf>,
    /// Source dialect (auto-detected if None)
    pub from_dialect: Option<SqlDialect>,
    /// Target dialect
    pub to_dialect: SqlDialect,
    /// Dry run mode
    pub dry_run: bool,
    /// Show progress
    pub progress: bool,
    /// Strict mode (fail on any unsupported feature)
    pub strict: bool,
}

impl Default for ConvertConfig {
    fn default() -> Self {
        Self {
            input: PathBuf::new(),
            output: None,
            from_dialect: None,
            to_dialect: SqlDialect::Postgres,
            dry_run: false,
            progress: false,
            strict: false,
        }
    }
}

/// Statistics from convert operation
#[derive(Debug, Default, serde::Serialize)]
pub struct ConvertStats {
    /// Total statements processed
    pub statements_processed: u64,
    /// Statements converted
    pub statements_converted: u64,
    /// Statements passed through unchanged
    pub statements_unchanged: u64,
    /// Statements skipped (unsupported)
    pub statements_skipped: u64,
    /// Warnings generated
    pub warnings: Vec<ConvertWarning>,
}

/// Main converter that dispatches to specific dialect converters
pub struct Converter {
    from: SqlDialect,
    to: SqlDialect,
    warnings: WarningCollector,
    strict: bool,
    /// Pending COPY header for data block processing
    pending_copy_header: Option<CopyHeader>,
}

impl Converter {
    pub fn new(from: SqlDialect, to: SqlDialect) -> Self {
        Self {
            from,
            to,
            warnings: WarningCollector::new(),
            strict: false,
            pending_copy_header: None,
        }
    }

    pub fn with_strict(mut self, strict: bool) -> Self {
        self.strict = strict;
        self
    }

    /// Check if we have a pending COPY header (waiting for data block)
    pub fn has_pending_copy(&self) -> bool {
        self.pending_copy_header.is_some()
    }

    /// Process a COPY data block using the pending header
    pub fn process_copy_data(&mut self, data: &[u8]) -> Result<Vec<Vec<u8>>, ConvertWarning> {
        if let Some(header) = self.pending_copy_header.take() {
            if self.from == SqlDialect::Postgres && self.to != SqlDialect::Postgres {
                // Convert COPY data to INSERT statements
                let inserts = copy_to_inserts(&header, data, self.to);
                return Ok(inserts);
            }
        }
        // Pass through if same dialect or no pending header
        Ok(vec![data.to_vec()])
    }

    /// Convert a single statement
    pub fn convert_statement(&mut self, stmt: &[u8]) -> Result<Vec<u8>, ConvertWarning> {
        let (stmt_type, table_name) =
            Parser::<&[u8]>::parse_statement_with_dialect(stmt, self.from);

        let table = if table_name.is_empty() {
            None
        } else {
            Some(table_name.as_str())
        };

        match stmt_type {
            StatementType::CreateTable => self.convert_create_table(stmt, table),
            StatementType::Insert => self.convert_insert(stmt, table),
            StatementType::CreateIndex => self.convert_create_index(stmt),
            StatementType::AlterTable => self.convert_alter_table(stmt),
            StatementType::DropTable => self.convert_drop_table(stmt),
            StatementType::Copy => self.convert_copy(stmt, table),
            StatementType::Unknown => self.convert_other(stmt),
        }
    }

    /// Convert CREATE TABLE statement
    fn convert_create_table(
        &mut self,
        stmt: &[u8],
        table_name: Option<&str>,
    ) -> Result<Vec<u8>, ConvertWarning> {
        let stmt_str = String::from_utf8_lossy(stmt);
        let mut result = stmt_str.to_string();

        // Detect unsupported features BEFORE conversion (so we see original types)
        self.detect_unsupported_features(&result, table_name)?;

        // Convert MSSQL-specific syntax BEFORE identifier conversion
        // (so we can strip [dbo]. schema prefix properly)
        if self.from == SqlDialect::Mssql && self.to != SqlDialect::Mssql {
            result = self.strip_mssql_schema_prefix(&result);
            result = self.convert_mssql_getdate(&result);
            result = self.strip_mssql_on_filegroup(&result);
            result = self.strip_mssql_clustered(&result);
            result = self.convert_mssql_unicode_strings(&result);
        }

        // Convert identifier quoting
        result = self.convert_identifiers(&result);

        // Convert data types
        result = self.convert_data_types(&result);

        // Convert AUTO_INCREMENT
        result = self.convert_auto_increment(&result, table_name);

        // Convert PostgreSQL-specific syntax
        if self.from == SqlDialect::Postgres && self.to != SqlDialect::Postgres {
            result = self.strip_postgres_casts(&result);
            result = self.convert_nextval(&result);
            result = self.convert_default_now(&result);
            result = self.strip_schema_prefix(&result);
        }

        // Convert string escapes
        result = self.convert_string_escapes(&result);

        // Strip MySQL conditional comments
        result = self.strip_conditional_comments(&result);

        // Convert ENGINE clause
        result = self.strip_engine_clause(&result);

        // Convert CHARSET/COLLATE
        result = self.strip_charset_clauses(&result);

        Ok(result.into_bytes())
    }

    /// Convert INSERT statement
    fn convert_insert(
        &mut self,
        stmt: &[u8],
        _table_name: Option<&str>,
    ) -> Result<Vec<u8>, ConvertWarning> {
        let stmt_str = String::from_utf8_lossy(stmt);
        let mut result = stmt_str.to_string();

        // Convert MSSQL-specific syntax BEFORE identifier conversion
        if self.from == SqlDialect::Mssql && self.to != SqlDialect::Mssql {
            result = self.strip_mssql_schema_prefix(&result);
            result = self.convert_mssql_unicode_strings(&result);
        }

        // Convert identifier quoting
        result = self.convert_identifiers(&result);

        // Convert PostgreSQL-specific syntax
        if self.from == SqlDialect::Postgres && self.to != SqlDialect::Postgres {
            result = self.strip_postgres_casts(&result);
            result = self.strip_schema_prefix(&result);
        }

        // Convert string escapes (careful with data!)
        result = self.convert_string_escapes(&result);

        Ok(result.into_bytes())
    }

    /// Convert CREATE INDEX statement
    fn convert_create_index(&mut self, stmt: &[u8]) -> Result<Vec<u8>, ConvertWarning> {
        let stmt_str = String::from_utf8_lossy(stmt);
        let mut result = stmt_str.to_string();

        // Convert MSSQL-specific syntax BEFORE identifier conversion
        if self.from == SqlDialect::Mssql && self.to != SqlDialect::Mssql {
            result = self.strip_mssql_schema_prefix(&result);
            result = self.strip_mssql_clustered(&result);
        }

        // Convert identifier quoting
        result = self.convert_identifiers(&result);

        // Convert PostgreSQL-specific syntax
        if self.from == SqlDialect::Postgres && self.to != SqlDialect::Postgres {
            result = self.strip_postgres_casts(&result);
            result = self.strip_schema_prefix(&result);
        }

        // Detect FULLTEXT/SPATIAL
        if result.contains("FULLTEXT") || result.contains("fulltext") {
            self.warnings.add(ConvertWarning::UnsupportedFeature {
                feature: "FULLTEXT INDEX".to_string(),
                suggestion: Some("Use PostgreSQL GIN index or skip".to_string()),
            });
            if self.strict {
                return Err(ConvertWarning::UnsupportedFeature {
                    feature: "FULLTEXT INDEX".to_string(),
                    suggestion: None,
                });
            }
        }

        Ok(result.into_bytes())
    }

    /// Convert ALTER TABLE statement
    fn convert_alter_table(&mut self, stmt: &[u8]) -> Result<Vec<u8>, ConvertWarning> {
        let stmt_str = String::from_utf8_lossy(stmt);
        let mut result = stmt_str.to_string();

        result = self.convert_identifiers(&result);
        result = self.convert_data_types(&result);

        // Convert PostgreSQL-specific syntax
        if self.from == SqlDialect::Postgres && self.to != SqlDialect::Postgres {
            result = self.strip_postgres_casts(&result);
            result = self.convert_nextval(&result);
            result = self.convert_default_now(&result);
            result = self.strip_schema_prefix(&result);
        }

        Ok(result.into_bytes())
    }

    /// Convert DROP TABLE statement
    fn convert_drop_table(&mut self, stmt: &[u8]) -> Result<Vec<u8>, ConvertWarning> {
        let stmt_str = String::from_utf8_lossy(stmt);
        let mut result = stmt_str.to_string();

        result = self.convert_identifiers(&result);

        // Strip PostgreSQL schema prefix
        if self.from == SqlDialect::Postgres && self.to != SqlDialect::Postgres {
            result = self.strip_schema_prefix(&result);
        }

        Ok(result.into_bytes())
    }

    /// Convert COPY statement (PostgreSQL-specific)
    ///
    /// This handles the COPY header. The data block is processed separately
    /// via process_copy_data() when called from the run() function.
    fn convert_copy(
        &mut self,
        stmt: &[u8],
        _table_name: Option<&str>,
    ) -> Result<Vec<u8>, ConvertWarning> {
        let stmt_str = String::from_utf8_lossy(stmt);

        // Check if this contains "FROM stdin" (COPY header) or is data
        let upper = stmt_str.to_uppercase();
        if upper.contains("FROM STDIN") {
            // This is a COPY header - parse it and store for later
            if let Some(header) = parse_copy_header(&stmt_str) {
                if self.from == SqlDialect::Postgres && self.to != SqlDialect::Postgres {
                    // Store the header, will convert data block in process_copy_data
                    self.pending_copy_header = Some(header);
                    // Return empty - the actual INSERT will be generated from data
                    return Ok(Vec::new());
                }
            }
        }

        // If same dialect or couldn't parse, pass through
        Ok(stmt.to_vec())
    }

    /// Convert other statements (comments, session settings, etc.)
    fn convert_other(&mut self, stmt: &[u8]) -> Result<Vec<u8>, ConvertWarning> {
        let stmt_str = String::from_utf8_lossy(stmt);
        let result = stmt_str.to_string();
        let trimmed = result.trim();

        // Skip MySQL session commands when converting to other dialects
        if self.from == SqlDialect::MySql
            && self.to != SqlDialect::MySql
            && self.is_mysql_session_command(&result)
        {
            return Ok(Vec::new()); // Skip
        }

        // Skip PostgreSQL session commands and unsupported features when converting to other dialects
        if self.from == SqlDialect::Postgres
            && self.to != SqlDialect::Postgres
            && self.is_postgres_session_command(&result)
        {
            return Ok(Vec::new()); // Skip
        }
        if self.from == SqlDialect::Postgres
            && self.to != SqlDialect::Postgres
            && self.is_postgres_only_feature(trimmed)
        {
            self.warnings.add(ConvertWarning::SkippedStatement {
                reason: "PostgreSQL-only feature".to_string(),
                statement_preview: trimmed.chars().take(60).collect(),
            });
            return Ok(Vec::new()); // Skip
        }

        // Skip SQLite pragmas when converting to other dialects
        if self.from == SqlDialect::Sqlite
            && self.to != SqlDialect::Sqlite
            && self.is_sqlite_pragma(&result)
        {
            return Ok(Vec::new()); // Skip
        }

        // Skip MSSQL session commands when converting to other dialects
        if self.from == SqlDialect::Mssql
            && self.to != SqlDialect::Mssql
            && self.is_mssql_session_command(&result)
        {
            return Ok(Vec::new()); // Skip
        }

        // Strip conditional comments
        if result.contains("/*!") {
            let stripped = self.strip_conditional_comments(&result);
            return Ok(stripped.into_bytes());
        }

        Ok(stmt.to_vec())
    }

    /// Check if statement is a MySQL session command
    fn is_mysql_session_command(&self, stmt: &str) -> bool {
        let upper = stmt.to_uppercase();
        upper.contains("SET NAMES")
            || upper.contains("SET CHARACTER")
            || upper.contains("SET SQL_MODE")
            || upper.contains("SET TIME_ZONE")
            || upper.contains("SET FOREIGN_KEY_CHECKS")
            || upper.contains("LOCK TABLES")
            || upper.contains("UNLOCK TABLES")
    }

    /// Check if statement is a PostgreSQL session command or unsupported statement
    fn is_postgres_session_command(&self, stmt: &str) -> bool {
        let upper = stmt.to_uppercase();
        // Session/transaction settings
        upper.contains("SET CLIENT_ENCODING")
            || upper.contains("SET STANDARD_CONFORMING_STRINGS")
            || upper.contains("SET CHECK_FUNCTION_BODIES")
            || upper.contains("SET SEARCH_PATH")
            || upper.contains("SET DEFAULT_TABLESPACE")
            || upper.contains("SET LOCK_TIMEOUT")
            || upper.contains("SET IDLE_IN_TRANSACTION_SESSION_TIMEOUT")
            || upper.contains("SET ROW_SECURITY")
            || upper.contains("SET STATEMENT_TIMEOUT")
            || upper.contains("SET XMLOPTION")
            || upper.contains("SET CLIENT_MIN_MESSAGES")
            || upper.contains("SET DEFAULT_TABLE_ACCESS_METHOD")
            || upper.contains("SELECT PG_CATALOG")
            // Ownership/permission statements
            || upper.contains("OWNER TO")
            || upper.contains("GRANT ")
            || upper.contains("REVOKE ")
    }

    /// Check if statement is a PostgreSQL-only feature that should be skipped
    fn is_postgres_only_feature(&self, stmt: &str) -> bool {
        // Strip leading comments to find the actual statement
        let stripped = self.strip_leading_sql_comments(stmt);
        let upper = stripped.to_uppercase();

        // These PostgreSQL features have no MySQL/SQLite equivalent
        upper.starts_with("CREATE DOMAIN")
            || upper.starts_with("CREATE TYPE")
            || upper.starts_with("CREATE FUNCTION")
            || upper.starts_with("CREATE PROCEDURE")
            || upper.starts_with("CREATE AGGREGATE")
            || upper.starts_with("CREATE OPERATOR")
            || upper.starts_with("CREATE SEQUENCE")
            || upper.starts_with("CREATE EXTENSION")
            || upper.starts_with("CREATE SCHEMA")
            || upper.starts_with("CREATE TRIGGER")
            || upper.starts_with("ALTER DOMAIN")
            || upper.starts_with("ALTER TYPE")
            || upper.starts_with("ALTER FUNCTION")
            || upper.starts_with("ALTER SEQUENCE")
            || upper.starts_with("ALTER SCHEMA")
            || upper.starts_with("COMMENT ON")
    }

    /// Strip leading SQL comments (-- and /* */) from a string
    fn strip_leading_sql_comments(&self, stmt: &str) -> String {
        let mut result = stmt.trim();
        loop {
            // Strip -- comments
            if result.starts_with("--") {
                if let Some(pos) = result.find('\n') {
                    result = result[pos + 1..].trim();
                    continue;
                } else {
                    return String::new();
                }
            }
            // Strip /* */ comments
            if result.starts_with("/*") {
                if let Some(pos) = result.find("*/") {
                    result = result[pos + 2..].trim();
                    continue;
                } else {
                    return String::new();
                }
            }
            break;
        }
        result.to_string()
    }

    /// Check if statement is a SQLite pragma
    fn is_sqlite_pragma(&self, stmt: &str) -> bool {
        let upper = stmt.to_uppercase();
        upper.contains("PRAGMA")
    }

    /// Check if statement is an MSSQL session command
    fn is_mssql_session_command(&self, stmt: &str) -> bool {
        let upper = stmt.to_uppercase();
        upper.contains("SET ANSI_NULLS")
            || upper.contains("SET QUOTED_IDENTIFIER")
            || upper.contains("SET NOCOUNT")
            || upper.contains("SET XACT_ABORT")
            || upper.contains("SET ARITHABORT")
            || upper.contains("SET ANSI_WARNINGS")
            || upper.contains("SET ANSI_PADDING")
            || upper.contains("SET CONCAT_NULL_YIELDS_NULL")
            || upper.contains("SET NUMERIC_ROUNDABORT")
            || upper.contains("SET IDENTITY_INSERT")
    }

    /// Convert identifier quoting based on dialects
    fn convert_identifiers(&self, stmt: &str) -> String {
        match (self.from, self.to) {
            (SqlDialect::MySql, SqlDialect::Postgres | SqlDialect::Sqlite) => {
                // Backticks → double quotes
                self.backticks_to_double_quotes(stmt)
            }
            (SqlDialect::MySql, SqlDialect::Mssql) => {
                // Backticks → square brackets
                self.backticks_to_square_brackets(stmt)
            }
            (SqlDialect::Postgres | SqlDialect::Sqlite, SqlDialect::MySql) => {
                // Double quotes → backticks
                self.double_quotes_to_backticks(stmt)
            }
            (SqlDialect::Postgres | SqlDialect::Sqlite, SqlDialect::Mssql) => {
                // Double quotes → square brackets
                self.double_quotes_to_square_brackets(stmt)
            }
            (SqlDialect::Mssql, SqlDialect::MySql) => {
                // Square brackets → backticks
                self.square_brackets_to_backticks(stmt)
            }
            (SqlDialect::Mssql, SqlDialect::Postgres | SqlDialect::Sqlite) => {
                // Square brackets → double quotes
                self.square_brackets_to_double_quotes(stmt)
            }
            _ => stmt.to_string(),
        }
    }

    /// Convert backticks to double quotes
    pub fn backticks_to_double_quotes(&self, stmt: &str) -> String {
        let mut result = String::with_capacity(stmt.len());
        let mut in_string = false;
        let mut in_backtick = false;

        for c in stmt.chars() {
            if c == '\'' && !in_backtick {
                in_string = !in_string;
                result.push(c);
            } else if c == '`' && !in_string {
                in_backtick = !in_backtick;
                result.push('"');
            } else {
                result.push(c);
            }
        }
        result
    }

    /// Convert double quotes to backticks
    pub fn double_quotes_to_backticks(&self, stmt: &str) -> String {
        let mut result = String::with_capacity(stmt.len());
        let mut in_string = false;
        let mut in_dquote = false;
        let chars = stmt.chars();

        for c in chars {
            if c == '\'' && !in_dquote {
                in_string = !in_string;
                result.push(c);
            } else if c == '"' && !in_string {
                in_dquote = !in_dquote;
                result.push('`');
            } else {
                result.push(c);
            }
        }
        result
    }

    /// Convert backticks to square brackets (for MSSQL)
    pub fn backticks_to_square_brackets(&self, stmt: &str) -> String {
        let mut result = String::with_capacity(stmt.len());
        let mut in_string = false;
        let mut in_backtick = false;

        for c in stmt.chars() {
            if c == '\'' && !in_backtick {
                in_string = !in_string;
                result.push(c);
            } else if c == '`' && !in_string {
                if !in_backtick {
                    result.push('[');
                } else {
                    result.push(']');
                }
                in_backtick = !in_backtick;
            } else {
                result.push(c);
            }
        }
        result
    }

    /// Convert double quotes to square brackets (for MSSQL)
    pub fn double_quotes_to_square_brackets(&self, stmt: &str) -> String {
        let mut result = String::with_capacity(stmt.len());
        let mut in_string = false;
        let mut in_dquote = false;

        for c in stmt.chars() {
            if c == '\'' && !in_dquote {
                in_string = !in_string;
                result.push(c);
            } else if c == '"' && !in_string {
                if !in_dquote {
                    result.push('[');
                } else {
                    result.push(']');
                }
                in_dquote = !in_dquote;
            } else {
                result.push(c);
            }
        }
        result
    }

    /// Convert square brackets to backticks (from MSSQL to MySQL)
    pub fn square_brackets_to_backticks(&self, stmt: &str) -> String {
        let mut result = String::with_capacity(stmt.len());
        let mut in_string = false;

        for c in stmt.chars() {
            if c == '\'' {
                in_string = !in_string;
                result.push(c);
            } else if !in_string && (c == '[' || c == ']') {
                result.push('`');
            } else {
                result.push(c);
            }
        }
        result
    }

    /// Convert square brackets to double quotes (from MSSQL to PostgreSQL/SQLite)
    pub fn square_brackets_to_double_quotes(&self, stmt: &str) -> String {
        let mut result = String::with_capacity(stmt.len());
        let mut in_string = false;

        for c in stmt.chars() {
            if c == '\'' {
                in_string = !in_string;
                result.push(c);
            } else if !in_string && (c == '[' || c == ']') {
                result.push('"');
            } else {
                result.push(c);
            }
        }
        result
    }

    /// Convert data types between dialects
    fn convert_data_types(&self, stmt: &str) -> String {
        TypeMapper::convert(stmt, self.from, self.to)
    }

    /// Convert AUTO_INCREMENT/SERIAL syntax
    fn convert_auto_increment(&self, stmt: &str, _table_name: Option<&str>) -> String {
        match (self.from, self.to) {
            (SqlDialect::MySql, SqlDialect::Postgres) => {
                // INT AUTO_INCREMENT → SERIAL
                // BIGINT AUTO_INCREMENT → BIGSERIAL
                let result = stmt.replace("BIGINT AUTO_INCREMENT", "BIGSERIAL");
                let result = result.replace("bigint AUTO_INCREMENT", "BIGSERIAL");
                let result = result.replace("INT AUTO_INCREMENT", "SERIAL");
                let result = result.replace("int AUTO_INCREMENT", "SERIAL");
                result.replace("AUTO_INCREMENT", "") // Clean up any remaining
            }
            (SqlDialect::MySql, SqlDialect::Sqlite) => {
                // INT AUTO_INCREMENT PRIMARY KEY → INTEGER PRIMARY KEY
                // The AUTOINCREMENT keyword is optional in SQLite
                let result = stmt.replace("INT AUTO_INCREMENT", "INTEGER");
                let result = result.replace("int AUTO_INCREMENT", "INTEGER");
                result.replace("AUTO_INCREMENT", "")
            }
            (SqlDialect::Postgres, SqlDialect::MySql) => {
                // SERIAL → INT AUTO_INCREMENT
                // BIGSERIAL → BIGINT AUTO_INCREMENT
                let result = stmt.replace("BIGSERIAL", "BIGINT AUTO_INCREMENT");
                let result = result.replace("bigserial", "BIGINT AUTO_INCREMENT");
                let result = result.replace("SMALLSERIAL", "SMALLINT AUTO_INCREMENT");
                let result = result.replace("smallserial", "SMALLINT AUTO_INCREMENT");
                let result = result.replace("SERIAL", "INT AUTO_INCREMENT");
                result.replace("serial", "INT AUTO_INCREMENT")
            }
            (SqlDialect::Postgres, SqlDialect::Sqlite) => {
                // SERIAL → INTEGER (SQLite auto-increments INTEGER PRIMARY KEY)
                let result = stmt.replace("BIGSERIAL", "INTEGER");
                let result = result.replace("bigserial", "INTEGER");
                let result = result.replace("SMALLSERIAL", "INTEGER");
                let result = result.replace("smallserial", "INTEGER");
                let result = result.replace("SERIAL", "INTEGER");
                result.replace("serial", "INTEGER")
            }
            (SqlDialect::Sqlite, SqlDialect::MySql) => {
                // SQLite uses INTEGER PRIMARY KEY for auto-increment
                // We can't easily detect this pattern, so just pass through
                stmt.to_string()
            }
            (SqlDialect::Sqlite, SqlDialect::Postgres) => {
                // SQLite uses INTEGER PRIMARY KEY for auto-increment
                // We can't easily detect this pattern, so just pass through
                stmt.to_string()
            }
            // MSSQL conversions
            (SqlDialect::MySql, SqlDialect::Mssql) => {
                // AUTO_INCREMENT → IDENTITY(1,1)
                let result = stmt.replace("BIGINT AUTO_INCREMENT", "BIGINT IDENTITY(1,1)");
                let result = result.replace("bigint AUTO_INCREMENT", "BIGINT IDENTITY(1,1)");
                let result = result.replace("INT AUTO_INCREMENT", "INT IDENTITY(1,1)");
                let result = result.replace("int AUTO_INCREMENT", "INT IDENTITY(1,1)");
                result.replace("AUTO_INCREMENT", "IDENTITY(1,1)")
            }
            (SqlDialect::Mssql, SqlDialect::MySql) => {
                // IDENTITY(1,1) → AUTO_INCREMENT
                self.convert_identity_to_auto_increment(stmt)
            }
            (SqlDialect::Postgres, SqlDialect::Mssql) => {
                // SERIAL → INT IDENTITY(1,1) (handled by type mapper)
                stmt.to_string()
            }
            (SqlDialect::Mssql, SqlDialect::Postgres) => {
                // IDENTITY(1,1) → SERIAL (need to add SERIAL instead)
                self.convert_identity_to_serial(stmt)
            }
            (SqlDialect::Sqlite, SqlDialect::Mssql) => {
                // SQLite → MSSQL: pass through
                stmt.to_string()
            }
            (SqlDialect::Mssql, SqlDialect::Sqlite) => {
                // IDENTITY → strip (SQLite uses INTEGER PRIMARY KEY)
                self.strip_identity(stmt)
            }
            _ => stmt.to_string(),
        }
    }

    /// Convert MSSQL IDENTITY to MySQL AUTO_INCREMENT
    fn convert_identity_to_auto_increment(&self, stmt: &str) -> String {
        use once_cell::sync::Lazy;
        use regex::Regex;

        static RE_IDENTITY: Lazy<Regex> =
            Lazy::new(|| Regex::new(r"(?i)\bIDENTITY\s*\(\s*\d+\s*,\s*\d+\s*\)").unwrap());

        RE_IDENTITY.replace_all(stmt, "AUTO_INCREMENT").to_string()
    }

    /// Convert MSSQL IDENTITY to PostgreSQL SERIAL
    fn convert_identity_to_serial(&self, stmt: &str) -> String {
        use once_cell::sync::Lazy;
        use regex::Regex;

        // Match INT IDENTITY(1,1) and replace with SERIAL
        static RE_BIGINT_IDENTITY: Lazy<Regex> =
            Lazy::new(|| Regex::new(r"(?i)\bBIGINT\s+IDENTITY\s*\(\s*\d+\s*,\s*\d+\s*\)").unwrap());
        static RE_INT_IDENTITY: Lazy<Regex> =
            Lazy::new(|| Regex::new(r"(?i)\bINT\s+IDENTITY\s*\(\s*\d+\s*,\s*\d+\s*\)").unwrap());
        static RE_SMALLINT_IDENTITY: Lazy<Regex> = Lazy::new(|| {
            Regex::new(r"(?i)\bSMALLINT\s+IDENTITY\s*\(\s*\d+\s*,\s*\d+\s*\)").unwrap()
        });

        let result = RE_BIGINT_IDENTITY
            .replace_all(stmt, "BIGSERIAL")
            .to_string();
        let result = RE_INT_IDENTITY.replace_all(&result, "SERIAL").to_string();
        RE_SMALLINT_IDENTITY
            .replace_all(&result, "SMALLSERIAL")
            .to_string()
    }

    /// Strip MSSQL IDENTITY clause for SQLite
    fn strip_identity(&self, stmt: &str) -> String {
        use once_cell::sync::Lazy;
        use regex::Regex;

        static RE_IDENTITY: Lazy<Regex> =
            Lazy::new(|| Regex::new(r"(?i)\s*IDENTITY\s*\(\s*\d+\s*,\s*\d+\s*\)").unwrap());

        RE_IDENTITY.replace_all(stmt, "").to_string()
    }

    /// Convert string escape sequences
    fn convert_string_escapes(&self, stmt: &str) -> String {
        match (self.from, self.to) {
            (SqlDialect::MySql, SqlDialect::Postgres | SqlDialect::Sqlite) => {
                // MySQL uses \' for escaping, PostgreSQL/SQLite use ''
                self.mysql_escapes_to_standard(stmt)
            }
            _ => stmt.to_string(),
        }
    }

    /// Convert MySQL backslash escapes to standard SQL double-quote escapes
    fn mysql_escapes_to_standard(&self, stmt: &str) -> String {
        let mut result = String::with_capacity(stmt.len());
        let mut chars = stmt.chars().peekable();
        let mut in_string = false;

        while let Some(c) = chars.next() {
            if c == '\'' {
                in_string = !in_string;
                result.push(c);
            } else if c == '\\' && in_string {
                // Check next character
                if let Some(&next) = chars.peek() {
                    match next {
                        '\'' => {
                            // \' → ''
                            chars.next();
                            result.push_str("''");
                        }
                        '\\' => {
                            // \\ → keep as-is for data integrity
                            chars.next();
                            result.push_str("\\\\");
                        }
                        'n' | 'r' | 't' | '0' => {
                            // Keep common escapes as-is
                            result.push(c);
                        }
                        _ => {
                            result.push(c);
                        }
                    }
                } else {
                    result.push(c);
                }
            } else {
                result.push(c);
            }
        }
        result
    }

    /// Strip MySQL conditional comments /*!40101 ... */
    fn strip_conditional_comments(&self, stmt: &str) -> String {
        let mut result = String::with_capacity(stmt.len());
        let mut chars = stmt.chars().peekable();

        while let Some(c) = chars.next() {
            if c == '/' && chars.peek() == Some(&'*') {
                chars.next(); // consume *
                if chars.peek() == Some(&'!') {
                    // Skip conditional comment
                    chars.next(); // consume !
                                  // Skip version number
                    while chars.peek().map(|c| c.is_ascii_digit()).unwrap_or(false) {
                        chars.next();
                    }
                    // Skip content until */
                    let mut depth = 1;
                    while depth > 0 {
                        match chars.next() {
                            Some('*') if chars.peek() == Some(&'/') => {
                                chars.next();
                                depth -= 1;
                            }
                            Some('/') if chars.peek() == Some(&'*') => {
                                chars.next();
                                depth += 1;
                            }
                            None => break,
                            _ => {}
                        }
                    }
                } else {
                    // Regular comment, keep it
                    result.push('/');
                    result.push('*');
                }
            } else {
                result.push(c);
            }
        }
        result
    }

    /// Strip ENGINE clause
    fn strip_engine_clause(&self, stmt: &str) -> String {
        use once_cell::sync::Lazy;
        use regex::Regex;

        if self.to == SqlDialect::MySql {
            return stmt.to_string();
        }

        // Remove ENGINE=InnoDB, ENGINE=MyISAM, etc.
        static RE_ENGINE: Lazy<Regex> =
            Lazy::new(|| Regex::new(r"(?i)\s*ENGINE\s*=\s*\w+").unwrap());
        RE_ENGINE.replace_all(stmt, "").to_string()
    }

    /// Strip CHARSET/COLLATE clauses
    fn strip_charset_clauses(&self, stmt: &str) -> String {
        use once_cell::sync::Lazy;
        use regex::Regex;

        if self.to == SqlDialect::MySql {
            return stmt.to_string();
        }

        static RE_CHARSET: Lazy<Regex> =
            Lazy::new(|| Regex::new(r"(?i)\s*(DEFAULT\s+)?CHARSET\s*=\s*\w+").unwrap());
        static RE_COLLATE: Lazy<Regex> =
            Lazy::new(|| Regex::new(r"(?i)\s*COLLATE\s*=?\s*\w+").unwrap());

        let result = RE_CHARSET.replace_all(stmt, "").to_string();
        RE_COLLATE.replace_all(&result, "").to_string()
    }

    /// Strip PostgreSQL type casts (::type and ::regclass)
    fn strip_postgres_casts(&self, stmt: &str) -> String {
        use once_cell::sync::Lazy;
        use regex::Regex;

        // Match ::regclass, ::text, ::integer, etc. (including complex types like character varying)
        static RE_CAST: Lazy<Regex> = Lazy::new(|| {
            Regex::new(r"::[a-zA-Z_][a-zA-Z0-9_]*(?:\s+[a-zA-Z_][a-zA-Z0-9_]*)*").unwrap()
        });

        RE_CAST.replace_all(stmt, "").to_string()
    }

    /// Convert nextval('sequence') to NULL or remove (AUTO_INCREMENT handles it)
    fn convert_nextval(&self, stmt: &str) -> String {
        use once_cell::sync::Lazy;
        use regex::Regex;

        // Match nextval('sequence_name'::regclass) or nextval('sequence_name')
        // Remove the DEFAULT nextval(...) entirely - AUTO_INCREMENT is already applied
        static RE_NEXTVAL: Lazy<Regex> =
            Lazy::new(|| Regex::new(r"(?i)\s*DEFAULT\s+nextval\s*\([^)]+\)").unwrap());

        RE_NEXTVAL.replace_all(stmt, "").to_string()
    }

    /// Convert DEFAULT now() to DEFAULT CURRENT_TIMESTAMP
    fn convert_default_now(&self, stmt: &str) -> String {
        use once_cell::sync::Lazy;
        use regex::Regex;

        static RE_NOW: Lazy<Regex> =
            Lazy::new(|| Regex::new(r"(?i)\bDEFAULT\s+now\s*\(\s*\)").unwrap());

        RE_NOW
            .replace_all(stmt, "DEFAULT CURRENT_TIMESTAMP")
            .to_string()
    }

    /// Strip schema prefix from table names (e.g., public.users -> users)
    fn strip_schema_prefix(&self, stmt: &str) -> String {
        use once_cell::sync::Lazy;
        use regex::Regex;

        // Match schema.table patterns (with optional quotes)
        // Handle: public.table, "public"."table", public."table"
        static RE_SCHEMA: Lazy<Regex> =
            Lazy::new(|| Regex::new(r#"(?i)\b(public|pg_catalog|pg_temp)\s*\.\s*"#).unwrap());

        RE_SCHEMA.replace_all(stmt, "").to_string()
    }

    /// Convert MSSQL GETDATE() to CURRENT_TIMESTAMP
    fn convert_mssql_getdate(&self, stmt: &str) -> String {
        use once_cell::sync::Lazy;
        use regex::Regex;

        static RE_GETDATE: Lazy<Regex> =
            Lazy::new(|| Regex::new(r"(?i)\bGETDATE\s*\(\s*\)").unwrap());
        static RE_SYSDATETIME: Lazy<Regex> =
            Lazy::new(|| Regex::new(r"(?i)\bSYSDATETIME\s*\(\s*\)").unwrap());
        static RE_GETUTCDATE: Lazy<Regex> =
            Lazy::new(|| Regex::new(r"(?i)\bGETUTCDATE\s*\(\s*\)").unwrap());

        let result = RE_GETDATE
            .replace_all(stmt, "CURRENT_TIMESTAMP")
            .to_string();
        let result = RE_SYSDATETIME
            .replace_all(&result, "CURRENT_TIMESTAMP")
            .to_string();
        RE_GETUTCDATE
            .replace_all(&result, "CURRENT_TIMESTAMP")
            .to_string()
    }

    /// Strip MSSQL ON [filegroup] clause
    fn strip_mssql_on_filegroup(&self, stmt: &str) -> String {
        use once_cell::sync::Lazy;
        use regex::Regex;

        // Match ON [PRIMARY] or ON [filegroup_name]
        static RE_ON_FILEGROUP: Lazy<Regex> =
            Lazy::new(|| Regex::new(r"(?i)\s+ON\s*\[\s*\w+\s*\]").unwrap());

        RE_ON_FILEGROUP.replace_all(stmt, "").to_string()
    }

    /// Strip MSSQL CLUSTERED/NONCLUSTERED keywords
    fn strip_mssql_clustered(&self, stmt: &str) -> String {
        use once_cell::sync::Lazy;
        use regex::Regex;

        static RE_CLUSTERED: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bCLUSTERED\s+").unwrap());
        static RE_NONCLUSTERED: Lazy<Regex> =
            Lazy::new(|| Regex::new(r"(?i)\bNONCLUSTERED\s+").unwrap());

        let result = RE_CLUSTERED.replace_all(stmt, "").to_string();
        RE_NONCLUSTERED.replace_all(&result, "").to_string()
    }

    /// Convert MSSQL N'unicode' strings to regular 'unicode' strings
    fn convert_mssql_unicode_strings(&self, stmt: &str) -> String {
        use once_cell::sync::Lazy;
        use regex::Regex;

        // Match N'...' unicode strings, being careful not to match inside strings
        // This is a simplified version that handles most cases
        static RE_UNICODE_STRING: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bN'").unwrap());

        RE_UNICODE_STRING.replace_all(stmt, "'").to_string()
    }

    /// Strip MSSQL schema prefix (dbo., etc.) from table names
    fn strip_mssql_schema_prefix(&self, stmt: &str) -> String {
        use once_cell::sync::Lazy;
        use regex::Regex;

        // Match [dbo].[table] or dbo.table and keep just [table] or table
        // We replace schema.table with just table, handling both bracketed and unbracketed forms
        static RE_MSSQL_SCHEMA: Lazy<Regex> =
            Lazy::new(|| Regex::new(r"(?i)\[?dbo\]?\s*\.\s*").unwrap());

        RE_MSSQL_SCHEMA.replace_all(stmt, "").to_string()
    }

    /// Detect unsupported features and add warnings
    fn detect_unsupported_features(
        &mut self,
        stmt: &str,
        table_name: Option<&str>,
    ) -> Result<(), ConvertWarning> {
        let upper = stmt.to_uppercase();

        // MySQL-specific features
        if self.from == SqlDialect::MySql {
            // ENUM types
            if upper.contains("ENUM(") {
                let warning = ConvertWarning::UnsupportedFeature {
                    feature: format!(
                        "ENUM type{}",
                        table_name
                            .map(|t| format!(" in table {}", t))
                            .unwrap_or_default()
                    ),
                    suggestion: Some(
                        "Converted to VARCHAR - consider adding CHECK constraint".to_string(),
                    ),
                };
                self.warnings.add(warning.clone());
                if self.strict {
                    return Err(warning);
                }
            }

            // SET types (MySQL)
            if upper.contains("SET(") {
                let warning = ConvertWarning::UnsupportedFeature {
                    feature: format!(
                        "SET type{}",
                        table_name
                            .map(|t| format!(" in table {}", t))
                            .unwrap_or_default()
                    ),
                    suggestion: Some(
                        "Converted to VARCHAR - SET semantics not preserved".to_string(),
                    ),
                };
                self.warnings.add(warning.clone());
                if self.strict {
                    return Err(warning);
                }
            }

            // UNSIGNED
            if upper.contains("UNSIGNED") {
                self.warnings.add(ConvertWarning::UnsupportedFeature {
                    feature: "UNSIGNED modifier".to_string(),
                    suggestion: Some(
                        "Removed - consider adding CHECK constraint for non-negative values"
                            .to_string(),
                    ),
                });
            }
        }

        // PostgreSQL-specific features
        if self.from == SqlDialect::Postgres {
            // Array types
            if upper.contains("[]") || upper.contains("ARRAY[") {
                let warning = ConvertWarning::UnsupportedFeature {
                    feature: format!(
                        "Array type{}",
                        table_name
                            .map(|t| format!(" in table {}", t))
                            .unwrap_or_default()
                    ),
                    suggestion: Some(
                        "Array types not supported in target dialect - consider using JSON"
                            .to_string(),
                    ),
                };
                self.warnings.add(warning.clone());
                if self.strict {
                    return Err(warning);
                }
            }

            // INHERITS
            if upper.contains("INHERITS") {
                let warning = ConvertWarning::UnsupportedFeature {
                    feature: "Table inheritance (INHERITS)".to_string(),
                    suggestion: Some(
                        "PostgreSQL table inheritance not supported in target dialect".to_string(),
                    ),
                };
                self.warnings.add(warning.clone());
                if self.strict {
                    return Err(warning);
                }
            }

            // PARTITION BY
            if upper.contains("PARTITION BY") && self.to == SqlDialect::Sqlite {
                let warning = ConvertWarning::UnsupportedFeature {
                    feature: "Table partitioning".to_string(),
                    suggestion: Some("Partitioning not supported in SQLite".to_string()),
                };
                self.warnings.add(warning.clone());
                if self.strict {
                    return Err(warning);
                }
            }
        }

        Ok(())
    }

    /// Get collected warnings
    pub fn warnings(&self) -> &[ConvertWarning] {
        self.warnings.warnings()
    }
}

/// Run the convert command
pub fn run(config: ConvertConfig) -> anyhow::Result<ConvertStats> {
    let mut stats = ConvertStats::default();

    // Detect or use specified source dialect
    let from_dialect = if let Some(d) = config.from_dialect {
        d
    } else {
        let result = crate::parser::detect_dialect_from_file(&config.input)?;
        if config.progress {
            eprintln!(
                "Auto-detected source dialect: {} (confidence: {:?})",
                result.dialect, result.confidence
            );
        }
        result.dialect
    };

    // Check for same dialect
    if from_dialect == config.to_dialect {
        anyhow::bail!(
            "Source and target dialects are the same ({}). No conversion needed.",
            from_dialect
        );
    }

    // Get file size for progress tracking
    let file_size = std::fs::metadata(&config.input)?.len();

    let progress_bar = if config.progress {
        let pb = ProgressBar::new(file_size);
        pb.set_style(
            ProgressStyle::with_template(
                "{spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] {bytes}/{total_bytes} ({percent}%) {msg}",
            )
            .unwrap()
            .progress_chars("█▓▒░  ")
            .tick_chars("⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"),
        );
        pb.enable_steady_tick(std::time::Duration::from_millis(100));
        pb.set_message("Converting...");
        Some(pb)
    } else {
        None
    };

    // Create converter
    let mut converter = Converter::new(from_dialect, config.to_dialect).with_strict(config.strict);

    // Open input file with optional progress tracking
    let file = File::open(&config.input)?;
    let compression = Compression::from_path(&config.input);
    let reader: Box<dyn Read> = if let Some(ref pb) = progress_bar {
        let pb_clone = pb.clone();
        let progress_reader = ProgressReader::new(file, move |bytes| {
            pb_clone.set_position(bytes);
        });
        compression.wrap_reader(Box::new(progress_reader))?
    } else {
        compression.wrap_reader(Box::new(file))?
    };
    let mut parser = Parser::with_dialect(reader, 64 * 1024, from_dialect);

    // Open output
    let mut writer: Box<dyn Write> = if config.dry_run {
        Box::new(std::io::sink())
    } else {
        match &config.output {
            Some(path) => {
                if let Some(parent) = path.parent() {
                    std::fs::create_dir_all(parent)?;
                }
                Box::new(BufWriter::with_capacity(256 * 1024, File::create(path)?))
            }
            None => Box::new(BufWriter::new(std::io::stdout())),
        }
    };

    // Write header
    if !config.dry_run {
        write_header(&mut writer, &config, from_dialect)?;
    }

    // Process statements
    while let Some(stmt) = parser.read_statement()? {
        stats.statements_processed += 1;

        // Check if this is a COPY data block (follows a COPY header)
        if converter.has_pending_copy() {
            // This is a data block, convert it to INSERT statements
            match converter.process_copy_data(&stmt) {
                Ok(inserts) => {
                    for insert in inserts {
                        if !insert.is_empty() {
                            stats.statements_converted += 1;
                            if !config.dry_run {
                                writer.write_all(&insert)?;
                                writer.write_all(b"\n")?;
                            }
                        }
                    }
                }
                Err(warning) => {
                    stats.warnings.push(warning);
                    stats.statements_skipped += 1;
                }
            }
            continue;
        }

        match converter.convert_statement(&stmt) {
            Ok(converted) => {
                if converted.is_empty() {
                    stats.statements_skipped += 1;
                } else if converted == stmt {
                    stats.statements_unchanged += 1;
                    if !config.dry_run {
                        writer.write_all(&converted)?;
                        writer.write_all(b"\n")?;
                    }
                } else {
                    stats.statements_converted += 1;
                    if !config.dry_run {
                        writer.write_all(&converted)?;
                        writer.write_all(b"\n")?;
                    }
                }
            }
            Err(warning) => {
                stats.warnings.push(warning);
                stats.statements_skipped += 1;
            }
        }
    }

    // Collect warnings
    stats.warnings.extend(converter.warnings().iter().cloned());

    if let Some(pb) = progress_bar {
        pb.finish_with_message("done");
    }

    Ok(stats)
}

/// Write output header
fn write_header(
    writer: &mut dyn Write,
    config: &ConvertConfig,
    from: SqlDialect,
) -> std::io::Result<()> {
    writeln!(writer, "-- Converted by sql-splitter")?;
    writeln!(writer, "-- From: {} → To: {}", from, config.to_dialect)?;
    writeln!(writer, "-- Source: {}", config.input.display())?;
    writeln!(writer)?;

    // Write dialect-specific header
    match config.to_dialect {
        SqlDialect::Postgres => {
            writeln!(writer, "SET client_encoding = 'UTF8';")?;
            writeln!(writer, "SET standard_conforming_strings = on;")?;
        }
        SqlDialect::Sqlite => {
            writeln!(writer, "PRAGMA foreign_keys = OFF;")?;
        }
        SqlDialect::MySql => {
            writeln!(writer, "SET NAMES utf8mb4;")?;
            writeln!(writer, "SET FOREIGN_KEY_CHECKS = 0;")?;
        }
        SqlDialect::Mssql => {
            writeln!(writer, "SET ANSI_NULLS ON;")?;
            writeln!(writer, "SET QUOTED_IDENTIFIER ON;")?;
            writeln!(writer, "SET NOCOUNT ON;")?;
        }
    }
    writeln!(writer)?;

    Ok(())
}