sql-splitter 1.20.0

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
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
pub mod mysql_insert;
pub mod postgres_copy;

// Re-export types for bulk loading (consumed by the duckdb loader and by
// library users; the bin target without duckdb-query doesn't use them)
#[cfg_attr(not(feature = "duckdb-query"), allow(unused_imports))]
pub use mysql_insert::{parse_insert_for_bulk, ParsedValue};

use once_cell::sync::Lazy;
use regex::bytes::Regex;
use std::io::{BufRead, BufReader, Read};

pub const SMALL_BUFFER_SIZE: usize = 64 * 1024;
pub const MEDIUM_BUFFER_SIZE: usize = 256 * 1024;

/// SQL dialect for parser behavior
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum SqlDialect {
    /// MySQL/MariaDB mysqldump format (backtick quoting, backslash escapes)
    #[default]
    MySql,
    /// PostgreSQL pg_dump format (double-quote identifiers, COPY FROM stdin, dollar-quoting)
    Postgres,
    /// SQLite .dump format (double-quote identifiers, '' escapes)
    Sqlite,
    /// Microsoft SQL Server / T-SQL (square bracket identifiers, GO batches, N'unicode' strings)
    Mssql,
}

impl std::str::FromStr for SqlDialect {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "mysql" | "mariadb" => Ok(SqlDialect::MySql),
            "postgres" | "postgresql" | "pg" => Ok(SqlDialect::Postgres),
            "sqlite" | "sqlite3" => Ok(SqlDialect::Sqlite),
            "mssql" | "sqlserver" | "sql_server" | "tsql" => Ok(SqlDialect::Mssql),
            _ => Err(format!(
                "Unknown dialect: {}. Valid options: mysql, postgres, sqlite, mssql",
                s
            )),
        }
    }
}

impl std::fmt::Display for SqlDialect {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SqlDialect::MySql => write!(f, "mysql"),
            SqlDialect::Postgres => write!(f, "postgres"),
            SqlDialect::Sqlite => write!(f, "sqlite"),
            SqlDialect::Mssql => write!(f, "mssql"),
        }
    }
}

/// Result of dialect auto-detection
#[derive(Debug, Clone)]
pub struct DialectDetectionResult {
    pub dialect: SqlDialect,
    pub confidence: DialectConfidence,
}

/// Confidence level of dialect detection
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DialectConfidence {
    /// High confidence - found definitive markers (e.g., "pg_dump", "MySQL dump")
    High,
    /// Medium confidence - found likely markers
    Medium,
    /// Low confidence - defaulting to MySQL
    Low,
}

#[derive(Default)]
struct DialectScore {
    mysql: u32,
    postgres: u32,
    sqlite: u32,
    mssql: u32,
}

/// Detect SQL dialect from file header content.
/// Reads up to 8KB and looks for dialect-specific markers.
pub fn detect_dialect(header: &[u8]) -> DialectDetectionResult {
    let mut score = DialectScore::default();

    // Simple "substring present => add weight to a dialect" markers. Confidence
    // is encoded by the weight: 20/10 = high, 5 = medium, 2 = low.
    const MARKERS: &[(&[u8], SqlDialect, u32)] = &[
        (b"pg_dump", SqlDialect::Postgres, 10),
        (b"PostgreSQL database dump", SqlDialect::Postgres, 10),
        (b"MySQL dump", SqlDialect::MySql, 10),
        (b"MariaDB dump", SqlDialect::MySql, 10),
        (b"SQLite", SqlDialect::Sqlite, 10),
        (b"search_path", SqlDialect::Postgres, 5),
        (b"LOCK TABLES", SqlDialect::MySql, 5),
        (b"PRAGMA", SqlDialect::Sqlite, 5),
        (b"CREATE EXTENSION", SqlDialect::Postgres, 2),
        // BEGIN TRANSACTION is generic ANSI SQL, only slightly suggests SQLite
        (b"BEGIN TRANSACTION", SqlDialect::Sqlite, 2),
        (b"SET ANSI_NULLS", SqlDialect::Mssql, 20),
        (b"SET QUOTED_IDENTIFIER", SqlDialect::Mssql, 20),
        (b"IDENTITY(", SqlDialect::Mssql, 10),
        (b"ON [PRIMARY]", SqlDialect::Mssql, 10),
        (b"NVARCHAR", SqlDialect::Mssql, 5),
        (b"CLUSTERED", SqlDialect::Mssql, 5),
        (b"SET NOCOUNT", SqlDialect::Mssql, 5),
    ];
    for &(needle, dialect, weight) in MARKERS {
        if contains_bytes(header, needle) {
            match dialect {
                SqlDialect::MySql => score.mysql += weight,
                SqlDialect::Postgres => score.postgres += weight,
                SqlDialect::Sqlite => score.sqlite += weight,
                SqlDialect::Mssql => score.mssql += weight,
            }
        }
    }

    // Compound / structural markers that don't fit the simple table.
    if contains_bytes(header, b"COPY ") && contains_bytes(header, b"FROM stdin") {
        score.postgres += 5;
    }
    if contains_bytes(header, b"/*!40") || contains_bytes(header, b"/*!50") {
        score.mysql += 5;
    }
    if contains_bytes(header, b"$$") {
        score.postgres += 2;
    }
    // Backticks suggest MySQL (could also appear in data/comments)
    if header.contains(&b'`') {
        score.mysql += 2;
    }
    // GO as batch separator on its own line (check for common patterns)
    if contains_bytes(header, b"\nGO\n") || contains_bytes(header, b"\nGO\r\n") {
        score.mssql += 15;
    }
    // Square-bracket identifiers, but distinguish them from PostgreSQL array
    // types: `[id]`/`[dbo]` (identifier-shaped) => MSSQL; `integer[]` (empty)
    // or `[5]` (non-identifier) => not MSSQL (bug #9).
    {
        let mut mssql_bracket_ident = false;
        let mut pg_array_brackets = false;
        let mut k = 0;
        while k < header.len() {
            if header[k] == b'[' {
                if let Some(rel) = header[k + 1..].iter().position(|&c| c == b']') {
                    let inner = &header[k + 1..k + 1 + rel];
                    let ident_shaped = inner
                        .first()
                        .is_some_and(|&c| c.is_ascii_alphabetic() || c == b'_')
                        && inner
                            .iter()
                            .all(|&c| c.is_ascii_alphanumeric() || c == b'_' || c == b' ');
                    if inner.is_empty() {
                        pg_array_brackets = true;
                    } else if ident_shaped {
                        mssql_bracket_ident = true;
                    }
                    k += rel + 2;
                    continue;
                }
            }
            k += 1;
        }
        if mssql_bracket_ident {
            score.mssql += 10;
        }
        if pg_array_brackets {
            score.postgres += 2;
        }
    }

    // N'unicode' literal — require a non-word char before N so ordinary data
    // ending in N before a quote (e.g. ...JOHN') doesn't score MSSQL (bug #9).
    {
        let mut k = 0;
        while k + 1 < header.len() {
            if header[k] == b'N' && header[k + 1] == b'\'' {
                let before_ok =
                    k == 0 || !(header[k - 1].is_ascii_alphanumeric() || header[k - 1] == b'_');
                if before_ok {
                    score.mssql += 5;
                    break;
                }
            }
            k += 1;
        }
    }

    // Determine winner and confidence
    let max_score = score
        .mysql
        .max(score.postgres)
        .max(score.sqlite)
        .max(score.mssql);

    if max_score == 0 {
        return DialectDetectionResult {
            dialect: SqlDialect::MySql,
            confidence: DialectConfidence::Low,
        };
    }

    // Find the dialect with the highest score
    let (dialect, winning_score) = if score.mssql > score.mysql
        && score.mssql > score.postgres
        && score.mssql > score.sqlite
    {
        (SqlDialect::Mssql, score.mssql)
    } else if score.postgres > score.mysql && score.postgres > score.sqlite {
        (SqlDialect::Postgres, score.postgres)
    } else if score.sqlite > score.mysql {
        (SqlDialect::Sqlite, score.sqlite)
    } else {
        (SqlDialect::MySql, score.mysql)
    };

    // Determine confidence based on winning score
    let confidence = if winning_score >= 10 {
        DialectConfidence::High
    } else if winning_score >= 5 {
        DialectConfidence::Medium
    } else {
        DialectConfidence::Low
    };

    DialectDetectionResult {
        dialect,
        confidence,
    }
}

/// Detect dialect from a file, reading its first 8KB. Goes through
/// [`crate::splitter::open_input`] so compressed and zipped inputs are
/// transparently decoded before sniffing — without that, detection would
/// see raw compressed bytes instead of SQL text.
pub fn detect_dialect_from_file(path: &std::path::Path) -> anyhow::Result<DialectDetectionResult> {
    use std::io::Read;

    let mut reader = crate::splitter::open_input(path)?;
    let mut buf = [0u8; 8192];
    let n = reader.read(&mut buf)?;
    Ok(detect_dialect(&buf[..n]))
}

#[inline]
fn contains_bytes(haystack: &[u8], needle: &[u8]) -> bool {
    memchr::memmem::find(haystack, needle).is_some()
}

/// Check if a line is a MSSQL GO batch separator
/// GO must be on its own line (with optional whitespace and optional repeat count)
/// Examples: "GO\n", "  GO  \n", "GO 100\n", "go\r\n"
fn is_go_line(line: &[u8]) -> bool {
    // Trim leading whitespace
    let mut start = 0;
    while start < line.len()
        && (line[start] == b' ' || line[start] == b'\t' || line[start] == b'\r')
    {
        start += 1;
    }

    // Trim trailing whitespace and newlines
    let mut end = line.len();
    while end > start
        && (line[end - 1] == b' '
            || line[end - 1] == b'\t'
            || line[end - 1] == b'\r'
            || line[end - 1] == b'\n')
    {
        end -= 1;
    }

    let trimmed = &line[start..end];

    if trimmed.len() < 2 {
        return false;
    }

    // Check for "GO" (case-insensitive)
    if trimmed.len() == 2 {
        return (trimmed[0] == b'G' || trimmed[0] == b'g')
            && (trimmed[1] == b'O' || trimmed[1] == b'o');
    }

    // Check for "GO <number>" pattern
    if (trimmed[0] == b'G' || trimmed[0] == b'g')
        && (trimmed[1] == b'O' || trimmed[1] == b'o')
        && (trimmed[2] == b' ' || trimmed[2] == b'\t')
    {
        // Rest should be whitespace and digits (allocation-free scan)
        return trimmed[3..]
            .iter()
            .skip_while(|&&b| b == b' ' || b == b'\t')
            .all(|&b| b.is_ascii_digit());
    }

    false
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StatementType {
    Unknown,
    CreateTable,
    Insert,
    CreateIndex,
    AlterTable,
    DropTable,
    /// PostgreSQL COPY FROM stdin
    Copy,
}

impl StatementType {
    /// Returns true if this is a schema-related statement (DDL)
    pub fn is_schema(&self) -> bool {
        matches!(
            self,
            StatementType::CreateTable
                | StatementType::CreateIndex
                | StatementType::AlterTable
                | StatementType::DropTable
        )
    }

    /// Returns true if this is a data-related statement (DML)
    pub fn is_data(&self) -> bool {
        matches!(self, StatementType::Insert | StatementType::Copy)
    }
}

/// Content filter mode for splitting
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ContentFilter {
    /// Include both schema and data statements (default)
    #[default]
    All,
    /// Only schema statements (CREATE TABLE, CREATE INDEX, ALTER TABLE, DROP TABLE)
    SchemaOnly,
    /// Only data statements (INSERT, COPY)
    DataOnly,
}

// Word boundary before ON so index names ending in "on" (idx_position,
// idx_created_on, ...) don't match the "on" inside the identifier.
static CREATE_INDEX_RE: Lazy<Regex> =
    Lazy::new(|| Regex::new(r"(?i)\bON\s+`?([^\s`(;]+)`?").unwrap());

// MSSQL CREATE INDEX: extracts table from ON [schema].[table] or ON [table]
// Matches: ON [table], ON [dbo].[table], ON [db].[dbo].[table]
// Captures the complete table reference before `(`.
static CREATE_INDEX_MSSQL_RE: Lazy<Regex> = Lazy::new(|| {
    Regex::new(
        r"(?i)ON\s+((?:(?:\[(?:[^\]]|\]\])*\]|[^\s.()]+)\s*\.\s*)*(?:\[(?:[^\]]|\]\])*\]|[^\s.()]+))",
    )
    .unwrap()
});

static ALTER_TABLE_RE: Lazy<Regex> =
    Lazy::new(|| Regex::new(r"(?i)ALTER\s+TABLE\s+`?([^\s`;]+)`?").unwrap());

static DROP_TABLE_RE: Lazy<Regex> = Lazy::new(|| {
    Regex::new(r#"(?i)DROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?[`"]?([^\s`"`;]+)[`"]?"#).unwrap()
});

// More flexible table name regex that handles:
// - Backticks: `table`
// - Double quotes: "table"
// - Schema qualified: schema.table, `schema`.`table`, "schema"."table"
// - IF NOT EXISTS
static CREATE_TABLE_FLEXIBLE_RE: Lazy<Regex> = Lazy::new(|| {
    Regex::new(r#"(?i)^\s*CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(?:[`"]?[\w]+[`"]?\s*\.\s*)?[`"]?([\w]+)[`"]?"#).unwrap()
});

static INSERT_FLEXIBLE_RE: Lazy<Regex> = Lazy::new(|| {
    Regex::new(
        r#"(?i)^\s*INSERT\s+INTO\s+(?:ONLY\s+)?(?:[`"]?[\w]+[`"]?\s*\.\s*)?[`"]?([\w]+)[`"]?"#,
    )
    .unwrap()
});

/// Result of peeking at the byte after position `i` for a two-byte token
/// (`--`, `/*`, `*/`, `]]`). See [`Parser::peek2`].
#[derive(Clone, Copy, PartialEq, Eq)]
enum Peek2 {
    /// The next byte is present and matches: the token is complete.
    Hit,
    /// The next byte differs, or input ended at EOF (a dangling first byte at
    /// the tail is treated as a literal byte).
    Miss,
    /// The buffer ends here but more input may arrive: the caller must pause
    /// the scan (`break 'scan`) with its state intact so the token can never
    /// straddle a refill (see the `buf` field docs).
    NeedMore,
}

/// Result of probing for a MySQL `DELIMITER` client command at a statement
/// boundary. See [`Parser::scan_delimiter_command`].
enum DelimiterScan {
    /// The bytes at the boundary are not a `DELIMITER` command.
    NotDelimiter,
    /// A complete `DELIMITER <token>` line: switch the terminator to
    /// `new_delim` and resume scanning the real statement at `next`.
    Consumed { new_delim: Vec<u8>, next: usize },
    /// The line is not fully buffered yet: grow the buffer and retry.
    NeedMore,
}

/// Control-flow signal returned by row/event visitors.
///
/// Lives in the parser layer (rather than a consumer module) so the streaming
/// row visitors ([`crate::parser::mysql_insert::visit_insert_rows_with`],
/// [`crate::parser::postgres_copy::visit_postgres_copy_rows_with`]) and
/// [`Parser::visit_events`] can all speak the same vocabulary. Re-exported from
/// `crate::transform_common` for the sample/shard consumers.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RowFlow {
    /// Keep iterating.
    Continue,
    /// Skip the remaining rows of the current INSERT/COPY statement, then
    /// resume with the next statement.
    SkipStatement,
    /// Stop the walk entirely.
    Stop,
}

/// A single streaming event emitted by [`Parser::visit_events`].
///
/// Data rows are treated as stream boundaries: a multi-row INSERT is delivered
/// as its shared header plus one [`ParserEvent::InsertRow`] per tuple, and a
/// COPY block as [`ParserEvent::CopyStart`] / one [`ParserEvent::CopyRow`] per
/// line / [`ParserEvent::CopyEnd`] — never buffering the whole block. All byte
/// slices borrow from the parser's internal buffer (or, for `InsertRow.header`,
/// a small owned copy of the header) and are only valid until the callback
/// returns.
pub enum ParserEvent<'a> {
    /// A complete non-data statement (DDL / control), including its terminator.
    Statement(&'a [u8]),
    /// One INSERT `(...)` value tuple. `header` is the statement text up to and
    /// including the `VALUES` keyword (so the column list can be recovered);
    /// `first_in_statement` is true for the first row of each INSERT so callers
    /// can rebuild per-statement column context exactly once.
    InsertRow {
        header: &'a [u8],
        row: &'a [u8],
        first_in_statement: bool,
    },
    /// The `COPY ... FROM stdin;` header line that opens a COPY data block.
    CopyStart(&'a [u8]),
    /// One raw COPY data line (newline stripped; a trailing `\r`, if any, is
    /// left for the consumer to strip so it matches the collecting parser).
    CopyRow(&'a [u8]),
    /// The `\.` terminator that closes a COPY data block.
    CopyEnd,
}

/// Configurable safety caps on how much a single buffered unit may grow before
/// [`Parser::visit_events`] reports an error (rather than silently truncating
/// or buffering without bound). Defaults are generous; they exist to turn a
/// pathological/corrupt input into a diagnosable error instead of an OOM.
#[derive(Debug, Clone, Copy)]
pub struct ParserLimits {
    /// Max bytes for one non-data statement (DDL/control).
    pub max_ddl: usize,
    /// Max bytes for an INSERT/COPY header before the first row.
    pub max_header: usize,
    /// Max bytes for a single INSERT tuple or COPY line.
    pub max_row: usize,
}

impl Default for ParserLimits {
    fn default() -> Self {
        Self {
            max_ddl: 256 * 1024 * 1024,
            max_header: 64 * 1024 * 1024,
            max_row: 256 * 1024 * 1024,
        }
    }
}

/// Longest statement terminator a `DELIMITER` command may set, stored inline.
/// Real delimiters are 1–2 bytes (`;`, `;;`, `//`, `$$`); a longer one is
/// truncated to this cap, which no realistic dump reaches.
const MAX_DELIMITER_LEN: usize = 8;

pub struct Parser<R: Read> {
    reader: BufReader<R>,
    dialect: SqlDialect,
    /// For PostgreSQL: true when reading COPY data block
    in_copy_data: bool,
    /// Accumulated, not-yet-returned input. The scanners read whole `fill_buf`
    /// chunks into `buf` and scan it with an index cursor, so a multi-byte
    /// token (`--`, `/* */`, `$tag$`, `]]`) can never straddle an internal
    /// buffer boundary. `buf_pos` is the start of the next statement to return;
    /// bytes before it are already-returned and are dropped on the next refill
    /// (never per-statement) so scanning stays O(n) rather than O(n²).
    buf: Vec<u8>,
    buf_pos: usize,
    /// Current statement terminator, stored inline so constructing a `Parser`
    /// never heap-allocates for the common `;` case. Defaults to `;`, but a
    /// MySQL `DELIMITER` client command (as emitted by `mysqldump --routines`
    /// around stored procedure/function/trigger bodies) switches it to e.g.
    /// `;;` so the `;`-terminated statements inside a `BEGIN … END` body are not
    /// split apart. Persists across `read_statement` calls for the same stream.
    /// The active delimiter is `current_delimiter[..current_delimiter_len]`.
    current_delimiter: [u8; MAX_DELIMITER_LEN],
    current_delimiter_len: usize,
    /// Number of bytes dropped off the front of `buf` so far, so an absolute
    /// input offset can be reported in [`Parser::visit_events`] diagnostics.
    base: u64,
    /// High-water mark of `buf.len()`, so tests can assert the streaming walker
    /// keeps its working set bounded.
    peak_buffered: usize,
    /// Safety caps for [`Parser::visit_events`].
    limits: ParserLimits,
}

impl<R: Read> Parser<R> {
    #[allow(dead_code)]
    pub fn new(reader: R, buffer_size: usize) -> Self {
        Self::with_dialect(reader, buffer_size, SqlDialect::default())
    }

    pub fn with_dialect(reader: R, buffer_size: usize, dialect: SqlDialect) -> Self {
        Self {
            reader: BufReader::with_capacity(buffer_size, reader),
            dialect,
            in_copy_data: false,
            buf: Vec::new(),
            buf_pos: 0,
            current_delimiter: {
                let mut d = [0u8; MAX_DELIMITER_LEN];
                d[0] = b';';
                d
            },
            current_delimiter_len: 1,
            base: 0,
            peak_buffered: 0,
            limits: ParserLimits::default(),
        }
    }

    /// Override the [`ParserLimits`] used by [`Parser::visit_events`].
    #[allow(dead_code)]
    pub fn with_limits(mut self, limits: ParserLimits) -> Self {
        self.limits = limits;
        self
    }

    /// Total bytes currently buffered in memory. Used by tests to assert the
    /// event walker keeps its working set bounded even for huge INSERT/COPY
    /// blocks.
    pub fn buffered_len(&self) -> usize {
        self.buf.len()
    }

    /// High-water mark of buffered bytes over this parser's lifetime. Used by
    /// tests to assert [`Parser::visit_events`] never buffers a whole multi-row
    /// INSERT/COPY block.
    pub fn peak_buffered(&self) -> usize {
        self.peak_buffered
    }

    /// True when the statement just returned by [`read_statement`](Self::read_statement)
    /// was a `COPY ... FROM stdin;` header, meaning the *next* call returns that
    /// block's data rather than a statement. Lets a caller pair a header with its
    /// data block off the parser's own state instead of re-deriving the rule and
    /// risking a desync on edge cases like `FROM STDIN WITH (FORMAT csv)`.
    pub fn in_copy_data(&self) -> bool {
        self.in_copy_data
    }

    /// Drop the already-returned prefix `buf[..keep_from]` and append the next
    /// `fill_buf` chunk. Returns `(bytes_removed_from_front, got_more_data)`.
    /// Callers subtract `bytes_removed_from_front` from their scan indices.
    #[inline]
    fn grow_buffer(&mut self, keep_from: usize) -> std::io::Result<(usize, bool)> {
        if keep_from > 0 {
            self.buf.drain(..keep_from);
            self.base += keep_from as u64;
        }
        let chunk = self.reader.fill_buf()?;
        if chunk.is_empty() {
            return Ok((keep_from, false));
        }
        self.buf.extend_from_slice(chunk);
        let n = chunk.len();
        self.reader.consume(n);
        self.peak_buffered = self.peak_buffered.max(self.buf.len());
        Ok((keep_from, true))
    }

    /// Classify the byte after `i` against the second byte of a two-byte
    /// token. Centralizes the boundary handling shared by every such token in
    /// [`read_statement`](Self::read_statement) and `read_statement_mssql`.
    #[inline(always)]
    fn peek2(&self, i: usize, expected: u8, at_eof: bool) -> Peek2 {
        match self.buf.get(i + 1) {
            Some(&c) if c == expected => Peek2::Hit,
            Some(_) => Peek2::Miss,
            None if at_eof => Peek2::Miss,
            None => Peek2::NeedMore,
        }
    }

    /// Cheap guard for the `DELIMITER` pre-scan: `true` when the next statement
    /// could begin a `DELIMITER` command, i.e. the first non-whitespace byte at
    /// `buf_pos` is `D`/`d`, or the buffer ran out before a non-whitespace byte
    /// was found (so the full scan must grow it to decide). `false` — the common
    /// case — lets `read_statement` skip the pre-scan loop entirely.
    #[inline]
    fn upcoming_maybe_delimiter(&self) -> bool {
        let mut p = self.buf_pos;
        while p < self.buf.len() {
            match self.buf[p] {
                b' ' | b'\t' | b'\r' | b'\n' => p += 1,
                b'D' | b'd' => return true,
                _ => return false,
            }
        }
        // Ran out of buffered bytes without deciding: let the full scan grow it.
        true
    }

    /// Detect a MySQL `DELIMITER <token>` client command starting at `from`
    /// (after leading whitespace). The command is line-terminated (not
    /// terminated by the current delimiter) and is a mysql-client directive
    /// with no SQL meaning, so it is consumed and not emitted as a statement.
    fn scan_delimiter_command(&self, from: usize, at_eof: bool) -> DelimiterScan {
        const KW: &[u8] = b"DELIMITER";

        let mut p = from;
        while p < self.buf.len() && matches!(self.buf[p], b' ' | b'\t' | b'\r' | b'\n') {
            p += 1;
        }
        if self.buf.len() - p < KW.len() {
            return if at_eof {
                DelimiterScan::NotDelimiter
            } else {
                DelimiterScan::NeedMore
            };
        }
        for (k, &kw) in KW.iter().enumerate() {
            if self.buf[p + k].to_ascii_uppercase() != kw {
                return DelimiterScan::NotDelimiter;
            }
        }
        let mut q = p + KW.len();
        // The keyword must be followed by horizontal whitespace, else it is an
        // identifier that merely starts with "DELIMITER" (e.g. `DELIMITERS`).
        match self.buf.get(q) {
            Some(&c) if c == b' ' || c == b'\t' => {}
            Some(_) => return DelimiterScan::NotDelimiter,
            None if at_eof => return DelimiterScan::NotDelimiter,
            None => return DelimiterScan::NeedMore,
        }
        while q < self.buf.len() && matches!(self.buf[q], b' ' | b'\t') {
            q += 1;
        }
        let line_end = match memchr::memchr(b'\n', &self.buf[q..]) {
            Some(off) => q + off,
            None if at_eof => self.buf.len(),
            None => return DelimiterScan::NeedMore,
        };
        // Trim trailing horizontal whitespace / CR from the delimiter token.
        let mut end = line_end;
        while end > q && matches!(self.buf[end - 1], b' ' | b'\t' | b'\r') {
            end -= 1;
        }
        if end == q {
            // `DELIMITER` with no argument: malformed. Leave it to normal
            // parsing rather than swallowing the line.
            return DelimiterScan::NotDelimiter;
        }
        let new_delim = self.buf[q..end].to_vec();
        let next = if line_end < self.buf.len() {
            line_end + 1
        } else {
            line_end
        };
        DelimiterScan::Consumed { new_delim, next }
    }

    pub fn read_statement(&mut self) -> std::io::Result<Option<Vec<u8>>> {
        // If we're in PostgreSQL COPY data mode, read until we see the terminator
        if self.in_copy_data {
            return self.read_copy_data();
        }

        // For MSSQL, use line-based parsing to handle GO batch separator
        if self.dialect == SqlDialect::Mssql {
            return self.read_statement_mssql();
        }

        let is_mysql = self.dialect == SqlDialect::MySql;
        let is_postgres = self.dialect == SqlDialect::Postgres;

        // Scan `self.buf` from the current statement start with an index cursor.
        // More data is appended by `grow_buffer` (which also drops already-
        // returned statements), so a multi-byte token (`--`, `/* */`, `$tag$`)
        // never straddles a chunk boundary: the scan waits for more bytes with
        // its state (`i`, quote/comment flags) intact.
        let mut start = self.buf_pos;
        let mut i = self.buf_pos;

        let mut inside_single_quote = false;
        // The current single-quoted string is a PostgreSQL escape string
        // (`E'…'`), inside which backslash is an escape character — so a
        // backslash-escaped quote (`E'a\'b'`) does not end the string.
        let mut in_escape_string = false;
        let mut inside_double_quote = false;
        let mut inside_backtick = false; // MySQL `identifier` quoting (bug #10)
        let mut escaped = false;
        let mut in_line_comment = false;
        let mut in_block_comment = false; // /* ... */ (bug #5)
        let mut in_dollar_quote = false;
        let mut dollar_tag: Vec<u8> = Vec::new();
        let mut at_eof = false;

        // Consume any leading MySQL `DELIMITER` client commands before scanning
        // the next real statement, so `;`-terminated statements inside a stored
        // routine body are kept whole under a `;;` (or other) delimiter.
        //
        // Fast path: a `DELIMITER` command begins with `D`/`d` after optional
        // leading whitespace. When that first byte is already buffered and is
        // not `D`/`d`, there is no command here, so skip the full scan entirely
        // — this keeps the per-statement cost off the parser's hot loop for the
        // overwhelmingly common non-`DELIMITER` statement.
        if is_mysql && self.upcoming_maybe_delimiter() {
            loop {
                match self.scan_delimiter_command(self.buf_pos, at_eof) {
                    DelimiterScan::NotDelimiter => break,
                    DelimiterScan::Consumed { new_delim, next } => {
                        let n = new_delim.len().min(MAX_DELIMITER_LEN);
                        self.current_delimiter[..n].copy_from_slice(&new_delim[..n]);
                        self.current_delimiter_len = n;
                        self.buf_pos = next;
                        start = self.buf_pos;
                        i = self.buf_pos;
                    }
                    DelimiterScan::NeedMore => {
                        let (removed, more) = self.grow_buffer(self.buf_pos)?;
                        self.buf_pos -= removed;
                        start = self.buf_pos;
                        i = self.buf_pos;
                        if !more {
                            at_eof = true;
                        }
                    }
                }
            }
        }

        // Lookup table of bytes that are significant outside strings/comments;
        // everything else can be skipped in a tight loop.
        let mut sig = [false; 256];
        for &c in b";'\"-/" {
            sig[c as usize] = true;
        }
        if is_mysql {
            sig[b'`' as usize] = true;
            sig[b'#' as usize] = true;
        }
        if is_postgres {
            sig[b'$' as usize] = true;
        }
        // A custom multi-byte delimiter (from `DELIMITER`) may start with a byte
        // the default table does not flag; make sure the scan stops on it. The
        // delimiter can't change during this scan (only the pre-scan above sets
        // it), so cache it in locals to keep the hot loop off the struct fields.
        let delim0 = self.current_delimiter[0];
        let delim_len = self.current_delimiter_len;
        sig[delim0 as usize] = true;

        loop {
            'scan: while i < self.buf.len() {
                let b = self.buf[i];

                // Inside a /* */ block comment: only the closing */ ends it.
                if in_block_comment {
                    if b == b'*' {
                        match self.peek2(i, b'/', at_eof) {
                            Peek2::Hit => {
                                in_block_comment = false;
                                i += 2;
                                continue;
                            }
                            Peek2::Miss => {
                                i += 1;
                                continue;
                            }
                            Peek2::NeedMore => break 'scan,
                        }
                    }
                    i += 1;
                    continue;
                }

                // Inside a -- or # line comment: consume until newline.
                if in_line_comment {
                    if b == b'\n' {
                        in_line_comment = false;
                    }
                    i += 1;
                    continue;
                }

                if escaped {
                    escaped = false;
                    i += 1;
                    continue;
                }

                let inside_string = inside_single_quote
                    || inside_double_quote
                    || inside_backtick
                    || in_dollar_quote;

                // Fast path: inside a string/quoted region only the closing
                // delimiter (and, for MySQL, a `\` escape) is significant, so
                // memchr past the ordinary bytes. This is the hot loop for
                // INSERT string data.
                if inside_string {
                    let rest = &self.buf[i..];
                    let hit = if inside_single_quote {
                        if is_mysql || (is_postgres && in_escape_string) {
                            memchr::memchr2(b'\'', b'\\', rest)
                        } else {
                            memchr::memchr(b'\'', rest)
                        }
                    } else if inside_double_quote {
                        if is_mysql {
                            memchr::memchr2(b'"', b'\\', rest)
                        } else {
                            memchr::memchr(b'"', rest)
                        }
                    } else if inside_backtick {
                        memchr::memchr(b'`', rest)
                    } else {
                        // in_dollar_quote: only `$` can start the closing tag
                        memchr::memchr(b'$', rest)
                    };
                    match hit {
                        Some(0) => {} // significant byte at i
                        Some(off) => {
                            i += off;
                            continue;
                        }
                        None if at_eof => {
                            i = self.buf.len();
                            continue;
                        }
                        None => break 'scan,
                    }
                }

                // Backslash escapes apply inside MySQL '…'/"…" literals and
                // inside a PostgreSQL E'…' escape string (but never inside
                // backtick identifiers or dollar quotes).
                if b == b'\\'
                    && ((is_mysql && (inside_single_quote || inside_double_quote))
                        || (is_postgres && inside_single_quote && in_escape_string))
                {
                    escaped = true;
                    i += 1;
                    continue;
                }

                if !inside_string {
                    // Fast path: skip runs of insignificant bytes outside any
                    // string/comment with a tight table lookup.
                    if !sig[b as usize] {
                        let mut j = i + 1;
                        while j < self.buf.len() && !sig[self.buf[j] as usize] {
                            j += 1;
                        }
                        i = j;
                        continue;
                    }
                    // -- line comment
                    if b == b'-' {
                        match self.peek2(i, b'-', at_eof) {
                            Peek2::Hit => {
                                // MySQL requires whitespace/EOL after `--` for it
                                // to be a comment; `a--b` is arithmetic. Other
                                // dialects always treat `--` as a comment.
                                if is_mysql {
                                    match self.buf.get(i + 2) {
                                        Some(&c)
                                            if c == b' '
                                                || c == b'\t'
                                                || c == b'\n'
                                                || c == b'\r' =>
                                        {
                                            in_line_comment = true;
                                            i += 2;
                                            continue;
                                        }
                                        None if at_eof => {
                                            in_line_comment = true;
                                            i += 2;
                                            continue;
                                        }
                                        None => break 'scan,
                                        // `--x`: not a comment, just consume one `-`.
                                        Some(_) => {
                                            i += 1;
                                            continue;
                                        }
                                    }
                                }
                                in_line_comment = true;
                                i += 2;
                                continue;
                            }
                            Peek2::Miss => {
                                i += 1;
                                continue;
                            }
                            Peek2::NeedMore => break 'scan,
                        }
                    }
                    // MySQL # line comment
                    if b == b'#' && is_mysql {
                        in_line_comment = true;
                        i += 1;
                        continue;
                    }
                    // /* block comment
                    if b == b'/' {
                        match self.peek2(i, b'*', at_eof) {
                            Peek2::Hit => {
                                in_block_comment = true;
                                i += 2;
                                continue;
                            }
                            Peek2::Miss => {
                                i += 1;
                                continue;
                            }
                            Peek2::NeedMore => break 'scan,
                        }
                    }
                }

                // PostgreSQL dollar-quoting (outside other quotes).
                if is_postgres && !inside_single_quote && !inside_double_quote && !inside_backtick {
                    if b == b'$' && !in_dollar_quote {
                        match self.buf[i + 1..].iter().position(|&c| c == b'$') {
                            Some(end) => {
                                let tag_bytes = &self.buf[i + 1..i + 1 + end];
                                if is_valid_dollar_tag(tag_bytes) {
                                    dollar_tag = tag_bytes.to_vec();
                                    in_dollar_quote = true;
                                    // Skip the whole opening $tag$ so its trailing
                                    // $ is not re-read as a closer (bug #7).
                                    i += end + 2;
                                    continue;
                                }
                                // Not a valid tag: treat $ as an ordinary byte.
                                i += 1;
                                continue;
                            }
                            None if at_eof => {
                                i += 1;
                                continue;
                            }
                            // No closing $ yet — it may arrive in the next chunk.
                            None => break 'scan,
                        }
                    } else if b == b'$' && in_dollar_quote {
                        let tag_len = dollar_tag.len();
                        if i + 1 + tag_len < self.buf.len() {
                            if self.buf[i + 1..i + 1 + tag_len] == dollar_tag[..]
                                && self.buf[i + 1 + tag_len] == b'$'
                            {
                                in_dollar_quote = false;
                                dollar_tag.clear();
                                i += tag_len + 2;
                                continue;
                            }
                            i += 1;
                            continue;
                        } else if at_eof {
                            i += 1;
                            continue;
                        } else {
                            break 'scan;
                        }
                    }
                }

                if b == b'\'' && !inside_double_quote && !inside_backtick && !in_dollar_quote {
                    if inside_single_quote {
                        inside_single_quote = false;
                        in_escape_string = false;
                    } else {
                        inside_single_quote = true;
                        // A PostgreSQL E'…' escape string: the quote is preceded
                        // by `E`/`e` at a word boundary (not part of an
                        // identifier ending in e).
                        in_escape_string = is_postgres
                            && i > 0
                            && matches!(self.buf[i - 1], b'E' | b'e')
                            && (i < 2 || !is_word_byte(self.buf[i - 2]));
                    }
                } else if b == b'"' && !inside_single_quote && !inside_backtick && !in_dollar_quote
                {
                    inside_double_quote = !inside_double_quote;
                } else if b == b'`'
                    && is_mysql
                    && !inside_single_quote
                    && !inside_double_quote
                    && !in_dollar_quote
                {
                    inside_backtick = !inside_backtick;
                } else if b == delim0 && !inside_string {
                    // Statement terminator. The bytes after it stay in `buf` and
                    // become the next statement (buf_pos advances, no shifting).
                    let dl = delim_len;
                    if dl == 1 {
                        let result = self.buf[start..=i].to_vec();
                        self.buf_pos = i + 1;

                        if is_postgres && self.is_copy_from_stdin(&result) {
                            self.in_copy_data = true;
                        }
                        return Ok(Some(result));
                    }
                    // Multi-byte delimiter (e.g. `;;`): the full token must match
                    // starting at `i`. A lone first byte (a `;` inside a routine
                    // body under a `;;` delimiter) is just an ordinary byte.
                    if i + dl <= self.buf.len() {
                        if self.buf[i..i + dl] == self.current_delimiter[..dl] {
                            let result = self.buf[start..i + dl].to_vec();
                            self.buf_pos = i + dl;
                            return Ok(Some(result));
                        }
                        i += 1;
                        continue;
                    } else if at_eof {
                        i += 1;
                        continue;
                    } else {
                        break 'scan;
                    }
                }

                i += 1;
            }

            if at_eof {
                if start >= self.buf.len() {
                    return Ok(None);
                }
                let result = self.buf[start..].to_vec();
                self.buf_pos = self.buf.len();
                return Ok(Some(result));
            }

            // Need more bytes. Drop already-returned statements before `start`.
            let (removed, got_more) = self.grow_buffer(start)?;
            start -= removed;
            i -= removed;
            if !got_more {
                // Re-scan the remaining bytes once more with at_eof set so any
                // incomplete token at the tail is treated literally.
                at_eof = true;
            }
        }
    }

    /// Check if statement is a PostgreSQL COPY FROM stdin
    fn is_copy_from_stdin(&self, stmt: &[u8]) -> bool {
        has_postgres_copy_stdin_source(stmt)
    }

    /// Read PostgreSQL COPY data block until we see the terminator line (\.).
    /// The returned block includes everything up to and including the
    /// terminator line; anything after it is carried in `pending`.
    ///
    /// Note: a COPY block is buffered whole in memory (like every other
    /// statement here) — its size sets the memory floor for a pg_dump with one
    /// very large table. This is intentional: downstream consumers (redact,
    /// diff, sample) operate on a full block at a time.
    fn read_copy_data(&mut self) -> std::io::Result<Option<Vec<u8>>> {
        let mut start = self.buf_pos;
        let mut scan = self.buf_pos;

        loop {
            // Scan completed lines for the terminator.
            while let Some(rel) = memchr::memchr(b'\n', &self.buf[scan..]) {
                let nl = scan + rel;
                let line = &self.buf[scan..=nl];
                if line == b"\\.\n" || line == b"\\.\r\n" {
                    self.in_copy_data = false;
                    let result = self.buf[start..=nl].to_vec();
                    self.buf_pos = nl + 1;
                    return Ok(Some(result));
                }
                scan = nl + 1;
            }

            let (removed, got_more) = self.grow_buffer(start)?;
            start -= removed;
            scan -= removed;
            if !got_more {
                self.in_copy_data = false;
                if start >= self.buf.len() {
                    return Ok(None);
                }
                let result = self.buf[start..].to_vec();
                self.buf_pos = self.buf.len();
                return Ok(Some(result));
            }
        }
    }

    /// Stream the input as [`ParserEvent`]s with bounded memory.
    ///
    /// Ordinary DDL/control statements are buffered whole (they are small) and
    /// delivered as [`ParserEvent::Statement`]. A multi-row INSERT is delivered
    /// as its header plus one [`ParserEvent::InsertRow`] per tuple, and a COPY
    /// block as [`ParserEvent::CopyStart`] / [`ParserEvent::CopyRow`] per line /
    /// [`ParserEvent::CopyEnd`] — the whole multi-row block is never buffered at
    /// once. The callback must consume each borrowed slice before returning.
    ///
    /// Unlike [`read_statement`](Self::read_statement) (kept for compatibility),
    /// data statements are not routed through it: their rows are streamed.
    pub fn visit_events<F>(&mut self, mut on_event: F) -> anyhow::Result<()>
    where
        F: FnMut(ParserEvent<'_>) -> anyhow::Result<RowFlow>,
    {
        loop {
            // Ensure at least one byte at/after buf_pos, or stop at EOF.
            while self.buf_pos >= self.buf.len() {
                let (removed, more) = self.grow_buffer(self.buf_pos)?;
                self.buf_pos -= removed;
                if !more {
                    return Ok(());
                }
            }

            if self.peek_is_insert()? {
                if self.visit_insert_stmt(&mut on_event)? == RowFlow::Stop {
                    return Ok(());
                }
                continue;
            }

            // Non-INSERT: reuse read_statement to consume one DDL/control or
            // COPY header statement (small). COPY data blocks are then streamed
            // line-by-line rather than buffered whole.
            let stmt = match self.read_statement()? {
                Some(s) => s,
                None => return Ok(()),
            };
            if self.in_copy_data {
                self.in_copy_data = false;
                let skip_rows = match on_event(ParserEvent::CopyStart(&stmt))? {
                    RowFlow::Continue => false,
                    RowFlow::SkipStatement => true,
                    RowFlow::Stop => return Ok(()),
                };
                if self.visit_copy_data(&mut on_event, skip_rows)? == RowFlow::Stop {
                    return Ok(());
                }
            } else if on_event(ParserEvent::Statement(&stmt))? == RowFlow::Stop {
                return Ok(());
            }
        }
    }

    /// Peek whether the next statement (after leading comments/whitespace) is an
    /// `INSERT INTO`/`INSERT ONLY`, growing the buffer just enough to decide.
    fn peek_is_insert(&mut self) -> anyhow::Result<bool> {
        loop {
            let stripped = strip_leading_comments_and_whitespace(&self.buf[self.buf_pos..]);
            if stripped.len() >= 11 {
                return Ok(starts_with_insert(stripped));
            }
            if self.buf.len() - self.buf_pos > self.limits.max_header {
                anyhow::bail!(
                    "statement header exceeds max_header ({} bytes) at input offset {}",
                    self.limits.max_header,
                    self.base + self.buf_pos as u64
                );
            }
            let (removed, more) = self.grow_buffer(self.buf_pos)?;
            self.buf_pos -= removed;
            if !more {
                let stripped = strip_leading_comments_and_whitespace(&self.buf[self.buf_pos..]);
                return Ok(starts_with_insert(stripped));
            }
        }
    }

    /// Stream one INSERT statement's tuples as [`ParserEvent::InsertRow`]s.
    fn visit_insert_stmt<F>(&mut self, on_event: &mut F) -> anyhow::Result<RowFlow>
    where
        F: FnMut(ParserEvent<'_>) -> anyhow::Result<RowFlow>,
    {
        // Locate the VALUES keyword, buffering only the header (bounded). The
        // scan stops at the statement's own `;`, so a VALUES-less INSERT
        // (INSERT … SELECT / SET) is emitted whole rather than absorbing later
        // statements while hunting for a VALUES that belongs to one of them.
        let (header, values_abs) = loop {
            let stripped_len =
                strip_leading_comments_and_whitespace(&self.buf[self.buf_pos..]).len();
            let start = self.buf.len() - stripped_len;
            match mysql_insert::scan_insert_header(&self.buf[start..], self.dialect) {
                mysql_insert::HeaderScan::Values(vp) => {
                    let values_abs = start + vp;
                    break (self.buf[start..values_abs].to_vec(), values_abs);
                }
                mysql_insert::HeaderScan::NoValues(end_off) => {
                    // Emit the whole statement (up to and including its `;`) as
                    // an opaque Statement; there are no rows to stream.
                    let stmt_end = start + end_off;
                    let flow = on_event(ParserEvent::Statement(&self.buf[self.buf_pos..stmt_end]))?;
                    self.buf_pos = stmt_end;
                    return Ok(flow);
                }
                mysql_insert::HeaderScan::Incomplete => {
                    if self.buf.len() - self.buf_pos > self.limits.max_header {
                        anyhow::bail!(
                            "INSERT header exceeds max_header ({} bytes) at input offset {}",
                            self.limits.max_header,
                            self.base + self.buf_pos as u64
                        );
                    }
                    let (removed, more) = self.grow_buffer(self.buf_pos)?;
                    self.buf_pos -= removed;
                    if !more {
                        // Truncated header at EOF: emit the remaining bytes as an
                        // opaque statement so nothing is lost.
                        let flow = on_event(ParserEvent::Statement(&self.buf[self.buf_pos..]))?;
                        self.buf_pos = self.buf.len();
                        return Ok(flow);
                    }
                }
            }
        };

        let mut cur = values_abs;
        let mut first = true;
        let mut skipping = false;

        loop {
            // Skip inter-tuple whitespace and commas.
            loop {
                while cur < self.buf.len()
                    && matches!(self.buf[cur], b' ' | b'\t' | b'\n' | b'\r' | b',')
                {
                    cur += 1;
                }
                if cur < self.buf.len() {
                    break;
                }
                let (removed, more) = self.grow_buffer(cur)?;
                cur -= removed;
                if !more {
                    break;
                }
            }

            if cur >= self.buf.len() {
                self.buf_pos = self.buf.len();
                return Ok(RowFlow::Continue);
            }
            match self.buf[cur] {
                b';' => {
                    self.buf_pos = cur + 1;
                    return Ok(RowFlow::Continue);
                }
                b'(' => {}
                // Anything else (e.g. an MSSQL GO batch line) ends the INSERT;
                // leave it for the next statement.
                _ => {
                    self.buf_pos = cur;
                    return Ok(RowFlow::Continue);
                }
            }

            // Scan exactly one tuple, growing until it is complete or EOF.
            let (tuple_end, complete) = loop {
                if self.buf.len() - cur > self.limits.max_row {
                    anyhow::bail!(
                        "INSERT row exceeds max_row ({} bytes) at input offset {}",
                        self.limits.max_row,
                        self.base + cur as u64
                    );
                }
                match mysql_insert::scan_insert_tuple(&self.buf[cur..], self.dialect) {
                    Some((len, true)) => break (cur + len, true),
                    Some(_) => {
                        let (removed, more) = self.grow_buffer(cur)?;
                        cur -= removed;
                        if !more {
                            break (self.buf.len(), false);
                        }
                    }
                    None => {
                        self.buf_pos = cur;
                        return Ok(RowFlow::Continue);
                    }
                }
            };

            if skipping {
                cur = tuple_end;
            } else {
                let flow = on_event(ParserEvent::InsertRow {
                    header: &header,
                    row: &self.buf[cur..tuple_end],
                    first_in_statement: first,
                })?;
                first = false;
                match flow {
                    RowFlow::Continue => cur = tuple_end,
                    RowFlow::SkipStatement => {
                        skipping = true;
                        cur = tuple_end;
                    }
                    RowFlow::Stop => {
                        self.buf_pos = tuple_end;
                        return Ok(RowFlow::Stop);
                    }
                }
            }

            if !complete {
                self.buf_pos = self.buf.len();
                return Ok(RowFlow::Continue);
            }
        }
    }

    /// Stream a COPY data block (positioned just past the header's `;`) as
    /// [`ParserEvent::CopyRow`]s followed by [`ParserEvent::CopyEnd`].
    fn visit_copy_data<F>(
        &mut self,
        on_event: &mut F,
        initially_skipping: bool,
    ) -> anyhow::Result<RowFlow>
    where
        F: FnMut(ParserEvent<'_>) -> anyhow::Result<RowFlow>,
    {
        // Consume the line terminator that ends the `COPY ... FROM stdin;`
        // header line (read_statement stopped at the `;`), so the first emitted
        // CopyRow is a real data line rather than a phantom empty one.
        for &want in b"\r\n" {
            while self.buf_pos >= self.buf.len() {
                let (removed, more) = self.grow_buffer(self.buf_pos)?;
                self.buf_pos -= removed;
                if !more {
                    return Ok(RowFlow::Continue);
                }
            }
            if self.buf[self.buf_pos] == want {
                self.buf_pos += 1;
            }
        }

        let mut ls = self.buf_pos;
        let mut skipping = initially_skipping;

        loop {
            let nl = loop {
                if let Some(rel) = memchr::memchr(b'\n', &self.buf[ls..]) {
                    break Some(ls + rel);
                }
                if self.buf.len() - ls > self.limits.max_row {
                    anyhow::bail!(
                        "COPY line exceeds max_row ({} bytes) at input offset {}",
                        self.limits.max_row,
                        self.base + ls as u64
                    );
                }
                let (removed, more) = self.grow_buffer(ls)?;
                ls -= removed;
                if !more {
                    break None;
                }
            };

            if nl.is_none() && ls >= self.buf.len() {
                // EOF with no trailing data.
                self.buf_pos = self.buf.len();
                return Ok(RowFlow::Continue);
            }

            let line_end = nl.unwrap_or(self.buf.len());
            let line = &self.buf[ls..line_end];
            let check: &[u8] = if line.last() == Some(&b'\r') {
                &line[..line.len() - 1]
            } else {
                line
            };

            if check == b"\\." {
                let flow = on_event(ParserEvent::CopyEnd)?;
                self.buf_pos = nl.map(|n| n + 1).unwrap_or(self.buf.len());
                return Ok(flow);
            }

            if !skipping {
                match on_event(ParserEvent::CopyRow(line))? {
                    RowFlow::Continue => {}
                    RowFlow::SkipStatement => skipping = true,
                    RowFlow::Stop => {
                        self.buf_pos = nl.map(|n| n + 1).unwrap_or(self.buf.len());
                        return Ok(RowFlow::Stop);
                    }
                }
            }

            match nl {
                Some(n) => ls = n + 1,
                None => {
                    self.buf_pos = self.buf.len();
                    return Ok(RowFlow::Continue);
                }
            }
        }
    }

    /// Read MSSQL statement with GO batch separator support.
    /// GO is a batch separator that appears on its own line; `;` also
    /// terminates. Uses the same `buf` + cursor model as [`read_statement`] so
    /// tokens can't straddle a chunk boundary and scanning stays O(n).
    fn read_statement_mssql(&mut self) -> std::io::Result<Option<Vec<u8>>> {
        let mut start = self.buf_pos;
        let mut i = self.buf_pos;
        let mut line_start = self.buf_pos;

        let mut inside_single_quote = false;
        let mut inside_bracket_quote = false;
        let mut in_line_comment = false;
        let mut in_block_comment = false;
        let mut at_eof = false;

        loop {
            'scan: while i < self.buf.len() {
                let b = self.buf[i];

                if in_block_comment {
                    if b == b'*' {
                        match self.peek2(i, b'/', at_eof) {
                            Peek2::Hit => {
                                in_block_comment = false;
                                i += 2;
                                continue;
                            }
                            Peek2::Miss => {
                                i += 1;
                                continue;
                            }
                            Peek2::NeedMore => break 'scan,
                        }
                    }
                    i += 1;
                    continue;
                }

                if in_line_comment {
                    if b == b'\n' {
                        in_line_comment = false;
                        line_start = i + 1;
                    }
                    i += 1;
                    continue;
                }

                if inside_bracket_quote {
                    if b == b']' {
                        match self.peek2(i, b']', at_eof) {
                            // Escaped ]] stays inside the identifier (bug #8)
                            Peek2::Hit => {
                                i += 2;
                                continue;
                            }
                            Peek2::Miss => {
                                inside_bracket_quote = false;
                                i += 1;
                                continue;
                            }
                            Peek2::NeedMore => break 'scan,
                        }
                    }
                    i += 1;
                    continue;
                }

                if inside_single_quote {
                    // Fast-skip to the closing quote (MSSQL has no `\` escapes).
                    match memchr::memchr(b'\'', &self.buf[i..]) {
                        Some(0) => inside_single_quote = false,
                        Some(off) => {
                            i += off;
                            continue;
                        }
                        None if at_eof => {
                            i = self.buf.len();
                            continue;
                        }
                        None => break 'scan,
                    }
                    i += 1;
                    continue;
                }

                // Outside strings/comments.
                if b == b'-' {
                    match self.peek2(i, b'-', at_eof) {
                        Peek2::Hit => {
                            in_line_comment = true;
                            i += 2;
                            continue;
                        }
                        Peek2::Miss => {
                            i += 1;
                            continue;
                        }
                        Peek2::NeedMore => break 'scan,
                    }
                }
                if b == b'/' {
                    match self.peek2(i, b'*', at_eof) {
                        Peek2::Hit => {
                            in_block_comment = true;
                            i += 2;
                            continue;
                        }
                        Peek2::Miss => {
                            i += 1;
                            continue;
                        }
                        Peek2::NeedMore => break 'scan,
                    }
                }
                if b == b'\'' {
                    inside_single_quote = true;
                    i += 1;
                    continue;
                }
                if b == b'[' {
                    inside_bracket_quote = true;
                    i += 1;
                    continue;
                }
                if b == b';' {
                    let result = self.buf[start..=i].to_vec();
                    self.buf_pos = i + 1;
                    return Ok(Some(result));
                }
                if b == b'\n' {
                    if is_go_line(&self.buf[line_start..=i]) {
                        // Trim trailing whitespace before the GO line.
                        let mut stmt_end = line_start;
                        while stmt_end > start
                            && matches!(self.buf[stmt_end - 1], b'\n' | b'\r' | b' ' | b'\t')
                        {
                            stmt_end -= 1;
                        }
                        self.buf_pos = i + 1;
                        if stmt_end > start {
                            return Ok(Some(self.buf[start..stmt_end].to_vec()));
                        }
                        // Empty batch: start a new statement after the GO line.
                        start = i + 1;
                        line_start = i + 1;
                        i += 1;
                        continue;
                    }
                    line_start = i + 1;
                    i += 1;
                    continue;
                }

                i += 1;
            }

            if at_eof {
                if start >= self.buf.len() {
                    return Ok(None);
                }
                // Handle a trailing GO with no final newline (bug #12).
                if is_go_line(&self.buf[line_start..]) {
                    let mut stmt_end = line_start;
                    while stmt_end > start
                        && matches!(self.buf[stmt_end - 1], b'\n' | b'\r' | b' ' | b'\t')
                    {
                        stmt_end -= 1;
                    }
                    self.buf_pos = self.buf.len();
                    if stmt_end > start {
                        return Ok(Some(self.buf[start..stmt_end].to_vec()));
                    }
                    return Ok(None);
                }
                let result = self.buf[start..].to_vec();
                self.buf_pos = self.buf.len();
                return Ok(Some(result));
            }

            let (removed, got_more) = self.grow_buffer(start)?;
            start -= removed;
            i -= removed;
            line_start -= removed;
            if !got_more {
                at_eof = true;
            }
        }
    }

    #[allow(dead_code)]
    pub fn parse_statement(stmt: &[u8]) -> (StatementType, String) {
        Self::parse_statement_with_dialect(stmt, SqlDialect::MySql)
    }

    /// Parse a statement with dialect-specific handling
    pub fn parse_statement_with_dialect(
        stmt: &[u8],
        dialect: SqlDialect,
    ) -> (StatementType, String) {
        // Strip leading comments (e.g., pg_dump adds -- comments before statements)
        let stmt = strip_leading_comments_and_whitespace(stmt);

        if stmt.len() < 4 {
            return (StatementType::Unknown, String::new());
        }

        // Use stack-allocated buffer to avoid heap allocation in hot path
        let mut upper_prefix = [0u8; 25];
        let prefix_len = stmt.len().min(25);
        for (i, &b) in stmt.iter().take(prefix_len).enumerate() {
            upper_prefix[i] = b.to_ascii_uppercase();
        }
        let upper_prefix = &upper_prefix[..prefix_len];

        // PostgreSQL COPY statement
        if upper_prefix.starts_with(b"COPY ") {
            if let Some(name) = extract_table_name_flexible(stmt, 4, dialect) {
                return (StatementType::Copy, name);
            }
        }

        if upper_prefix.starts_with(b"CREATE TABLE") {
            // Try fast extraction first
            if let Some(name) = extract_table_name_flexible(stmt, 12, dialect) {
                return (StatementType::CreateTable, name);
            }
            // Fall back to flexible regex
            if let Some(caps) = CREATE_TABLE_FLEXIBLE_RE.captures(stmt) {
                if let Some(m) = caps.get(1) {
                    return (
                        StatementType::CreateTable,
                        String::from_utf8_lossy(m.as_bytes()).into_owned(),
                    );
                }
            }
        }

        if upper_prefix.starts_with(b"INSERT INTO") || upper_prefix.starts_with(b"INSERT ONLY") {
            if let Some(name) = extract_table_name_flexible(stmt, 11, dialect) {
                return (StatementType::Insert, name);
            }
            if let Some(caps) = INSERT_FLEXIBLE_RE.captures(stmt) {
                if let Some(m) = caps.get(1) {
                    return (
                        StatementType::Insert,
                        String::from_utf8_lossy(m.as_bytes()).into_owned(),
                    );
                }
            }
        }

        if upper_prefix.starts_with(b"CREATE INDEX")
            || upper_prefix.starts_with(b"CREATE UNIQUE")
            || upper_prefix.starts_with(b"CREATE CLUSTERED")
            || upper_prefix.starts_with(b"CREATE NONCLUSTER")
        {
            // For MSSQL, try the bracket-aware regex first
            if dialect == SqlDialect::Mssql {
                if let Some(caps) = CREATE_INDEX_MSSQL_RE.captures(stmt) {
                    if let Some(m) = caps.get(1) {
                        if let Some(name) = extract_table_name_flexible(m.as_bytes(), 0, dialect) {
                            return (StatementType::CreateIndex, name);
                        }
                    }
                }
            }
            // Fall back to generic regex for MySQL/PostgreSQL/SQLite
            if let Some(caps) = CREATE_INDEX_RE.captures(stmt) {
                if let Some(m) = caps.get(1) {
                    if let Some(name) = extract_table_name_flexible(m.as_bytes(), 0, dialect) {
                        return (StatementType::CreateIndex, name);
                    }
                }
            }
        }

        if upper_prefix.starts_with(b"ALTER TABLE") {
            if let Some(name) = extract_table_name_flexible(stmt, 11, dialect) {
                return (StatementType::AlterTable, name);
            }
            if let Some(caps) = ALTER_TABLE_RE.captures(stmt) {
                if let Some(m) = caps.get(1) {
                    return (
                        StatementType::AlterTable,
                        String::from_utf8_lossy(m.as_bytes()).into_owned(),
                    );
                }
            }
        }

        if upper_prefix.starts_with(b"DROP TABLE") {
            if let Some(name) = extract_table_name_flexible(stmt, 10, dialect) {
                return (StatementType::DropTable, name);
            }
            if let Some(caps) = DROP_TABLE_RE.captures(stmt) {
                if let Some(m) = caps.get(1) {
                    return (
                        StatementType::DropTable,
                        String::from_utf8_lossy(m.as_bytes()).into_owned(),
                    );
                }
            }
        }

        // MSSQL BULK INSERT - treat as Insert statement type
        if upper_prefix.starts_with(b"BULK INSERT") {
            if let Some(name) = extract_table_name_flexible(stmt, 11, dialect) {
                return (StatementType::Insert, name);
            }
        }

        (StatementType::Unknown, String::new())
    }
}

#[inline]
fn trim_ascii_start(data: &[u8]) -> &[u8] {
    let start = data
        .iter()
        .position(|&b| !matches!(b, b' ' | b'\t' | b'\n' | b'\r'))
        .unwrap_or(data.len());
    &data[start..]
}

/// Strip leading whitespace and SQL line comments (`-- ...`) from a statement.
/// This makes parsing robust to pg_dump-style comment blocks before statements.
pub(crate) fn strip_leading_comments_and_whitespace(mut data: &[u8]) -> &[u8] {
    loop {
        // First trim leading ASCII whitespace
        data = trim_ascii_start(data);

        // Strip a leading UTF-8 BOM (EF BB BF). Without this the first statement
        // in a BOM-prefixed dump classifies as Unknown and split drops it.
        if data.starts_with(&[0xEF, 0xBB, 0xBF]) {
            data = &data[3..];
            continue;
        }

        // Handle -- line comments
        if data.len() >= 2 && data[0] == b'-' && data[1] == b'-' {
            // Skip until end of line
            if let Some(pos) = data.iter().position(|&b| b == b'\n') {
                data = &data[pos + 1..];
                continue;
            } else {
                // Comment runs to EOF, nothing left
                return &[];
            }
        }

        // Handle /* */ block comments (including MySQL conditional comments)
        if data.len() >= 2 && data[0] == b'/' && data[1] == b'*' {
            // Find the closing */
            let mut i = 2;
            let mut depth = 1;
            while i < data.len() - 1 && depth > 0 {
                if data[i] == b'*' && data[i + 1] == b'/' {
                    depth -= 1;
                    i += 2;
                } else if data[i] == b'/' && data[i + 1] == b'*' {
                    depth += 1;
                    i += 2;
                } else {
                    i += 1;
                }
            }
            if depth == 0 {
                data = &data[i..];
                continue;
            } else {
                // Unclosed comment runs to EOF
                return &[];
            }
        }

        // Handle # line comments (MySQL)
        if !data.is_empty() && data[0] == b'#' {
            if let Some(pos) = data.iter().position(|&b| b == b'\n') {
                data = &data[pos + 1..];
                continue;
            } else {
                return &[];
            }
        }

        break;
    }

    data
}

/// Return whether `stmt` is a PostgreSQL `COPY ... FROM STDIN` command.
///
/// This deliberately recognizes source tokens rather than searching bytes. A
/// quoted identifier, a string literal, a comment, or a parenthesized COPY
/// query can contain `FROM STDIN` without opening a data block.
fn has_postgres_copy_stdin_source(stmt: &[u8]) -> bool {
    let stmt = strip_leading_comments_and_whitespace(stmt);
    let mut i = 0;
    let mut paren_depth = 0u32;
    let mut saw_copy = false;
    let mut expecting_stdin = false;

    while i < stmt.len() {
        let byte = stmt[i];

        if is_whitespace(byte) {
            i += 1;
            continue;
        }

        if byte == b'-' && stmt.get(i + 1) == Some(&b'-') {
            i += 2;
            while i < stmt.len() && stmt[i] != b'\n' {
                i += 1;
            }
            continue;
        }

        if byte == b'/' && stmt.get(i + 1) == Some(&b'*') {
            i += 2;
            let mut comment_depth = 1u32;
            while i < stmt.len() && comment_depth > 0 {
                match (stmt[i], stmt.get(i + 1)) {
                    (b'/', Some(b'*')) => {
                        comment_depth += 1;
                        i += 2;
                    }
                    (b'*', Some(b'/')) => {
                        comment_depth -= 1;
                        i += 2;
                    }
                    _ => i += 1,
                }
            }
            continue;
        }

        if matches!(byte, b'\'' | b'\"' | b'`' | b'[') {
            let close = if byte == b'[' { b']' } else { byte };
            i += 1;
            while i < stmt.len() {
                if stmt[i] == b'\\' && close == b'\'' && i + 1 < stmt.len() {
                    i += 2;
                    continue;
                }
                if stmt[i] == close {
                    if stmt.get(i + 1) == Some(&close) {
                        i += 2;
                        continue;
                    }
                    i += 1;
                    break;
                }
                i += 1;
            }
            expecting_stdin = false;
            continue;
        }

        match byte {
            b'(' => {
                paren_depth = paren_depth.saturating_add(1);
                expecting_stdin = false;
                i += 1;
                continue;
            }
            b')' => {
                paren_depth = paren_depth.saturating_sub(1);
                expecting_stdin = false;
                i += 1;
                continue;
            }
            b';' => return false,
            _ => {}
        }

        if byte.is_ascii_alphabetic() || byte == b'_' {
            let start = i;
            i += 1;
            while i < stmt.len() && is_word_byte(stmt[i]) {
                i += 1;
            }
            let word = &stmt[start..i];

            if !saw_copy {
                if !word.eq_ignore_ascii_case(b"COPY") {
                    return false;
                }
                saw_copy = true;
                continue;
            }

            if paren_depth == 0 {
                if expecting_stdin {
                    return word.eq_ignore_ascii_case(b"STDIN");
                }
                expecting_stdin = word.eq_ignore_ascii_case(b"FROM");
            }
            continue;
        }

        expecting_stdin = false;
        i += 1;
    }

    false
}

/// Extract table name with support for:
/// - IF NOT EXISTS
/// - ONLY (PostgreSQL)
/// - Schema-qualified names (`schema.table` is retained)
/// - Both backtick and double-quote quoting
#[inline]
pub(crate) fn extract_table_name_flexible(
    stmt: &[u8],
    offset: usize,
    dialect: SqlDialect,
) -> Option<String> {
    let mut i = offset;

    // Skip whitespace
    while i < stmt.len() && is_whitespace(stmt[i]) {
        i += 1;
    }

    if i >= stmt.len() {
        return None;
    }

    // Check for IF NOT EXISTS or IF EXISTS (stack-allocated to avoid heap allocation)
    let mut upper_check = [0u8; 20];
    let check_len = (stmt.len() - i).min(20);
    for (idx, &b) in stmt[i..].iter().take(check_len).enumerate() {
        upper_check[idx] = b.to_ascii_uppercase();
    }
    let upper_slice = &upper_check[..check_len];
    if upper_slice.starts_with(b"IF NOT EXISTS") {
        i += 13; // Skip "IF NOT EXISTS"
        while i < stmt.len() && is_whitespace(stmt[i]) {
            i += 1;
        }
    } else if upper_slice.starts_with(b"IF EXISTS") {
        i += 9; // Skip "IF EXISTS"
        while i < stmt.len() && is_whitespace(stmt[i]) {
            i += 1;
        }
    }

    // Check for ONLY (PostgreSQL) - reuse first 10 bytes or re-check if position changed
    let only_check = if i < stmt.len() {
        let mut buf = [0u8; 10];
        let len = (stmt.len() - i).min(10);
        for (idx, &b) in stmt[i..].iter().take(len).enumerate() {
            buf[idx] = b.to_ascii_uppercase();
        }
        (buf, len)
    } else {
        ([0u8; 10], 0)
    };
    let only_slice = &only_check.0[..only_check.1];
    if only_slice.starts_with(b"ONLY ") || only_slice.starts_with(b"ONLY\t") {
        i += 4;
        while i < stmt.len() && is_whitespace(stmt[i]) {
            i += 1;
        }
    }

    if i >= stmt.len() {
        return None;
    }

    // Read identifier (potentially schema-qualified)
    let mut parts: Vec<String> = Vec::new();

    loop {
        // Determine quote character based on dialect
        let (quote_char, close_char) = match stmt.get(i) {
            Some(b'`') if dialect == SqlDialect::MySql => {
                i += 1;
                (Some(b'`'), b'`')
            }
            // Double quotes are the standard identifier quote for
            // Postgres/SQLite/MSSQL, and accepted for MySQL too (less common).
            Some(b'"') => {
                i += 1;
                (Some(b'"'), b'"')
            }
            Some(b'[') if dialect == SqlDialect::Mssql => {
                // MSSQL square bracket quoting
                i += 1;
                (Some(b'['), b']')
            }
            _ => (None, 0),
        };

        let start = i;

        while i < stmt.len() {
            let b = stmt[i];
            if quote_char.is_some() {
                if b == close_char {
                    // For MSSQL, check for escaped ]]
                    if dialect == SqlDialect::Mssql
                        && close_char == b']'
                        && i + 1 < stmt.len()
                        && stmt[i + 1] == b']'
                    {
                        // Escaped bracket, skip both
                        i += 2;
                        continue;
                    }
                    let name = &stmt[start..i];
                    // For MSSQL, unescape ]] to ]
                    let name_str = match quote_char {
                        Some(b'[') if dialect == SqlDialect::Mssql => {
                            String::from_utf8_lossy(name).replace("]]", "]")
                        }
                        Some(b'"') => String::from_utf8_lossy(name).replace("\"\"", "\""),
                        Some(b'`') => String::from_utf8_lossy(name).replace("``", "`"),
                        _ => String::from_utf8_lossy(name).into_owned(),
                    };
                    parts.push(canonicalize_qualified_part(name_str, quote_char.is_some()));
                    i += 1; // Skip closing quote
                    break;
                }
            } else if is_whitespace(b) || b == b'(' || b == b';' || b == b',' || b == b'.' {
                if i > start {
                    let name = &stmt[start..i];
                    parts.push(String::from_utf8_lossy(name).into_owned());
                }
                break;
            }
            i += 1;
        }

        // An unquoted terminal component can run to the end of a captured
        // table reference (for example `dbo.users` extracted from CREATE
        // INDEX), where the delimiter branch above never gets a chance to
        // push it.
        if quote_char.is_none() && i == stmt.len() && i > start {
            parts.push(String::from_utf8_lossy(&stmt[start..i]).into_owned());
        }

        // If at end of quoted name without finding close quote, bail
        if quote_char.is_some() && i <= start {
            break;
        }

        // Check for schema separator (.)
        while i < stmt.len() && is_whitespace(stmt[i]) {
            i += 1;
        }

        if i < stmt.len() && stmt[i] == b'.' {
            i += 1; // Skip the dot
            while i < stmt.len() && is_whitespace(stmt[i]) {
                i += 1;
            }
            // Continue to read the next identifier (table name)
        } else {
            break;
        }
    }

    if parts.is_empty() {
        None
    } else {
        Some(parts.join("."))
    }
}

#[inline]
fn is_whitespace(b: u8) -> bool {
    matches!(b, b' ' | b'\t' | b'\n' | b'\r')
}

/// Preserve a quoted identifier component that contains a dot. The schema and
/// output layers use dots as table-reference separators, so retaining quote
/// boundaries prevents `public."user.log"` from becoming three components.
fn canonicalize_qualified_part(part: String, was_quoted: bool) -> String {
    if was_quoted && part.contains('.') {
        format!("\"{}\"", part.replace('"', "\"\""))
    } else {
        part
    }
}

/// True if `b` can be part of a SQL identifier (letters, digits, `_`). Used to
/// tell a PostgreSQL `E'…'` escape-string prefix from an identifier that merely
/// ends in `e` (e.g. `type`).
#[inline]
fn is_word_byte(b: u8) -> bool {
    b.is_ascii_alphanumeric() || b == b'_'
}

/// True if `s` begins with an `INSERT INTO`/`INSERT ONLY` value statement (the
/// forms that carry a `VALUES` list). `BULK INSERT` and other keywords are
/// intentionally excluded so [`Parser::visit_events`] only enters tuple-
/// streaming mode for statements it can actually stream.
#[inline]
fn starts_with_insert(s: &[u8]) -> bool {
    s.len() >= 11
        && (s[..11].eq_ignore_ascii_case(b"INSERT INTO")
            || s[..11].eq_ignore_ascii_case(b"INSERT ONLY"))
}

/// A dollar-quote tag is either empty (`$$`) or an identifier
/// (`[A-Za-z_][A-Za-z0-9_]*`), matching PostgreSQL's rules.
#[inline]
fn is_valid_dollar_tag(tag: &[u8]) -> bool {
    match tag.first() {
        None => true,
        Some(&first) if first.is_ascii_alphabetic() || first == b'_' => tag[1..]
            .iter()
            .all(|&c| c.is_ascii_alphanumeric() || c == b'_'),
        _ => false,
    }
}

pub fn determine_buffer_size(file_size: u64) -> usize {
    if file_size > 1024 * 1024 * 1024 {
        MEDIUM_BUFFER_SIZE
    } else {
        SMALL_BUFFER_SIZE
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn copy_source_detection_ignores_quoted_and_literal_text() {
        for stmt in [
            b"COPY \"FROM STDIN\" TO STDOUT;".as_slice(),
            b"COPY report TO 'FROM STDIN';".as_slice(),
            b"COPY (SELECT 'FROM STDIN') TO STDOUT;".as_slice(),
            b"COPY report /* FROM STDIN */ TO STDOUT;".as_slice(),
        ] {
            assert!(
                !has_postgres_copy_stdin_source(stmt),
                "unexpected COPY data mode for {stmt:?}"
            );
        }
    }

    #[test]
    fn copy_source_detection_accepts_comments_between_source_tokens() {
        let stmt = b"COPY report (id) /* source */ FROM /* terminal */ STDIN;";
        assert!(has_postgres_copy_stdin_source(stmt));
    }

    #[test]
    fn copy_start_skip_statement_skips_rows_and_reaches_following_statement() {
        let sql = b"COPY report (id) FROM STDIN;\n1\n2\n\\.\nSELECT 42;";
        let mut parser = Parser::with_dialect(&sql[..], 8, SqlDialect::Postgres);
        let mut events = Vec::new();

        parser
            .visit_events(|event| match event {
                ParserEvent::CopyStart(_) => {
                    events.push("start");
                    Ok(RowFlow::SkipStatement)
                }
                ParserEvent::CopyRow(_) => {
                    events.push("row");
                    Ok(RowFlow::Continue)
                }
                ParserEvent::CopyEnd => {
                    events.push("end");
                    Ok(RowFlow::Continue)
                }
                ParserEvent::Statement(stmt) => {
                    assert_eq!(stmt, b"SELECT 42;");
                    events.push("statement");
                    Ok(RowFlow::Continue)
                }
                ParserEvent::InsertRow { .. } => unreachable!("unexpected INSERT event"),
            })
            .unwrap();

        assert_eq!(events, ["start", "end", "statement"]);
    }

    #[test]
    fn parser_retains_qualified_copy_names() {
        let cases = [
            (
                b"COPY public.users (id) FROM STDIN;".as_slice(),
                "public.users",
            ),
            (
                b"COPY \"tenant_a\".\"users\" (id) FROM STDIN;".as_slice(),
                "tenant_a.users",
            ),
            (
                b"COPY public.\"user.log\" (id) FROM STDIN;".as_slice(),
                "public.\"user.log\"",
            ),
        ];

        for (stmt, expected) in cases {
            let (kind, name) =
                Parser::<&[u8]>::parse_statement_with_dialect(stmt, SqlDialect::Postgres);
            assert_eq!(kind, StatementType::Copy);
            assert_eq!(name, expected);
        }
    }

    #[test]
    fn parser_retains_qualified_mssql_index_names() {
        for stmt in [
            b"CREATE INDEX users_email_idx ON [dbo].[users] ([email]);".as_slice(),
            b"CREATE INDEX users_email_idx ON dbo.users (email);".as_slice(),
        ] {
            let (kind, name) =
                Parser::<&[u8]>::parse_statement_with_dialect(stmt, SqlDialect::Mssql);
            assert_eq!(kind, StatementType::CreateIndex);
            assert_eq!(name, "dbo.users");
        }
    }

    #[test]
    fn parser_normalizes_quoted_qualified_generic_index_names() {
        let (kind, name) = Parser::<&[u8]>::parse_statement_with_dialect(
            b"CREATE INDEX users_email_idx ON \"tenant_a\".\"users\" (email);",
            SqlDialect::Postgres,
        );
        assert_eq!(kind, StatementType::CreateIndex);
        assert_eq!(name, "tenant_a.users");
    }

    #[test]
    fn parser_streams_mssql_temporary_table_insert_rows() {
        let sql = b"INSERT INTO #daily_users (id) VALUES (1), (2);";
        let mut parser = Parser::with_dialect(&sql[..], 8, SqlDialect::Mssql);
        let mut rows = 0;

        parser
            .visit_events(|event| match event {
                ParserEvent::InsertRow { .. } => {
                    rows += 1;
                    Ok(RowFlow::Continue)
                }
                ParserEvent::Statement(_) | ParserEvent::CopyStart(_) | ParserEvent::CopyEnd => {
                    Ok(RowFlow::Continue)
                }
                ParserEvent::CopyRow(_) => unreachable!("unexpected COPY row"),
            })
            .unwrap();

        assert_eq!(rows, 2);
    }
}