razeri-plugin-contract 0.3.2

The dialect contract Razeri plugins are written against — rendering traits, data types, platform identity
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
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
// Copyright (C) 2026 Gabriel Shea
// Licensed under either of the Apache License, Version 2.0 or the MIT
// license, at your option.

//! Layered rendering traits for SQL generation.
//!
//! The hierarchy is designed so that implementing [`SqlRenderer`] (4 methods)
//! gives you ANSI-standard defaults for all higher-level traits.

use crate::DataType;
use crate::constraint_enforcement::ConstraintEnforcement;
use crate::evolution::ColumnEvolution;
use crate::procedure_log_level::ProcedureLogLevel;
use crate::routine_form::{ProcedureForm, ScalarFunctionForm, TableFunctionForm};
use crate::routine_spec::RoutineSpec;
use crate::sid_spelling::{SidHelperBody, SidSpelling, UNSPELLED_SID};

/// **Where the aggregated expression goes** in a form returned by
/// [`SqlRenderer::median_aggregate_form`].
///
/// The form is a template rather than finished SQL so that *which function*
/// and *how a column is written* stay in different hands — the dialect answers
/// the first, the query renderer the second. A form must carry this token
/// exactly once.
pub const AGGREGATE_ARGUMENT: &str = "{argument}";

/// **What kind of value an aggregate would have to collapse** — the axis
/// [`SqlRenderer::render_single_row_aggregate`] varies on, held to three arms
/// because three is what the measurements distinguish.
///
/// Not the full type lattice: `MAX` behaves identically across every numeric,
/// textual and temporal type on every platform razeri reaches, and splitting
/// them would invite per-type arms nothing has measured.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AggregableKind {
    /// Numeric, textual and temporal — every platform orders these and every
    /// platform has `MAX` for them.
    Orderable,
    /// A truth value. `PostgreSQL` and SQL Server have no `MAX` for it and each
    /// spells the collapse differently.
    Boolean,
    /// `uuid`, JSON, binary, interval, array, map — the families with no
    /// ordering to borrow. Availability is per platform and is measured, never
    /// assumed.
    Opaque,
}

/// **A clock bound once for a whole load script** — what
/// [`SqlRenderer::render_inline_clock_binding`] answers on an engine whose
/// loads ship as flat statement lists rather than procedure bodies.
///
/// The `statements` run first and capture the engine's current moment under
/// one name; `reference` is the expression every later statement of the same
/// run reads it back by. One binding, many readers, is what makes a version's
/// close and its successor's open the same instant by construction.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InlineClockBinding {
    /// The statement(s) that bind the moment, in run order, each terminated.
    pub statements: Vec<String>,
    /// The expression that reads the bound moment back.
    pub reference: String,
}

/// Level 1 — Core SQL rendering. REQUIRED: every dialect must implement these 4 methods.
///
/// These methods define the absolute minimum surface for rendering SQL:
/// data types, identifier quoting, qualified names, and timestamps.
pub trait SqlRenderer: Send + Sync {
    /// Render a [`DataType`] as platform-specific SQL.
    fn render_data_type(&self, dt: &DataType) -> String;

    /// **The type text for a routine's PARAMETER**, which is not always the text
    /// a column carries.
    ///
    /// Most engines spell a type one way wherever it appears, and for those this
    /// hook is [`Self::render_data_type`] under another name — which is the
    /// default, so a dialect with nothing to say says nothing.
    ///
    /// **Oracle is the reason it exists.** A column there takes
    /// `NUMBER(19, 0)` and `VARCHAR2(100)`; the same types in a parameter list
    /// are a compile error (`PLS-00103`, reported at the opening parenthesis),
    /// and the bare `NUMBER` and `VARCHAR2` are what a parameter clause takes.
    /// The length and the precision belong on the local declaration instead,
    /// which keeps them. A dialect there answers:
    ///
    /// ```ignore
    /// fn render_parameter_data_type(&self, dt: &DataType) -> String {
    ///     let column = self.render_data_type(dt);
    ///     match column.find('(') {
    ///         Some(at) => column[..at].trim_end().to_owned(),
    ///         None => column,
    ///     }
    /// }
    /// ```
    ///
    /// It is what fills
    /// [`RoutineParameter::data_type`](crate::routine_spec::RoutineParameter::data_type),
    /// so a dialect that answers it does not also post-process the string
    /// Razeri handed it.
    ///
    /// Parameters:
    /// - `dt`: the type the design declared.
    fn render_parameter_data_type(&self, dt: &DataType) -> String {
        self.render_data_type(dt)
    }

    /// **The type text for a column that ADMITS NULL** — the whole type, not a
    /// modifier appended to one.
    ///
    /// Nine of razeri's ten platforms spell nullability by SILENCE: a column
    /// declared without `NOT NULL` admits one, and its type text is the same
    /// text a required column carries. That is the default here, and for those
    /// nine this hook is [`SqlRenderer::render_data_type`] under another name.
    ///
    /// **`ClickHouse` is the exception, and it is the reason this hook exists.**
    /// There a bare type is NOT NULL — nullability is a property OF the type,
    /// spelled `Nullable(T)` — so a renderer that expresses *nullable* by
    /// omitting a keyword expresses nothing at all. `render_field` used to carry
    /// a comment saying the wrapper was *"handled in data type"*; it was handled
    /// nowhere, and every `nullable:` a design declared was discarded on that
    /// one engine (`Nullable(` appeared ZERO times in any rendered
    /// `schema.sql`).
    ///
    /// # What the discard actually cost, measured rather than assumed
    ///
    /// Not a loud refusal. `insert_null_as_default` **defaults to `1`** on
    /// `ClickHouse` (24.10.2, server default, `changed = 0`), so
    /// `INSERT … SELECT NULL` into a bare column does not raise — it writes the
    /// TYPE'S DEFAULT, silently: `''` for `String`, `0` for `Int64`,
    /// `1900-01-01` for `Date32` (which is razeri's own unknown-member date, so
    /// an unknown attribute came back indistinguishable from a deliberately
    /// seeded one). Only with `insert_null_as_default = 0` does the engine
    /// answer `Code: 70 … Cannot convert NULL to a non-nullable type`. **A
    /// design's own data was being fabricated on one engine and honest on the
    /// other nine**, and the DDL is where that is fixed.
    ///
    /// # A dialect overriding this owes a measurement
    ///
    /// Not every type can be wrapped. `ClickHouse` refuses
    /// `Nullable(Array(…))`, `Nullable(Map(…))` and `Nullable(JSON)` outright,
    /// so its override declines those and says so in its own rustdoc. A
    /// wrapper that cannot be applied must be DECLINED by name, never applied
    /// and hoped for: an unwrappable type rendered `Nullable(…)` turns a silent
    /// wrong value into a `CREATE TABLE` that does not run.
    fn render_nullable_data_type(&self, dt: &DataType) -> String {
        self.render_data_type(dt)
    }

    /// Quote an identifier using platform conventions.
    ///
    /// `PostgreSQL`: `"name"`, `MySQL`: `` `name` ``, SQL Server: `[name]`
    fn quote_identifier(&self, name: &str) -> String;

    /// Render a fully qualified name (optional schema + name).
    fn qualify_name(&self, schema: Option<&str>, name: &str) -> String;

    /// Whether this dialect uses schemas in qualified names.
    ///
    /// `ClickHouse` uses only `database.object` (no schema level).
    /// Default: `true` (most platforms use `catalog.schema.object`).
    fn uses_schema_in_qualified_names(&self) -> bool {
        true
    }

    /// Whether this dialect is the "agnostic" pseudo-dialect.
    ///
    /// Agnostic rendering produces unquoted, platform-neutral DDL.
    /// Real dialect implementations should not override this.
    fn is_agnostic_dialect(&self) -> bool {
        false
    }

    /// Whether this dialect supports `SECURE VIEW` (Snowflake).
    fn supports_secure_view(&self) -> bool {
        false
    }

    /// Whether this dialect supports `GLOBAL TEMPORARY VIEW` (Databricks).
    fn supports_global_temporary_view(&self) -> bool {
        false
    }

    /// Render the platform's `CURRENT_TIMESTAMP` expression.
    fn render_current_timestamp(&self) -> String;

    /// Return a stable string identifier for this dialect.
    ///
    /// Used for dispatch when trait-based rendering is not yet available for
    /// a domain concept, and as a human-readable label in diagnostics and
    /// error messages.  This method works for **all dialects** registered
    /// in the `PlatformRegistry` (e.g. `"postgresql"`, `"sqlite"`,
    /// `"cockroachdb"`).
    ///
    /// Convention: lowercase, hyphen-separated (e.g. `"postgresql"`,
    /// `"sql-server"`, `"snowflake"`, `"sqlite"`).
    ///
    /// The default returns `"ansi"`.
    fn dialect_name(&self) -> &'static str {
        "ansi"
    }

    /// **How this engine spells a surrogate key.**
    ///
    /// Razeri derives every key one way — normalize each part, join them, hash
    /// the result, guard NULLs with a sentinel — and composes that derivation
    /// in exactly one place. What a dialect decides is the *vocabulary*: what
    /// this engine calls `LOWER` and `TRIM`, how it joins strings, how it casts
    /// a value to text, and how it spells a 64-bit hash.
    ///
    /// The default is [`UNSPELLED_SID`] — ANSI's vocabulary under a name that
    /// says it is a guess. **A dialect that leaves it there is telling Razeri it
    /// has not decided**, and the emitted SQL will call an `xxhash64` its engine
    /// very likely does not have. Override it.
    ///
    /// If your engine has no portable 64-bit hash, say so rather than reaching
    /// for the nearest-looking function: a hash that is deterministic within one
    /// warehouse and equal to nothing outside it is the lock-in a portable key
    /// exists to end. Name an artifact your dialect's prerequisites install, or
    /// refuse the key and orient the reader.
    fn sid_spelling(&self) -> SidSpelling {
        UNSPELLED_SID
    }

    /// **The body of the surrogate-key helper, where SQL cannot spell it.**
    ///
    /// Razeri emits one function per warehouse — `generate_sid` — and normally
    /// builds its body itself, from the vocabulary
    /// [`sid_spelling`](Self::sid_spelling) states. The default here is `None`,
    /// which says exactly that: *compose the derivation in my own SQL*.
    ///
    /// Answer with [`SidHelperBody`] only when there is no SQL that could hold
    /// the derivation — the engine has no 64-bit hash under any name, so the
    /// vocabulary has nothing to spell the hash with and the definition has to
    /// be written in another language. `BigQuery` is the case Razeri ships:
    /// `GoogleSQL` has no XXH64, and the function that looks like the answer
    /// (`FARM_FINGERPRINT`) is a different number, so the body is JavaScript.
    ///
    /// **Do not use this to change the key.** The body computes the same number
    /// every other engine computes — XXH64, seed 0, over the UTF-8 bytes of the
    /// one already-normalized argument — and [`SidHelperBody`] says what it owes
    /// in full. Reaching for a native hash that is merely deterministic keys a
    /// warehouse to numbers nothing outside it can reproduce.
    ///
    /// A dialect that answers here should also state a
    /// [`SidSpelling::hash`](crate::SidSpelling::hash) that no engine has, so
    /// that any path which fell back to composing SQL fails loudly at deploy
    /// time rather than hashing nothing and handing back the value.
    fn sid_helper_body(&self) -> Option<SidHelperBody> {
        None
    }

    /// **How this engine reads a delimited text file as a relation**, or `None`
    /// where it cannot.
    ///
    /// A design can bind an entity to a source file, and Razeri then generates
    /// the staging fill: an `INSERT … SELECT … FROM <this>`. That only works on
    /// an engine that can open a file from inside a query. `DuckDB` can
    /// (`read_csv_auto`); most cannot — `PostgreSQL` wants `COPY`, Snowflake a
    /// stage, `SQLite` has nothing at all. Each of those is a bulk-load design
    /// decision rather than a rendering detail, so the default is `None` and
    /// the generated bundle says which platform declined and why instead of
    /// emitting SQL the engine would refuse.
    ///
    /// `path_literal` arrives as a finished single-quoted SQL string literal,
    /// already escaped — put it where the relation takes a path and do not
    /// quote it again.
    ///
    /// **What the returned relation owes**, because the fill is written against
    /// it and nothing checks these at render time:
    ///
    /// - the file's first row is its header, and the column names come from it,
    ///   spelled exactly as the file spells them;
    /// - every column reads as **text**, unparsed. The fill casts nothing: a
    ///   date's layout and a currency's prefix are the source's business, and a
    ///   reader that guessed a type would fail the load on its first row;
    /// - it is a relation usable in a `FROM` clause, not a statement.
    ///
    /// The path is embedded in the generated file as it was spelled when the
    /// bundle was built, so it must be one the engine resolves at run time.
    fn delimited_file_relation(&self, path_literal: &str) -> Option<String> {
        let _ = path_literal;
        None
    }

    /// **The `CAST` target spelling for a [`DataType`] on this engine.**
    ///
    /// A column declaration and a `CAST` target are two grammars on most
    /// engines, so this is a separate answer from
    /// [`render_data_type`](Self::render_data_type) and not a synonym for it.
    /// `MySQL` takes `SIGNED` where it declares `BIGINT`; T-SQL takes
    /// `NVARCHAR(MAX)` where ANSI says `TEXT`.
    ///
    /// Where the two *are* the same on your engine — which is the common case
    /// on engines with one type vocabulary — say so by delegating:
    ///
    /// ```ignore
    /// fn render_cast_type(&self, dt: &DataType) -> String {
    ///     self.render_data_type(dt)
    /// }
    /// ```
    ///
    /// The default is ANSI's cast vocabulary. Razeri's generated load opens
    /// with a CTE that casts every source column to its declared type, so a
    /// wrong name here fails the load on its first statement.
    fn render_cast_type(&self, dt: &DataType) -> String {
        crate::agnostic::render_cast_type_ansi(dt)
    }

    /// **Which stored-procedure grammar this engine speaks.**
    ///
    /// Razeri composes the procedure — its parameters, its steps, its comment —
    /// and spells it in the form this returns. The default is
    /// [`ProcedureForm::Agnostic`], which parses on no engine: it is the honest
    /// answer for a dialect that has not said, and it is what an unlisted
    /// platform has always been handed.
    ///
    /// It lives on `SqlRenderer` rather than on
    /// [`ProcedureRenderer`] because the composer
    /// holds the renderer as a [`DdlRenderer`], and a decision reachable only
    /// through a trait the caller does not hold is a decision the caller makes
    /// instead.
    fn procedure_form(&self) -> ProcedureForm {
        ProcedureForm::Agnostic
    }

    /// **Which scalar-function grammar this engine speaks.**
    ///
    /// The default is [`ScalarFunctionForm::PostgreSql`] — what an unlisted
    /// dialect has always been handed, and a dangerous inheritance on a near
    /// neighbour: `LANGUAGE SQL IMMUTABLE PARALLEL SAFE` is a *"syntax error at
    /// or near `PARALLEL`"* on an engine that descends from `PostgreSQL` and
    /// reports itself as one.
    fn scalar_function_form(&self) -> ScalarFunctionForm {
        ScalarFunctionForm::PostgreSql
    }

    /// **Which table-valued-function grammar this engine speaks, and — where it
    /// has none — the words it refuses in.**
    ///
    /// The default is [`TableFunctionForm::PostgreSql`], what an unlisted
    /// dialect has always been handed. If your engine has no routine a query
    /// selects `FROM`, answer [`TableFunctionForm::Unsupported`] with your own
    /// sentence: Razeri then declines to build the routine at all and prints
    /// **your** words rather than another engine's. A refusal written once per
    /// artifact kind tells every author about whichever engine happened to need
    /// it first, and the near form an author will otherwise find on their own
    /// is exactly what costs them a day.
    fn table_function_form(&self) -> TableFunctionForm {
        TableFunctionForm::PostgreSql
    }

    // ═══════════════════════════════════════════════════════════════
    // Routines this dialect spells itself
    // ═══════════════════════════════════════════════════════════════

    /// **Spell a whole stored procedure in this engine's own grammar** — the
    /// method [`ProcedureForm::Custom`] promises.
    ///
    /// Razeri composes the routine and hands it over as a [`RoutineSpec`]: the
    /// name, the parameters with their types already in your spelling, the
    /// declarations, the body's statements, the comment. What comes back is the
    /// complete `CREATE`, punctuation and all, and Razeri emits it unchanged.
    ///
    /// The default is `None`, which means *"I did not write one"*. It is only
    /// ever reached by a dialect that answered
    /// [`ProcedureForm::Custom`] and then did not override this — the
    /// conformance kit reports that as blocking, and the emitted SQL carries a
    /// comment saying the same thing where the procedure would have been.
    ///
    /// It lives on `SqlRenderer` rather than on [`ProcedureRenderer`] for the
    /// reason [`Self::procedure_form`] does: the composer holds the renderer as
    /// a [`DdlRenderer`], and an answer reachable only through a trait the
    /// caller does not hold is an answer the caller makes up instead.
    ///
    /// Parameters:
    /// - `routine`: the procedure Razeri composed.
    fn render_procedure(&self, routine: &RoutineSpec) -> Option<String> {
        let _ = routine;
        None
    }

    /// **Spell a whole scalar function in this engine's own grammar** — the
    /// method [`ScalarFunctionForm::Custom`] promises.
    ///
    /// The same contract as [`Self::render_procedure`]: a composed
    /// [`RoutineSpec`] in, the complete `CREATE` out, and `None` only where a
    /// dialect claimed a custom grammar and did not write the method.
    ///
    /// Parameters:
    /// - `routine`: the function Razeri composed.
    fn render_scalar_function(&self, routine: &RoutineSpec) -> Option<String> {
        let _ = routine;
        None
    }

    /// **Spell a whole table-valued function in this engine's own grammar** —
    /// the method [`TableFunctionForm::Custom`] promises.
    ///
    /// The same contract as [`Self::render_procedure`]: a composed
    /// [`RoutineSpec`] in, the complete `CREATE` out, and `None` only where a
    /// dialect claimed a custom grammar and did not write the method.
    ///
    /// Parameters:
    /// - `routine`: the function Razeri composed.
    fn render_table_function(&self, routine: &RoutineSpec) -> Option<String> {
        let _ = routine;
        None
    }

    // ═══════════════════════════════════════════════════════════════
    // Expression rendering extensions
    // ═══════════════════════════════════════════════════════════════

    /// Platform's `CURRENT_DATE` expression.
    ///
    /// `SqlServer`: `CAST(GETDATE() AS DATE)`, `ClickHouse`: `today()`, others: `CURRENT_DATE`
    fn render_current_date(&self) -> String {
        "CURRENT_DATE".to_string()
    }

    /// Render a boolean literal.
    ///
    /// SqlServer/ClickHouse: `1`/`0`, others: `TRUE`/`FALSE`
    fn render_boolean_literal(&self, value: bool) -> String {
        if value { "TRUE".to_string() } else { "FALSE".to_string() }
    }

    /// **Collapse a subquery that selects AT MOST ONE ROW into an aggregate**,
    /// for the engines that will not accept an unaggregated correlated scalar.
    ///
    /// Razeri's SCD-2 and SCD-1 re-opens assign `col = (SELECT … WHERE
    /// {correlation})`. Databricks refuses that shape by name
    /// (`MUST_AGGREGATE_CORRELATED_SCALAR_SUBQUERY`) and Snowflake stopped
    /// unnesting it the day the guard beside it became uncorrelated, so the
    /// emission wraps the projection in an aggregate. **Which** aggregate is a
    /// dialect fact and **whether one exists at all** is a dialect × type fact,
    /// which is why this hook takes the kind and may answer `None`:
    ///
    /// - `MAX` is the obvious choice and is wrong for a BOOLEAN on two of the
    ///   platforms razeri reaches. Measured on the running
    ///   containers: `PostgreSQL` and Citus raise
    ///   *"function max(boolean) does not exist"*, SQL Server raises
    ///   *"Msg 8117: Operand data type bit is invalid for max operator"*, while
    ///   `MariaDB` (`MAX(TRUE)` → `1`) and `ClickHouse` (`max(true)` → `true`)
    ///   answer it happily;
    /// - `PostgreSQL` has no `max()` for `uuid`, `jsonb` or `bytea` either
    ///   (measured, same run), and SQL Server has one for both
    ///   `uniqueidentifier` and `varbinary` (measured).
    ///
    /// **`None` means *this dialect cannot aggregate this kind* and is not a
    /// failure.** The caller then emits the bare correlated scalar — the
    /// prior shape, measured green on the whole
    /// `PostgreSQL` family — and says so on the output, because that shape is
    /// the one Databricks refuses.
    ///
    /// **Correctness does not come from the aggregate's meaning.** The subquery
    /// is under a guard that is false for the entire load if any member
    /// disagrees with itself, so it selects one row; `MAX`, `BOOL_OR` and
    /// `BOOLOR_AGG` of one value are all that value. The choice between them is
    /// availability, not semantics.
    fn render_single_row_aggregate(
        &self,
        expression: &str,
        kind: AggregableKind,
    ) -> Option<String> {
        let _ = kind;
        Some(format!("MAX({expression})"))
    }

    /// **Take any one value of `expression` from a group**, for the engines
    /// that cannot group on the column itself.
    ///
    /// A load collapses staged rows that repeat. Where the engine will not
    /// group on a nested column
    /// ([`crate::DialectCapabilities::groups_nested_values`]) the collapse
    /// groups on the remaining columns and takes one value of that one, which
    /// is what this renders.
    ///
    /// `ANY_VALUE` is the spelling `BigQuery`, Snowflake, Redshift, Databricks
    /// and `MySQL` all use, so it is the default; an engine that spells it
    /// differently, or reaches it through `FIRST`, says so here.
    ///
    /// Unlike [`Self::render_single_row_aggregate`] this one cannot decline:
    /// it is asked only where the dialect has already said it cannot group on
    /// the column, so there is no second shape to fall back to.
    ///
    /// Parameters:
    /// - `expression`: the column reference, already spelled by the renderer
    ///   that lays out the query.
    fn render_any_value(&self, expression: &str) -> String {
        format!("ANY_VALUE({expression})")
    }

    /// **The AGGREGATE median this engine has for `expression`, or `None` when
    /// it has none.**
    ///
    /// Aggregate is the load-bearing word, and it is why this cannot be
    /// answered from a function-name table. Four spellings are in the wild:
    ///
    /// - a plain `median(x)` aggregate — `duckdb`, `clickhouse`, `snowflake`;
    /// - the SQL ordered-set aggregate
    ///   `PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY x)` — `postgres` and its
    ///   family (measured on a running instance: it groups);
    /// - a two-argument `PERCENTILE(x, 0.5)` — `databricks`;
    /// - and a WINDOW function wearing one of those names, which is **not**
    ///   this. `mariadb` has `MEDIAN(x) OVER (…)` and `sqlserver` has
    ///   `PERCENTILE_CONT(…) OVER (…)`, and both are a syntax error in a
    ///   `GROUP BY` select list (measured: `MariaDB` raises `ERROR 1064` and
    ///   SQL Server raises *"Msg 10753: The function `PERCENTILE_CONT` must
    ///   have an OVER clause"*). A window function returns one value per ROW,
    ///   not one per group, so it is a different answer and not a fallback.
    ///
    /// **The default declines**, so a dialect that has never been asked the
    /// question is never assumed to have the answer, and a dialect added
    /// tomorrow opts in deliberately with a form somebody measured. The caller
    /// turns `None` into a build-time refusal naming the column and the target
    /// — razeri does not emit SQL its target cannot run.
    ///
    /// # Why a TEMPLATE rather than finished SQL
    ///
    /// The aggregated expression is a column reference, and how a column
    /// reference is spelled — quoted, bracketed, upper-cased — belongs to the
    /// renderer that lays out the query, not to this answer. Handing back a
    /// form with [`AGGREGATE_ARGUMENT`] where the expression goes keeps the
    /// two apart: this trait owns *which function*, the query renderer owns
    /// *how the column is written*, and neither has to reimplement the other.
    fn median_aggregate_form(&self) -> Option<&'static str> {
        None
    }

    /// Render a date literal.
    ///
    /// `ClickHouse`: `toDate('2024-01-15')`, others: `DATE '2024-01-15'`
    fn render_date_literal(&self, date: &str) -> String {
        format!("DATE '{date}'")
    }

    /// Render a timestamp literal.
    ///
    /// `ClickHouse`: `toDateTime('...')`, others: `TIMESTAMP '...'`
    fn render_timestamp_literal(&self, ts: &str) -> String {
        format!("TIMESTAMP '{ts}'")
    }

    /// Render an interval literal.
    ///
    /// `SqlServer`: `'P1Y2M3D'`, `ClickHouse`: `INTERVAL 1 YEAR`, others: `INTERVAL '1 year'`
    fn render_interval_literal(&self, interval: &str) -> String {
        format!("INTERVAL '{interval}'")
    }

    /// Render the string concatenation operator.
    ///
    /// `SqlServer`: `+`, others: `||`
    fn concat_operator(&self) -> &'static str {
        "||"
    }

    /// Render a NaN literal for a floating-point type.
    ///
    /// `PostgreSQL`: `'NaN'::float`, others: `NULL`
    fn render_nan_literal(&self, _dt: &DataType) -> String {
        "NULL".to_string()
    }

    /// Render an infinity literal for a floating-point type.
    ///
    /// `PostgreSQL`: `'Infinity'::float` / `'-Infinity'::float`, others: `NULL`
    fn render_infinity_literal(&self, _positive: bool, _dt: &DataType) -> String {
        "NULL".to_string()
    }

    /// Render the NULL-coalescing function name.
    ///
    /// `SqlServer`: `ISNULL`, `ClickHouse`: `ifNull`, others: `COALESCE`
    fn ifnull_function_name(&self) -> &'static str {
        "COALESCE"
    }

    /// Render an IIF expression (or CASE WHEN equivalent).
    ///
    /// `SqlServer`: `IIF(cond, then, else)`, others: `CASE WHEN cond THEN then ELSE else END`
    fn render_iif(&self, cond: &str, then_val: &str, else_val: &str) -> String {
        format!("CASE WHEN {cond} THEN {then_val} ELSE {else_val} END")
    }

    /// Render a `DATE_TRUNC` expression.
    ///
    /// `SqlServer`: `DATETRUNC(field, expr)`, `ClickHouse`: `toStartOfMonth(expr)`, others: `DATE_TRUNC('field', expr)`
    fn render_date_trunc(&self, field: &str, expr: &str) -> String {
        format!("DATE_TRUNC('{field}', {expr})")
    }

    /// Render a date field extraction expression.
    ///
    /// `SqlServer`: `DATEPART(field, column)`, `ClickHouse`: `toYear(col)/toMonth(col)`, others: `EXTRACT(field FROM column)`
    fn render_date_extract(&self, field: &str, column: &str) -> String {
        format!("EXTRACT({field} FROM {column})")
    }

    /// Render a `TRY_CAST` expression.
    ///
    /// `ClickHouse`: `accurateCastOrNull(expr, 'Type')`, others: `TRY_CAST(expr AS Type)`
    fn render_try_cast(&self, expr: &str, target: &DataType) -> String {
        format!("TRY_CAST({} AS {})", expr, self.render_data_type(target))
    }

    /// Render a positional parameter placeholder.
    ///
    /// `PostgreSQL`: `$1`, `SqlServer`: `@p1`, Databricks: `{param1}`, others: `?`
    fn render_parameter_placeholder(&self, index: usize) -> String {
        format!("${index}")
    }

    /// Render a named parameter placeholder.
    ///
    /// `SqlServer`: `@name`, `PostgreSQL`: `:name`, Databricks: `{name}`
    fn render_named_parameter(&self, name: &str) -> String {
        format!(":{name}")
    }

    /// Keyword emitted for MERGE NOT MATCHED branch.
    ///
    /// SqlServer/Databricks: `WHEN NOT MATCHED BY TARGET`, others: `WHEN NOT MATCHED`.
    fn merge_not_matched_keyword(&self) -> &'static str {
        "WHEN NOT MATCHED"
    }

    /// Whether MERGE supports `WHEN NOT MATCHED BY SOURCE`.
    fn supports_merge_not_matched_by_source(&self) -> bool {
        false
    }

    /// Whether this platform takes a `MERGE` statement.
    ///
    /// **This is `DialectCapabilities::merge_shape().merges()`, restated where
    /// only a `SqlRenderer` is in hand** — the standalone `MergeStatement`
    /// builder takes this trait alone and cannot ask the capability surface.
    /// The two must answer identically; the capability/renderer consistency
    /// gate holds them to equality with no exceptions, so a dialect that
    /// overrides one and not the other is refused before it ships. An engine
    /// whose shape is an upsert statement, an engine-deduplicated insert, or a
    /// refusal answers `false` here.
    fn merge_supported(&self) -> bool {
        true
    }

    /// Whether `WITH SCHEMA EVOLUTION` is supported for MERGE.
    fn merge_supports_schema_evolution_keyword(&self) -> bool {
        false
    }

    /// Whether table hints are supported in MERGE target.
    fn merge_supports_table_hints(&self) -> bool {
        false
    }

    /// Whether OUTPUT clause should be used for MERGE result projection.
    fn merge_uses_output_clause(&self) -> bool {
        false
    }

    /// Whether RETURNING clause is supported for MERGE.
    fn merge_supports_returning_clause(&self) -> bool {
        false
    }

    /// **Whether this engine lets a `MERGE` target carry an alias.**
    ///
    /// Most do, and the composed load addresses the target through a short
    /// `tgt`. An engine that answers `false` gets the target's own qualified
    /// name in every position the alias would have stood — dropping the
    /// qualifier instead makes the shared column names ambiguous.
    fn merge_target_accepts_alias(&self) -> bool {
        true
    }

    /// **Whether this engine refuses a `WITH` clause in front of `MERGE`.**
    ///
    /// The composed load types its staging rows in one common table expression
    /// and hashes them in a second. Where a leading `WITH` parses, the two sit
    /// in front of the statement and the source is the second one by name.
    /// Where it does not, the same two move inside the `USING` subquery, which
    /// is the same query in a position the grammar accepts.
    ///
    /// Answer `true` if `WITH … MERGE INTO …` is a syntax error on your engine.
    fn merge_source_requires_inlined_ctes(&self) -> bool {
        false
    }

    /// **Whether a `WITH` clause parses in front of this engine's `INSERT`.**
    ///
    /// A load that writes rows without matching them — one slice replaced, or
    /// rows appended — types its staging rows in one common table expression
    /// and hashes them in a second, exactly as the matching load does. Most
    /// engines take those two inside the statement, after the column list and
    /// in front of the `SELECT`, which is where Razeri puts them by default.
    ///
    /// Answer `true` where the same two have to lead instead, because the
    /// engine reads a `WITH` after a table name as something else entirely:
    /// T-SQL parses it as a table hint and rejects the statement. Nothing here
    /// changes the query — only where the engine will accept it written down.
    fn insert_accepts_leading_ctes(&self) -> bool {
        false
    }

    /// **Whether this engine can be given a function by `CREATE FUNCTION`.**
    ///
    /// Razeri derives a surrogate key through a small emitted function, and an
    /// engine whose SQL surface has no `CREATE FUNCTION` at all can never
    /// receive it — the definition has to come from application code instead.
    /// Such an engine gets no emitted helper and no per-entity key function,
    /// and its dialect states the substitute in its own words.
    ///
    /// This is about the **grammar**, not about who owns the name: an engine
    /// that can define functions but takes its key function from an installed
    /// artifact still answers `true` here.
    fn supports_sql_function_ddl(&self) -> bool {
        true
    }

    /// **Whether a scalar function's body is a bare expression.**
    ///
    /// Most engines want a full `SELECT` in front of the value a function
    /// returns. Some take the expression alone and reject the `SELECT`.
    fn scalar_function_body_is_expression(&self) -> bool {
        false
    }

    /// **Whether a scalar function belongs to a schema.**
    ///
    /// On most engines a function lives in a schema and both its definition and
    /// its call sites name it. On an engine that answers `false`, functions are
    /// server-global: `CREATE FUNCTION` takes no qualifier, and a qualified
    /// call names a function that does not exist.
    fn scalar_function_names_are_schema_qualified(&self) -> bool {
        true
    }

    /// **Whether an unqualified scalar-function call resolves.**
    ///
    /// Most engines resolve a bare function name through a search path. An
    /// engine that answers `true` resolves none, so a call with no schema in
    /// front of it has to be given one — [`DialectCapabilities::default_schema`]
    /// is the
    /// schema the function was created in when the caller named none.
    ///
    /// [`DialectCapabilities::default_schema`]: crate::DialectCapabilities::default_schema
    fn scalar_function_call_requires_schema(&self) -> bool {
        false
    }

    /// **How this engine invokes a stored procedure**, as a whole statement.
    ///
    /// The composed load calls its own identity step, and a deploy script that
    /// has no procedures at all has to recognise these calls in order to inline
    /// what they would have run — so the call is spelled once, here.
    fn render_procedure_call(&self, qualified_name: &str) -> String {
        format!("CALL {qualified_name}();")
    }

    /// The schema separator for qualified names.
    ///
    /// Almost always `.`, but could differ for some platforms.
    fn schema_separator(&self) -> &'static str {
        "."
    }

    /// The statement separator for scripts.
    ///
    /// Almost all platforms: `;\n`, `SqlServer`: `;\nGO\n`
    fn statement_separator(&self) -> &'static str {
        ";\n"
    }

    // ═══════════════════════════════════════════════════════════════
    // UPDATE behavior hooks
    // ═══════════════════════════════════════════════════════════════

    /// Whether the platform supports compound assignment operators (e.g., `col += value`).
    ///
    /// `SqlServer`: `true`, others: `false`.
    fn supports_compound_assignment(&self) -> bool {
        false
    }

    /// Whether UPDATE supports FROM clause for join-based updates.
    ///
    /// `PostgreSQL`, `SqlServer`, Snowflake, `CitusDB`: `true`, others: `false`.
    fn supports_update_from(&self) -> bool {
        false
    }

    /// Whether the platform uses ALTER TABLE ... UPDATE syntax (`ClickHouse` mutations).
    fn uses_alter_table_update(&self) -> bool {
        false
    }

    /// **Whether a mutation on this platform can read only the row it is
    /// mutating.**
    ///
    /// `uses_alter_table_update` above says how the mutation is SPELLED; this
    /// says what the mutation may LOOK AT, and the two are independent facts
    /// that happen to be true of the same engine today. A platform answering
    /// `true` here cannot express *assign this column from another relation*
    /// at all: neither the `SET` list nor the `WHERE` may correlate out to a
    /// second table, so no re-spelling of a correlated `UPDATE` compiles —
    /// what is available instead is `INSERT … SELECT` over a join and a
    /// mutation whose predicate is an uncorrelated `IN`.
    ///
    /// **Measured, and it is the reason the seam exists.** `ClickHouse`
    /// 24.10.2 (2026-08-23) answered razeri's emitted re-open with
    /// `Code: 47 … UNKNOWN_IDENTIFIER` while resolving the assignment's own
    /// subquery — after the statement PARSED, which is what made the
    /// distinction visible: the syntax was right and the reach was not.
    ///
    /// It sits here on [`SqlRenderer`] and **only** here, deliberately not
    /// duplicated onto `DialectCapabilities`: `SqlRenderer` is the trait
    /// razeri's generators call, so this is the definition that decides, and a
    /// second declaration of the same fact is one that can drift.
    ///
    /// Default `false`: every engine razeri reaches except `ClickHouse` lets a
    /// mutation correlate, and the ANSI correlated `UPDATE` those nine compile
    /// is unchanged by this flag existing.
    fn mutation_reads_only_its_own_rows(&self) -> bool {
        false
    }

    /// **The spelling a SQL statement inside a generated procedure body reads
    /// a declared local variable by.**
    ///
    /// A versioning load binds its clock ONCE — a `Declare` step at the top of
    /// the procedure — and every close and every open reads the variable
    /// instead of the engine's clock, so there is no daylight between the
    /// close of one version and the open of the next. The DECLARATION is the
    /// procedure renderer's business; what the load generators need is the
    /// reference spelling to embed in the raw statements they compose, and
    /// that differs by procedure language:
    ///
    /// - bare `name` — PL/pgSQL, MySQL/MariaDB, and the default;
    /// - `@name` — T-SQL;
    /// - `:name` — Snowflake Scripting's bind syntax inside SQL statements;
    /// - `$name` — the agnostic format's marker.
    ///
    /// It mirrors the variable-reference spelling of Razeri's own procedure
    /// renderers — the two must agree, and each override says so beside the
    /// spelling.
    fn render_procedure_variable_reference(&self, name: &str) -> String {
        name.to_owned()
    }

    /// **The statement that binds one query's answer to a declared local.**
    ///
    /// A procedure body asks a question — how many rows arrived, what the
    /// latest timestamp is — and keeps the answer in a variable the rest of the
    /// body reads. Every procedural language has that statement and no two
    /// spell it alike:
    ///
    /// - `SELECT COUNT(*) FROM stage INTO v_seen;` — PL/pgSQL;
    /// - `SELECT @v_seen = (SELECT COUNT(*) FROM stage);` — T-SQL;
    /// - `v_seen := (SELECT COUNT(*) FROM stage);` — Snowflake Scripting;
    /// - `EXECUTE IMMEDIATE 'SELECT COUNT(*) FROM stage' INTO v_seen;` —
    ///   Oracle's PL/SQL.
    ///
    /// `query` is the question, already carrying this dialect's variable
    /// spelling and with no trailing terminator; `variable` is the bare name of
    /// the local, so a grammar that wants the reference spelling asks
    /// [`Self::render_procedure_variable_reference`] for it and one that wants
    /// the bare name has it already. The answer is a whole statement,
    /// terminator included.
    ///
    /// The default names the query and the target in a form that belongs to no
    /// engine, because there is no spelling every engine shares. A dialect
    /// rendering its own routine grammar answers this and the body arrives
    /// ready to compile.
    fn render_procedure_query_into_variable(&self, variable: &str, query: &str) -> String {
        format!("EXECUTE {query} INTO {};", self.render_procedure_variable_reference(variable))
    }

    /// **The statement that stops a procedure body with an error of its own.**
    ///
    /// A generated load checks what it was given and refuses to go on when the
    /// answer is wrong. Every procedural language can stop that way and no two
    /// write it alike:
    ///
    /// - `RAISE EXCEPTION '%', 'the run brought no rows';` — PL/pgSQL;
    /// - `THROW 50000, 'the run brought no rows', 1;` — T-SQL;
    /// - `SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'the run brought no rows';`
    ///   — `MySQL` and `MariaDB`;
    /// - `RAISE_APPLICATION_ERROR(-20001, 'the run brought no rows');` —
    ///   Oracle's PL/SQL.
    ///
    /// `message` is the message **already rendered as a SQL expression in this
    /// dialect's spelling**: a literal arrives quoted and escaped, and a
    /// variable arrives named the way
    /// [`Self::render_procedure_variable_reference`] names one, because a body
    /// may raise what it read rather than what it was written with. Put it
    /// where the statement wants it and do not quote it again. `error_code` is
    /// the number the design gave, if it gave one; an engine whose statement
    /// takes a number supplies its own when this is `None`. The answer is a
    /// whole statement, terminator included.
    ///
    /// The default names the raise in a form that belongs to no engine. A
    /// dialect rendering its own routine grammar answers this and the body
    /// arrives ready to compile.
    fn render_procedure_raise(&self, message: &str, error_code: Option<i32>) -> String {
        match error_code {
            Some(code) => format!("RAISE EXCEPTION [{code}] {message};"),
            None => format!("RAISE EXCEPTION {message};"),
        }
    }

    /// **The statement that writes a message where an operator can read it.**
    ///
    /// A load says how it is going, and where that message goes is an engine's
    /// own business — a client notice, a print stream, an event table, a
    /// result set nobody reads:
    ///
    /// - `RAISE NOTICE '%', 'loaded';` — PL/pgSQL;
    /// - `PRINT 'loaded';` — T-SQL;
    /// - `SYSTEM$LOG('INFO', 'loaded');` — Snowflake Scripting;
    /// - `DBMS_OUTPUT.PUT_LINE('loaded');` — Oracle's PL/SQL, which has no
    ///   levels and ignores the one it is given.
    ///
    /// `message` arrives the same way [`Self::render_procedure_raise`] takes
    /// it: already a SQL expression in this dialect's spelling, quoted where it
    /// is a literal. `level` is the severity the design wrote; an engine whose
    /// statement carries one reads
    /// [`ProcedureLogLevel::as_str`] and spells it the way that statement
    /// wants. The answer is a whole statement, terminator included.
    ///
    /// The default names the level and the message in a form that belongs to no
    /// engine. A dialect rendering its own routine grammar answers this and the
    /// body arrives ready to compile.
    fn render_procedure_log(&self, level: ProcedureLogLevel, message: &str) -> String {
        let word = match level {
            ProcedureLogLevel::Debug => "DEBUG",
            ProcedureLogLevel::Info => "NOTICE",
            ProcedureLogLevel::Warning => "WARNING",
            ProcedureLogLevel::Error => "EXCEPTION",
        };
        format!("LOG {word} {message};")
    }

    /// **The statement a generated load asks a scalar question with and throws
    /// the answer away.**
    ///
    /// A load's guard evaluates one scalar and reads nothing back: it either
    /// passes silently or stops the load on the engine's own error. What
    /// differs between engines is not the question but the STATEMENT that may
    /// carry it, and the difference is a procedure-language rule rather than a
    /// SQL one:
    ///
    /// - a bare `SELECT` is a legal script statement everywhere, and is legal
    ///   inside the procedure bodies `MySQL`, `MariaDB` and T-SQL accept, where it
    ///   simply hands the caller a result set nobody reads — so that is the
    ///   default;
    /// - **PL/pgSQL refuses it.** A `SELECT` with no destination inside a
    ///   procedure body is `query has no destination for result data`, raised
    ///   the moment the procedure is called. PL/pgSQL's own discard form is
    ///   `PERFORM`, and the Postgres family overrides this to spell it.
    ///
    /// The engines that ship no stored procedure inline the same statement into
    /// a script, where the default is the only form that runs — and every such
    /// engine takes the default, so one answer per dialect is unambiguous.
    ///
    /// `alias` names the answered column for the forms that answer one; a
    /// discard form that answers nothing ignores it.
    fn render_discarded_scalar(&self, expression: &str, alias: &str) -> String {
        format!("SELECT {expression} AS {alias};")
    }

    /// **How a script with no stored procedures binds the load's clock once**
    /// — same rule as [`Self::render_procedure_variable_reference`], on the
    /// engines where a load ships as a flat statement list rather than a
    /// procedure body.
    ///
    /// The statements run FIRST and bind the engine's current moment to
    /// `name`; the reference is the expression every close and open in the
    /// same run then reads, so a version's `record_end_timestamp` and its
    /// successor's `record_start_timestamp` are one value by construction.
    /// Every spelling must be RE-RUNNABLE in one session — a second load in
    /// the same session rebinds rather than failing — because a load script is
    /// run whole and run again.
    ///
    /// The default is the one shape every engine can carry: a one-row
    /// temporary table capturing [`Self::render_current_timestamp`], read back
    /// through a scalar subquery. Engines with a native variable idiom
    /// override it (`DuckDB`'s `SET VARIABLE`, Databricks' session variables);
    /// `ClickHouse` overrides only the temporary-table spelling its own DDL
    /// requires.
    fn render_inline_clock_binding(&self, name: &str) -> InlineClockBinding {
        InlineClockBinding {
            statements: vec![
                format!("DROP TABLE IF EXISTS {name};"),
                format!(
                    "CREATE TEMPORARY TABLE {name} AS SELECT {} AS load_clock;",
                    self.render_current_timestamp()
                ),
            ],
            reference: format!("(SELECT load_clock FROM {name})"),
        }
    }

    /// Whether UPDATE supports TOP(n) clause (`SqlServer`).
    fn update_supports_top_clause(&self) -> bool {
        false
    }

    /// Whether UPDATE supports table hints (e.g., `WITH (NOLOCK)`) (`SqlServer`).
    fn update_supports_table_hints(&self) -> bool {
        false
    }

    /// Whether UPDATE uses OUTPUT clause positioned before FROM (`SqlServer`).
    ///
    /// When `true`, RETURNING/OUTPUT is rendered between SET and FROM.
    /// When `false`, RETURNING is rendered at the end of the statement.
    fn update_uses_output_clause(&self) -> bool {
        false
    }

    /// Whether UPDATE supports a RETURNING clause at the end of the statement.
    ///
    /// `PostgreSQL`, `CitusDB`: `true`. Others: `false`.
    fn update_supports_returning(&self) -> bool {
        false
    }

    // ========================================================================
    // INSERT behavior hooks
    // ========================================================================

    /// Whether INSERT uses OUTPUT clause positioned before VALUES/SELECT (`SqlServer`).
    ///
    /// When `true`, RETURNING/OUTPUT is rendered between column list and source.
    /// When `false`, RETURNING is rendered at the end of the statement.
    fn insert_uses_output_clause(&self) -> bool {
        false
    }

    /// Whether INSERT supports RETURNING at the end (`PostgreSQL`, `CitusDB`).
    fn insert_supports_returning(&self) -> bool {
        false
    }

    /// Whether INSERT supports table hints (e.g., `WITH (TABLOCK)`) (`SqlServer`).
    fn insert_supports_table_hints(&self) -> bool {
        false
    }

    /// Whether INSERT OVERWRITE is supported (Snowflake, Databricks).
    fn supports_insert_overwrite(&self) -> bool {
        false
    }

    /// Whether INSERT ... ON CONFLICT is supported (`PostgreSQL`, `CitusDB`).
    fn supports_on_conflict(&self) -> bool {
        false
    }

    /// Whether OVERRIDING SYSTEM/USER VALUE clause is supported (`PostgreSQL`).
    fn supports_overriding_clause(&self) -> bool {
        false
    }

    /// The keyword for returning data from DML: "OUTPUT" (`SqlServer`) or "RETURNING" (others).
    fn returning_clause_keyword(&self) -> &'static str {
        "RETURNING"
    }

    /// Whether OUTPUT ... INTO is supported (`SqlServer`).
    fn supports_returning_into(&self) -> bool {
        false
    }

    /// Whether multi-table INSERT (INSERT ALL) is supported (Snowflake).
    fn supports_multi_table_insert(&self) -> bool {
        false
    }

    // ========================================================================
    // Function/procedure parameter behavior hooks
    // ========================================================================

    /// Render the security mode clause for function/procedure definitions.
    ///
    /// Standard SQL: `SECURITY INVOKER`/`SECURITY DEFINER`.
    /// T-SQL: `EXECUTE AS CALLER`/`EXECUTE AS OWNER`.
    fn render_security_mode(&self, is_definer: bool) -> &'static str {
        if is_definer { "SECURITY DEFINER" } else { "SECURITY INVOKER" }
    }

    /// Render a function parameter name.
    ///
    /// Standard SQL uses the bare name. T-SQL prefixes with `@`.
    fn render_function_parameter_name(&self, name: &str) -> String {
        name.to_string()
    }

    /// Render explicit nullability for a function parameter, if the platform requires it.
    ///
    /// Most platforms omit nullability in parameter lists. T-SQL native
    /// compilation requires explicit `NULL`/`NOT NULL`.
    fn render_function_parameter_nullable(&self, _nullable: bool) -> Option<&'static str> {
        None
    }

    /// Render the default-value clause for a function parameter.
    ///
    /// Standard SQL: `DEFAULT value`. T-SQL: `= value`.
    fn render_function_parameter_default(&self, value: &str) -> String {
        format!("DEFAULT {value}")
    }

    /// Render a column name inside a table-valued function definition.
    ///
    /// Standard SQL uses the bare name. T-SQL uses bracket quoting `[name]`.
    fn render_function_column_name(&self, name: &str) -> String {
        name.to_string()
    }

    // ========================================================================
    // Partition & generated column rendering hooks
    // ========================================================================

    /// Render a time partition expression for a column and granularity.
    ///
    /// Granularity values: `"hourly"`, `"daily"`, `"weekly"`, `"monthly"`,
    /// `"quarterly"`, `"yearly"`.
    ///
    /// Default: `date_trunc('unit', column)` (ANSI / `PostgreSQL` style),
    /// mapping granularity names to `date_trunc` units.
    fn render_time_partition_expr(&self, column: &str, granularity: &str) -> String {
        let unit = match granularity {
            "hourly" => "hour",
            "daily" => "day",
            "weekly" => "week",
            "monthly" => "month",
            "quarterly" => "quarter",
            "yearly" => "year",
            other => other,
        };
        format!("date_trunc('{unit}', {column})")
    }

    /// Render a DDL partition clause wrapping the expression list.
    ///
    /// Default: `PARTITION BY (expr)`. Snowflake: `CLUSTER BY (expr)`,
    /// Databricks: `PARTITIONED BY (expr)`, `ClickHouse`: `PARTITION BY expr` (no parens).
    fn render_partition_clause(&self, expr: &str) -> String {
        format!("PARTITION BY ({expr})")
    }

    /// Render a generated column declaration.
    ///
    /// Default: `name GENERATED ALWAYS AS (expr) STORED` (`PostgreSQL` style).
    fn render_generated_column(&self, name: &str, expr: &str) -> String {
        format!("{name} GENERATED ALWAYS AS ({expr}) STORED")
    }

    // ========================================================================
    // Window function capability hooks
    // ========================================================================

    /// Whether the platform supports the EXCLUDE clause in window frame specifications.
    ///
    /// `PostgreSQL`, Snowflake, Databricks: `true`. Others: `false`.
    fn supports_window_frame_exclude(&self) -> bool {
        false
    }

    /// Whether the platform supports the GROUPS frame mode in window functions.
    ///
    /// `PostgreSQL`, Databricks: `true`. Others: `false`.
    fn supports_window_frame_groups(&self) -> bool {
        false
    }

    /// Whether the platform supports named windows (WINDOW clause).
    ///
    /// Most platforms: `true`. `ClickHouse`, `DuckDB`, `MariaDB`: `false`.
    fn supports_named_windows(&self) -> bool {
        true
    }

    // ========================================================================
    // DDL table-scope capability hooks
    // ========================================================================

    /// Whether the platform uses a `#` prefix for session-scoped temporary table names.
    ///
    /// SQL Server: `true`. Others: `false`.
    fn uses_hash_temp_table_prefix(&self) -> bool {
        false
    }

    /// Whether the platform supports `DECLARE @name TABLE (...)` table variables.
    ///
    /// SQL Server: `true`. Others: `false`.
    fn supports_table_variables(&self) -> bool {
        false
    }

    /// The full CREATE keyword for session-scoped temporary tables.
    ///
    /// Default: `"CREATE TEMPORARY"`.
    /// SQL Server: `"CREATE"` (uses `#name` instead of TEMPORARY keyword).
    /// Databricks: `"CREATE OR REPLACE TEMPORARY"`.
    fn render_create_temp_table_keyword(&self) -> &'static str {
        "CREATE TEMPORARY"
    }

    /// Whether the platform supports transient tables (e.g. `CREATE TRANSIENT TABLE`).
    ///
    /// Snowflake: `true`. Others: `false`.
    fn supports_transient_tables(&self) -> bool {
        false
    }

    /// Whether the platform supports `ON COMMIT DROP` for transaction-scoped temp tables.
    ///
    /// `PostgreSQL`, `CitusDB`: `true`. Others: `false`.
    fn supports_on_commit_drop(&self) -> bool {
        false
    }

    /// Whether the platform requires an `ENGINE = ...` clause on CREATE TABLE.
    ///
    /// `ClickHouse`: `true`. Others: `false`.
    ///
    /// A platform that answers `true` owns its whole engine suffix in ONE place:
    /// the `CREATE TABLE` composer emits the engine, then the sorting key, then
    /// whatever the resolved storage plan contributes. A storage renderer for
    /// such a platform must therefore contribute NEITHER an engine clause nor a
    /// sorting key — two engine clauses is `Code: 62 … Syntax error`, and a
    /// sorting key that disagrees with the inline `PRIMARY KEY` is
    /// `Code: 36 … Primary key must be a prefix of the sorting key` (both
    /// measured on `ClickHouse` 24.10.2).
    fn requires_table_engine(&self) -> bool {
        false
    }

    /// Whether this platform's table sorting key refuses nullable columns.
    ///
    /// `ClickHouse`: `true` — a `MergeTree` sorting key containing a
    /// `Nullable(…)` column answers `Code: 44 … Sorting key contains nullable
    /// columns, but merge tree setting allow_nullable_key is disabled`, measured
    /// on 24.10.2 against the control (the same key over a non-nullable column
    /// of the same type is accepted). Others: `false`.
    ///
    /// The materializer asks this before it lets a design's clustering columns
    /// into a sorting key, so the answer is a refusal the author can act on
    /// rather than a deployment failure they cannot.
    fn sorting_key_refuses_nullable_columns(&self) -> bool {
        false
    }

    /// Whether the platform requires a primary key on every table.
    ///
    /// `ClickHouse` (MergeTree): `true`. Others: `false`.
    fn requires_primary_key_in_create_table(&self) -> bool {
        false
    }

    /// Create a boxed [`FormulaRenderer`](crate::FormulaRenderer) for this dialect.
    ///
    /// Real dialect implementations override this to return `Box::new(Self)`.
    /// The default returns an ANSI dialect with standard function names.
    fn to_formula_renderer(&self) -> Box<dyn crate::FormulaRenderer> {
        Box::new(crate::AnsiDialect)
    }
}

/// Level 2 — Expression rendering with ANSI SQL defaults.
pub trait ExpressionRenderer: SqlRenderer {
    /// **Render a conversion of `expr` to `target`** — the expression the
    /// generated load's typed projection writes for every column.
    ///
    /// The default is `CAST(expr AS …)` over
    /// [`render_cast_type`](SqlRenderer::render_cast_type), the cast vocabulary
    /// rather than the column vocabulary: a column may be declared `STRING(36)`
    /// where a cast may name only `STRING`, and `TINYINT` where a cast must say
    /// `SMALLINT`. Override it where a conversion is not a `CAST` at all —
    /// `GoogleSQL` has no cast from `STRING` to `JSON` ("Invalid cast from
    /// STRING to JSON") and converts with `PARSE_JSON(expr)` instead.
    fn render_cast(&self, expr: &str, target: &DataType) -> String {
        format!("CAST({} AS {})", expr, self.render_cast_type(target))
    }

    /// Render string concatenation.
    fn render_concat(&self, parts: &[String]) -> String {
        format!("CONCAT({})", parts.join(", "))
    }

    /// Render a COALESCE expression.
    fn render_coalesce(&self, parts: &[String]) -> String {
        format!("COALESCE({})", parts.join(", "))
    }

    /// Render a string aggregation function.
    fn render_string_agg(&self, expr: &str, separator: &str) -> String {
        format!("STRING_AGG({expr}, '{separator}')")
    }
}

/// A foreign key's referential action — SQL's own five words, no synonyms.
///
/// Lives here (rather than in the table model) so a dialect can answer
/// [`DdlRenderer::supports_foreign_key_action`] about a specific action
/// without depending on the modeling crate.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ReferentialAction {
    /// Also delete or update the referencing rows
    Cascade,
    /// Set the referencing columns to NULL
    SetNull,
    /// Reject the delete or update; some engines defer the check
    Restrict,
    /// Reject the delete or update (the SQL default)
    NoAction,
    /// Set the referencing columns to their default values
    SetDefault,
}

impl ReferentialAction {
    /// Parses the SQL words, case-insensitively; underscores read as spaces
    /// so `set_null` and `SET NULL` both land.
    ///
    /// # Errors
    /// Returns a plain message listing the valid words when the input is not
    /// one of them.
    pub fn from_sql_word(word: &str) -> Result<Self, String> {
        match word.trim().replace('_', " ").to_uppercase().as_str() {
            "CASCADE" => Ok(Self::Cascade),
            "SET NULL" => Ok(Self::SetNull),
            "RESTRICT" => Ok(Self::Restrict),
            "NO ACTION" => Ok(Self::NoAction),
            "SET DEFAULT" => Ok(Self::SetDefault),
            _ => Err(format!(
                "'{word}' is not a referential action. Use one of: CASCADE, SET NULL, \
                 RESTRICT, NO ACTION, SET DEFAULT."
            )),
        }
    }
}

impl std::fmt::Display for ReferentialAction {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Cascade => write!(f, "CASCADE"),
            Self::SetNull => write!(f, "SET NULL"),
            Self::Restrict => write!(f, "RESTRICT"),
            Self::NoAction => write!(f, "NO ACTION"),
            Self::SetDefault => write!(f, "SET DEFAULT"),
        }
    }
}

/// Level 3 — DDL rendering with reasonable defaults.
pub trait DdlRenderer: SqlRenderer {
    /// Prefix for CREATE TABLE statements.
    fn render_create_table_prefix(&self) -> &'static str {
        "CREATE TABLE"
    }

    /// Whether this engine carries the given foreign-key referential action
    /// (`ON DELETE …` / `ON UPDATE …`) in `CREATE TABLE` DDL.
    ///
    /// The ANSI default says yes to all five words. A dialect answers `false`
    /// for an action its engine rejects or silently never enforces; the
    /// renderer then keeps the author's declaration visible as a plain
    /// comment instead of emitting a clause the engine would refuse — a
    /// declared action never vanishes without a trace.
    fn supports_foreign_key_action(&self, action: ReferentialAction) -> bool {
        let _ = action;
        true
    }

    /// Prefix for CREATE VIEW statements.
    fn render_create_view_prefix(&self) -> &'static str {
        "CREATE OR REPLACE VIEW"
    }

    /// Render a column definition (name, type, nullability).
    fn render_column_definition(&self, name: &str, dt: &DataType, nullable: bool) -> String {
        let quoted = self.quote_identifier(name);
        let (type_str, null_str) = if nullable {
            (self.render_nullable_data_type(dt), "")
        } else {
            (self.render_data_type(dt), " NOT NULL")
        };
        format!("{quoted} {type_str}{null_str}")
    }

    /// **The statement this engine takes for one change to a table that
    /// already holds rows**, or `None` where it has none.
    ///
    /// Razeri classifies every difference between two deploys and hands the
    /// ones that lose nothing to this method, one at a time. What comes back
    /// goes into the file an operator runs; `None` means the change is named in
    /// the plan with this engine's name beside it, so the reader learns which
    /// engine has no statement rather than that no engine does.
    ///
    /// # The default, and why it is the only one
    ///
    /// `ALTER TABLE … ADD COLUMN … <type>` is the one spelling every engine
    /// Razeri targets accepts, so a dialect that answers nothing still writes
    /// the commonest evolution there is: a column that was not there yesterday.
    /// The column is declared without `NOT NULL`, which is the only form that
    /// can be added to a table that already holds rows.
    ///
    /// Every other change answers `None` by default. A widening and a record
    /// that gained a field are each spelled three or four ways across the
    /// engines Razeri reaches, and a default picked from one of them writes SQL
    /// the others reject — a statement handed to an operator who then finds out
    /// their engine will not take it. A dialect that has measured its engine
    /// says so here, and the ones that have not say nothing.
    ///
    /// The statement comes back without a terminator; the caller separates
    /// statements the way this engine separates them.
    fn render_column_evolution(&self, change: &ColumnEvolution<'_>) -> Option<String> {
        match change {
            ColumnEvolution::AddColumn { schema, table, column, data_type } => {
                let target = self.qualify_name(*schema, table);
                let name = self.quote_identifier(column);
                let rendered = self.render_nullable_data_type(data_type);
                Some(format!("ALTER TABLE {target} ADD COLUMN {name} {rendered}"))
            }
            ColumnEvolution::WidenColumn { .. } | ColumnEvolution::AddNestedField { .. } => None,
        }
    }

    /// Render the surrogate identity column — a plain, ungenerated `BIGINT NOT
    /// NULL` on **every** dialect.
    ///
    /// **razeri's surrogate keys are logical and DETERMINATE, never
    /// engine-generated.** The identity value is a hash
    /// derived from the entity's identity grain, WRITTEN BY THE LOAD
    /// (`materialize_core`, `sid_expression`), so the same design loaded with the
    /// same data converges to the same key on `Postgres`, `Snowflake`, `MariaDB`,
    /// `ClickHouse` — every target. A database-assigned `AUTO_INCREMENT` /
    /// `IDENTITY(1,1)` / `GENERATED ALWAYS AS IDENTITY` would be sequential,
    /// load-order-dependent and **non-portable** — a different key per database
    /// for the same row — which is the one thing a portable key may not be. So no
    /// dialect emits a generator here; every one renders a plain column and the
    /// load fills it.
    ///
    /// `SQLite` narrows the type to `INTEGER` and `ClickHouse`/`DuckDB` carry
    /// their own overrides only to document the same plain shape; no override
    /// re-introduces a generator.
    ///
    /// The `_data_type` argument is reserved for future use (e.g., dialect-aware
    /// width selection); current dialects always emit `BIGINT` / `INTEGER`.
    fn render_identity_column(&self, name: &str, _data_type: &DataType) -> String {
        let quoted = self.quote_identifier(name);
        format!("{quoted} BIGINT NOT NULL")
    }

    /// Whether this platform's engine actually **assigns** an identity column's
    /// value, rather than merely tolerating the declaration.
    ///
    /// **This is a dialect fact, not a field fact, and the difference is a
    /// deploy-time failure.** `Field::identity` says razeri intends the engine
    /// to generate the value; whether it does depends entirely on the target.
    /// `render_identity_column`'s own table above records that `DuckDB`,
    /// `SQLite` and `ClickHouse` have **no native identity** — there the column
    /// comes out as a plain `NOT NULL` and **the writer must supply it.**
    ///
    /// The default is `false` because the default `render_identity_column`
    /// emits no generation clause: a dialect that overrides the rendering to
    /// generate values must override this too, and
    /// `the_identity_capability_matches_what_each_dialect_renders` holds the two
    /// in step so they cannot drift.
    ///
    /// Read by the deploy bundle's write contract: a column
    /// the engine does not generate is a column a hand-written `INSERT` owes.
    fn generates_identity_values(&self) -> bool {
        false
    }

    /// **The latest instant this platform can hold EXACTLY in the column it
    /// renders for `data_type`** — the ceiling the refuse-by-name rule compares
    /// against, or `None` for *no declared ceiling*.
    ///
    /// Spelled `YYYY-MM-DD HH:MM:SS`, which is how razeri writes a timestamp
    /// literal (`razeri_materialize::convert::OPEN_INTERVAL_SENTINEL`), so the
    /// comparison is a string comparison over a format that sorts
    /// chronologically. A ceiling and a value in the same spelling cannot be
    /// compared wrongly by a parser neither of them goes through.
    ///
    /// # What the refusal contract asks of this
    ///
    /// > A value razeri cannot store exactly on a target platform is a
    /// > deploy-time refusal naming the value, the column, the platform and the
    /// > ceiling — never a truncation, never a saturated write.
    ///
    /// The *refusal* lives in `razeri_materialize::bundle`, which is the one
    /// place it is built — the function is `refuse_unrepresentable_values`, and
    /// it is reached from `generate_bundle` before a single file is rendered.
    /// This is only where a platform declares the number.
    ///
    /// # A stated variance from the decision's original wording
    ///
    /// The refusal was decided as a *deploy-time* act, homed in the
    /// prerequisites step. Razeri refuses **earlier**: at bundle
    /// generation, by declining to emit the bundle at all. That is strictly
    /// ahead of deploy time and cannot be skipped by an operator who never runs
    /// the script — a deliberate strengthening, recorded rather
    /// than glossed. The consequence worth knowing: a *hand-assembled* bundle,
    /// or one from an older razeri, is not re-checked at deploy time by
    /// anything. **The default is `None`, which
    /// means "razeri has no measured ceiling for this platform and type" and not
    /// "this platform holds everything"** — an unmeasured platform gets no
    /// refusal rather than an invented one.
    ///
    /// # The ceiling is a property of the TYPE, not of the platform
    ///
    /// That is the half a platform-flat capability would get wrong, and it is
    /// measured rather than assumed (reading the renderers):
    ///
    /// | platform | `Timestamp(p)` renders | ceiling | `TimestampTz(p)` renders | ceiling |
    /// |---|---|---|---|---|
    /// | `MySQL`, `MariaDB` | `DATETIME(p)` | `None` — the end of the four-digit calendar is not a constraint | `TIMESTAMP(p)` | **`2038-01-19 03:14:07`** |
    /// | `ClickHouse` | `DateTime64(p)` | `2299-12-31 23:59:59` at p ≤ 6, **`2262-04-11 23:47:16`** at p ≥ 7 | `DateTime64(p,'UTC')` | the same |
    /// | everything else | — | not measured → `None` | — | `None` |
    ///
    /// On `MySQL` the two razeri type variants land on *different engine types*
    /// and get different answers: `Timestamp` renders as the
    /// non-converting `DATETIME` — the type whose semantics match the declared
    /// non-tz timestamp — which runs to the end of the calendar and so
    /// declares no ceiling at all, while `TimestampTz` keeps `TIMESTAMP` and its
    /// 32-bit epoch boundary. A check keyed on the platform alone would either
    /// miss the real ceiling or refuse a column that is fine. On `ClickHouse`
    /// the ceiling moves with the **declared precision** of one type:
    /// `DateTime64(9)` is int64 nanoseconds from the epoch and stops at
    /// 2262-04-11, while `DateTime64(6)` reaches 2299.
    ///
    /// Parameters:
    /// - `data_type`: the column's declared type, as the design carries it —
    ///   not the rendered string, because the precision is what moves the answer
    ///   and re-parsing it back out of `DateTime64(9)` would be a second reading
    ///   of what the dialect already knows.
    fn representable_timestamp_ceiling(&self, data_type: &DataType) -> Option<&'static str> {
        let _ = data_type;
        None
    }

    /// Whether the platform requires every auto-increment / identity column to
    /// be the leading column of an index (PK or KEY).
    ///
    /// `MySQL` / `MariaDB`: `true` (otherwise error 1075). Others: `false`.
    ///
    /// When this is `true` and an identity column is not already the leading
    /// column of the primary key, the DDL renderer must emit an additional
    /// `KEY (identity_col)` clause on the table.
    fn auto_increment_requires_key(&self) -> bool {
        false
    }

    /// Prefix for DROP TABLE statements.
    fn render_drop_table_prefix(&self, if_exists: bool) -> String {
        if if_exists { "DROP TABLE IF EXISTS".to_string() } else { "DROP TABLE".to_string() }
    }

    /// Prefix for DROP VIEW statements.
    fn render_drop_view_prefix(&self, if_exists: bool) -> String {
        if if_exists { "DROP VIEW IF EXISTS".to_string() } else { "DROP VIEW".to_string() }
    }

    /// Prefix for CREATE SCHEMA / CREATE NAMESPACE.
    fn render_create_schema_prefix(&self, if_not_exists: bool) -> String {
        if if_not_exists {
            "CREATE SCHEMA IF NOT EXISTS".to_string()
        } else {
            "CREATE SCHEMA".to_string()
        }
    }

    /// Render a complete CREATE SCHEMA statement.
    ///
    /// Dialects that need fundamentally different syntax (e.g. T-SQL wrapping
    /// in `IF SCHEMA_ID(...) IS NULL EXEC(...)`) should override this method.
    /// The default concatenates [`Self::render_create_schema_prefix`] with the name.
    fn render_create_schema_statement(&self, name: &str, if_not_exists: bool) -> String {
        let prefix = self.render_create_schema_prefix(if_not_exists);
        format!("{prefix} {name}")
    }

    /// Render a table comment (platform-specific syntax).
    ///
    /// Like [`Self::render_column_comment`], nothing in the tree calls this and
    /// no dialect overrides it — **and unlike its sibling it has not been
    /// measured.** Read that method's table before wiring either: the ANSI
    /// spelling is a hard syntax error on five of the ten platforms razeri
    /// renders for at the column level, and this form was not probed.
    fn render_table_comment(&self, table: &str, comment: &str) -> Option<String> {
        Some(format!("COMMENT ON TABLE {table} IS '{comment}'"))
    }

    /// Render a column comment — **not wired to anything, and measured**.
    ///
    /// # Nothing calls this
    ///
    /// No caller in the tree, no dialect override, and, until measured, no
    /// execution against a live engine — the exact state the column `DEFAULT`
    /// clause was in when it turned out to be refused outright on four platforms
    /// of ten and silently wrong on a fifth. Moving the open
    /// interval's meaning here was proposed **on the condition that it be measured first**,
    /// because *"a comment that fails to compile is a worse outcome than the
    /// clause it replaced"*.
    ///
    /// # It was measured, on ten platforms, and this ANSI form is right on five
    ///
    /// Executed against six containers, in-process `DuckDB` and
    /// `SQLite`, and both live cloud accounts:
    ///
    /// | platform | this `COMMENT ON COLUMN` | inline `COMMENT` in `CREATE TABLE` | what it does take |
    /// |---|---|---|---|
    /// | `PostgreSQL`, Citus | ✅ | ❌ syntax error | this, as a separate statement |
    /// | `DuckDB` | ✅ | ❌ syntax error | this, as a separate statement |
    /// | Snowflake, Databricks | ✅ | ✅ | either |
    /// | `ClickHouse` | ❌ `SYNTAX_ERROR` (code 62) | ✅ | inline, or `ALTER TABLE … COMMENT COLUMN c '…'` |
    /// | `MySQL`, `MariaDB` | ❌ `ERROR 1064` | ✅ | inline, or `ALTER TABLE … MODIFY <whole column definition> COMMENT '…'` |
    /// | SQL Server | ❌ `Msg 156, Incorrect syntax near the keyword 'ON'` | ❌ `Msg 102` | `EXEC sp_addextendedproperty …` — a stored procedure, not DDL |
    /// | `SQLite` | ❌ syntax error | ❌ syntax error | **nothing at all** |
    ///
    /// Four mechanisms for ten platforms, and two of them carry a hazard the
    /// `DEFAULT` clause never had:
    ///
    /// - `MySQL`'s and `MariaDB`'s only `ALTER` route **redefines the column**.
    ///   Measured: a `MODIFY` that did not restate `NOT NULL` left
    ///   `is_nullable = YES` behind it. A documentation mechanism that can
    ///   silently de-constrain a column is strictly worse than the clause it
    ///   replaces.
    /// - SQL Server's `sp_addextendedproperty` **is not idempotent**:
    ///   `Msg 15233 — Property 'MS_Description' already exists`. Razeri emits
    ///   `CREATE TABLE IF NOT EXISTS` so a deploy bundle can be re-applied; a
    ///   comment mechanism that fails on the second run takes that away.
    ///
    /// # So the escape hatch was taken
    ///
    /// Q1's answer included its own fall-back — *"if the measurement comes back
    /// ugly, take the simpler answer: no comment, and the bundle README carries
    /// the contract"* — and the measurement is ugly. **Razeri emits no column
    /// comment.** The open interval's meaning ships instead in the deploy
    /// bundle's generated *write contract*
    /// (`razeri_materialize::bundle::write_contract`, Q5), which is prose an
    /// operator reads, is right on all ten platforms because no engine parses
    /// it, and is owed regardless of how this measurement came out.
    ///
    /// The hook stays, unchanged and unwired, for the same reason
    /// `render_column_default` stays: a dialect that genuinely wants to emit one
    /// has somewhere to say so. **A dialect that overrides this owes a
    /// measurement first** — the ANSI spelling below is a hard syntax error on
    /// five of the ten platforms razeri renders for.
    fn render_column_comment(&self, table: &str, column: &str, comment: &str) -> Option<String> {
        Some(format!("COMMENT ON COLUMN {table}.{column} IS '{comment}'"))
    }

    /// Whether to render IF NOT EXISTS on CREATE TABLE.
    fn supports_if_not_exists(&self) -> bool {
        true
    }

    /// Render a column's `DEFAULT` clause — **keyword included** — or decline it.
    ///
    /// `None` means *this dialect renders no default clause for this value*,
    /// and Razeri's column renderer omits the whole clause. The ANSI default
    /// returns `None` for every value, which
    /// is the write-contract rule expressed where the renderer can see it:
    /// **razeri emits no
    /// column `DEFAULT` clause in rendered DDL, on any platform, for any value —
    /// a value the generated load owns is written by the load, never by the
    /// schema.**
    ///
    /// *Read that qualifier deliberately.* The sentence is about the DDL an engine
    /// executes. The `.raz.sql` **agnostic interchange** form —
    /// `Table::to_ddl()`, which `Table::from_ddl()` parses back — still
    /// serializes `Field::default_value` as `DEFAULT <value>`, because that is
    /// where a design's declared default survives a save and a load.
    ///
    /// **That exception is a serializer, not a platform, and the word "agnostic"
    /// names both.** `to_ddl()` renders through a free function and consults no
    /// dialect; you reach it by calling it, never by choosing a target.
    /// `SchemaObject::render_ddl` short-circuits to it only for a renderer whose
    /// [`SqlRenderer::is_agnostic_dialect`] answers `true` — which defaults to
    /// `false` here and is overridden by exactly one type in the tree,
    /// `AnsiDialect`, which no registration hands out. The platform the registry
    /// publishes under the name `agnostic` is `AgnosticDialect`; it does **not**
    /// override the method, so it declines the clause like every other target.
    /// The rule therefore holds on all eleven registered platforms, `agnostic`
    /// included, on every rendering path, and a regression test pins it.
    ///
    /// # Why the keyword lives in here
    ///
    /// It used to be concatenated by the caller — `parts.push(format!("DEFAULT
    /// {rendered}"))` — so the hook could rewrite a value and **could not decline
    /// a clause**: a dialect returning `""` emitted a bare dangling `DEFAULT`.
    /// This is the same correction made for
    /// statement boundaries: *the emission declares the boundary; a consumer
    /// never infers it.*
    ///
    /// # Why the hook survives the decision
    ///
    /// `Field::default_value` stays on the struct, so the design
    /// still knows what a column's intended default is, and a future dialect that
    /// genuinely wants to emit one has somewhere to say so. The distinction being
    /// bought is between **what razeri knows** and **what razeri emits**.
    ///
    /// A dialect that overrides this owes the whole clause, keyword and all —
    /// `Some(format!("DEFAULT {value}"))` — because there is nowhere else it is
    /// added.
    fn render_column_default(&self, value: &str) -> Option<String> {
        let _ = value;
        None
    }

    /// **Spell an author's OWN declared default in this engine's words.**
    ///
    /// This is the other sense of "default", and the seam a dialect had no way
    /// to reach. [`render_column_default`](Self::render_column_default) governs
    /// the tables Razeri's generated load owns, and it declines everywhere by
    /// design. A `tile: base` table is the ruled exception: the author owns
    /// every column, no generated statement writes into it, and the declared
    /// default is an engine constraint they asked for — so it is rendered, on
    /// every platform, and it used to be rendered **verbatim**.
    ///
    /// Verbatim is a portability hole with the design's own words in it. A
    /// design declaring `default: CURRENT_TIMESTAMP` is asking for *the current
    /// moment*, not for those eighteen characters; on `BigQuery` those
    /// characters name the zone-aware type, the column Razeri builds is
    /// `DATETIME`, and the `CREATE TABLE` is refused outright — *"Column
    /// default expression has type TIMESTAMP which cannot be assigned to column
    /// type DATETIME"*. The design was right and had nowhere to be translated.
    ///
    /// The default returns the value unchanged, which is exactly today's
    /// behaviour on every platform, so a dialect that says nothing renders what
    /// it always did.
    ///
    /// # A dialect overriding this owes a measurement, and owes restraint
    ///
    /// Translate an expression whose *meaning* your engine spells differently.
    /// Do not rewrite an author's literal, do not widen a type, and do not
    /// silently drop a default you cannot express — an author who declared one
    /// and got none has a column that fills with NULL and a document that says
    /// otherwise. Where the engine has no equivalent at all, leave the value
    /// alone and let the engine refuse it: a loud failure belongs to the value
    /// the author wrote, and a quiet substitution belongs to nobody.
    ///
    /// Parameters:
    /// - `value`: the default exactly as the design declares it.
    /// - `column_type`: the type of the column it is being assigned to —
    ///   load-bearing, because the same expression is legal against one type
    ///   and refused against another on the same engine.
    fn render_declared_column_default(&self, value: &str, column_type: &DataType) -> String {
        let _ = column_type;
        value.to_owned()
    }

    // ═══════════════════════════════════════════════════════════════
    // DDL Extensions
    // ═══════════════════════════════════════════════════════════════

    /// Render a BEGIN transaction statement.
    ///
    /// `PostgreSQL`: `BEGIN`, `SqlServer`: `BEGIN TRANSACTION`, `ClickHouse`: empty (no DDL transactions)
    fn render_begin_transaction(&self) -> &'static str {
        "BEGIN"
    }

    /// Render a COMMIT transaction statement.
    fn render_commit(&self) -> &'static str {
        "COMMIT"
    }

    /// Whether the platform supports DDL transactions.
    fn supports_ddl_transactions(&self) -> bool {
        true
    }

    /// Render a DROP FUNCTION statement with optional parameter types for overloaded functions.
    fn render_drop_function(&self, name: &str, param_types: &[&str], if_exists: bool) -> String {
        let exists = if if_exists { " IF EXISTS" } else { "" };
        if param_types.is_empty() {
            format!("DROP FUNCTION{exists} {name}")
        } else {
            format!("DROP FUNCTION{exists} {name}({})", param_types.join(", "))
        }
    }

    /// Render the drop keyword for a SQL object type.
    fn render_drop_object_keyword(&self, obj_type: &str) -> String {
        obj_type.to_uppercase()
    }

    /// Render the CREATE VIEW keyword/prefix with `secure/global_temp` modifiers.
    fn render_create_view_keyword(&self, secure: bool, global_temp: bool) -> String {
        let mut parts = vec!["CREATE OR REPLACE"];
        if secure {
            parts.push("SECURE");
        }
        if global_temp {
            parts.push("GLOBAL TEMPORARY");
        }
        parts.push("VIEW");
        parts.join(" ")
    }

    /// Render an IF EXISTS clause for ALTER TABLE DROP COLUMN/CONSTRAINT.
    ///
    /// Some platforms (`SqlServer`, Databricks, `MariaDB`) don't support IF EXISTS in ALTER DROP.
    fn supports_alter_drop_if_exists(&self) -> bool {
        true
    }

    // ═══════════════════════════════════════════════════════════════
    // Drop Behavior Hooks
    // ═══════════════════════════════════════════════════════════════

    /// Whether DROP INDEX uses ON syntax: `DROP INDEX idx ON table` (`SqlServer`).
    fn drop_index_uses_on_syntax(&self) -> bool {
        false
    }

    /// **Whether this engine checks the constraints it accepts.**
    ///
    /// The default is [`ConstraintEnforcement::Enforced`] — eight of Razeri's
    /// registered platforms, and the safe assumption for a dialect that has not
    /// said, because *"this engine guarantees nothing"* is the unusual claim.
    ///
    /// Answer [`ConstraintEnforcement::DeclaredOnly`] where a `PRIMARY KEY`,
    /// `FOREIGN KEY` or `UNIQUE` is accepted and never checked. Two engines are
    /// that, in two different ways, and the type carries both:
    ///
    /// - `BigQuery` has the words. `NOT ENFORCED` is the only legal spelling,
    ///   so the keyword goes on the constraint line and the engine makes the
    ///   declaration honest by itself.
    /// - `Redshift` has no words. It takes all three constraints, checks none,
    ///   and renders DDL a reader cannot tell from `PostgreSQL`'s — so the note
    ///   is written above the constraint list instead, and it is the only place
    ///   that DDL says what it means.
    ///
    /// [`key_constraint_suffix`](Self::key_constraint_suffix) reads this, so
    /// stating enforcement states the suffix too.
    fn constraint_enforcement(&self) -> ConstraintEnforcement {
        ConstraintEnforcement::Enforced
    }

    /// **The words a key constraint must carry to be accepted at all.**
    ///
    /// Appended to a table-level `PRIMARY KEY (…)` and to a
    /// `FOREIGN KEY (…) REFERENCES …`. Empty on every engine that enforces its
    /// keys, and empty on a declaring engine that has no keyword for it.
    ///
    /// The default reads
    /// [`constraint_enforcement`](Self::constraint_enforcement), so the two are
    /// one fact rather than two that must be kept in step. Override this only
    /// for a keyword a key constraint needs for some *other* reason than
    /// enforcement — there is no such engine in Razeri's set today.
    fn key_constraint_suffix(&self) -> &'static str {
        self.constraint_enforcement().keyword()
    }

    /// Whether a table-level `UNIQUE (…)` constraint is part of the grammar.
    ///
    /// `false` on an engine that has no such constraint at all, where the
    /// declaration is left out of the `CREATE TABLE` and named in a comment
    /// beside it rather than emitted and refused.
    fn supports_unique_constraint(&self) -> bool {
        true
    }

    /// Whether a table-level `CHECK (…)` constraint is part of the grammar.
    ///
    /// `false` on an engine that has none, with the same treatment as
    /// [`supports_unique_constraint`](Self::supports_unique_constraint): named
    /// in a comment, never written as SQL the engine will reject.
    fn supports_check_constraint(&self) -> bool {
        true
    }

    /// Whether the platform supports CASCADE/RESTRICT in DROP statements.
    ///
    /// True for `PostgreSQL`, `CitusDB`, `DuckDB`, Snowflake, Agnostic.
    /// False for `SqlServer`, `ClickHouse`, Databricks, `MySQL`, `MariaDB`.
    fn supports_cascade_drop(&self) -> bool {
        true
    }

    /// Whether `COMMENT ON PROCEDURE` is part of the grammar.
    ///
    /// `true` almost everywhere, and **false on `Redshift`**, where
    /// `COMMENT ON FUNCTION`, `COMMENT ON VIEW` and `COMMENT ON COLUMN` all
    /// exist and the procedure form alone does not: *"syntax error at or near
    /// `PROCEDURE`"*, measured on a live workgroup. A description is worth
    /// having and is not worth a statement that stops the script, so a
    /// declining engine simply carries no description on its procedures.
    fn supports_procedure_comment(&self) -> bool {
        true
    }

    /// Whether the platform supports function argument types in DROP FUNCTION.
    ///
    /// False for `ClickHouse` (no overloaded functions).
    fn supports_drop_function_arg_types(&self) -> bool {
        true
    }

    /// Whether the platform supports SYNC option for DROP (`ClickHouse`).
    fn supports_sync_drop(&self) -> bool {
        false
    }

    /// Whether the platform supports FORCE option for DROP (Databricks).
    fn supports_force_drop(&self) -> bool {
        false
    }

    /// Whether the platform supports CASCADE in ALTER TABLE DROP.
    ///
    /// Only `PostgreSQL`, `CitusDB`, `DuckDB` support CASCADE in ALTER TABLE DROP.
    fn supports_alter_drop_cascade(&self) -> bool {
        false
    }
}

/// **One row, written once** — the pieces of an INSERT that must do nothing
/// when a row already carries the same key.
///
/// The key value is not a field of its own: it is whichever `values` entry sits
/// at the same index as the key column in `columns`. Two fields that must agree
/// are two fields free to disagree, and the one they would disagree about here
/// is the one that decides whether a second write is a duplicate.
#[derive(Debug, Clone, Copy)]
pub struct InsertIfAbsent<'a> {
    /// The target table, already spelled the way the caller wants it written —
    /// schema-qualified or bare.
    pub table: &'a str,
    /// The columns being written, in the order `values` supplies them.
    pub columns: &'a [&'a str],
    /// One value expression per column.
    pub values: &'a [String],
    /// The columns whose equality means *this row is already here*.
    pub key_columns: &'a [&'a str],
}

impl InsertIfAbsent<'_> {
    /// The value expression written into `column`, if it is being written.
    #[must_use]
    pub fn value_of(&self, column: &str) -> Option<&str> {
        let at = self.columns.iter().position(|name| *name == column)?;
        self.values.get(at).map(String::as_str)
    }

    /// `key = value AND …` — the test for *already here*, in terms of the
    /// values this INSERT would have written.
    ///
    /// `qualifier` prefixes the column side, which the guarded form needs so
    /// the probe's own row is named unambiguously.
    ///
    /// # Panics
    ///
    /// When a key column is not among the columns being written. A key the
    /// INSERT does not supply cannot be tested for, and silently dropping it
    /// from the predicate would make the guard match everything.
    #[must_use]
    pub fn key_predicate(&self, qualifier: &str) -> String {
        self.key_columns
            .iter()
            .map(|column| {
                let value = self
                    .value_of(column)
                    .unwrap_or_else(|| panic!("{column} is a key column and must be written"));
                format!("{qualifier}{column} = {value}")
            })
            .collect::<Vec<_>>()
            .join(" AND ")
    }

    /// **`ON CONFLICT (key) DO NOTHING`** — for the platforms that let the
    /// engine decide, which is every platform that has the clause.
    ///
    /// The engine tests the key as it writes, so two sessions registering one
    /// file at the same moment settle on one row rather than on whichever of
    /// them looked first.
    #[must_use]
    pub fn on_conflict_do_nothing(&self) -> String {
        format!(
            "{}\n{}\nON CONFLICT ({}) DO NOTHING;",
            self.target(),
            self.values_clause(),
            self.key_columns.join(", ")
        )
    }

    /// **`ON DUPLICATE KEY UPDATE key = key`** — the `MySQL` family's no-op.
    ///
    /// `INSERT IGNORE` would be shorter and it is not the same request: it
    /// downgrades *every* error on the statement to a warning — a truncated
    /// value, a bad date — so a row that should have been refused arrives
    /// mangled and silent. Assigning the key to itself touches only the
    /// collision this is about, and leaves everything else to complain
    /// normally.
    #[must_use]
    pub fn on_duplicate_key_no_op(&self) -> String {
        let held = self
            .key_columns
            .iter()
            .map(|column| format!("{column} = {column}"))
            .collect::<Vec<_>>()
            .join(", ");
        format!("{}\n{}\nON DUPLICATE KEY UPDATE {held};", self.target(), self.values_clause())
    }

    /// **The guarded form over an explicit one-row source** — the same
    /// `INSERT … SELECT … WHERE NOT EXISTS` the portable default writes, with a
    /// `FROM` clause under it.
    ///
    /// `GoogleSQL` refuses a `WHERE` on a query that selects from nothing —
    /// *"Query without FROM clause cannot have a WHERE clause"*, measured on the
    /// live service on every generated `register_file` procedure — while
    /// `PostgreSQL` and its cousins accept the bare form. `(SELECT 1)` is a
    /// one-row table that changes no result: the guard still decides whether
    /// the row is written, and the values are still the caller's.
    ///
    /// It stays a separate form rather than becoming the default because the
    /// engines that need no `FROM` read better without one, and a clause every
    /// platform carries for one platform's sake is how a rendering stops saying
    /// what it means.
    #[must_use]
    pub fn guarded_over_one_row(&self) -> String {
        format!(
            "{}\nSELECT {}\nFROM (SELECT 1)\nWHERE NOT EXISTS (SELECT 1 FROM {} WHERE {});",
            self.target(),
            self.values.join(", "),
            self.table,
            self.key_predicate("")
        )
    }

    /// `INSERT INTO t (a, b)` — shared by every form below.
    fn target(&self) -> String {
        format!("INSERT INTO {} ({})", self.table, self.columns.join(", "))
    }

    /// `VALUES (…)`.
    fn values_clause(&self) -> String {
        format!("VALUES ({})", self.values.join(", "))
    }
}

/// Level 4 — DML rendering with reasonable defaults.
pub trait DmlRenderer: SqlRenderer {
    /// Prefix for INSERT statements.
    fn render_insert_prefix(&self) -> &'static str {
        "INSERT INTO"
    }

    /// **Write one row, and do nothing if its key is already there.**
    ///
    /// Every platform can express this and they do not agree on how, so the
    /// spelling belongs to the dialect and not to the caller. The default is
    /// the portable one — an `INSERT … SELECT` guarded by `WHERE NOT EXISTS` —
    /// which needs no upsert syntax at all and is therefore the right answer
    /// for a platform nobody has written an arm for. Platforms with a native
    /// idiom override it: `ON CONFLICT … DO NOTHING` where that exists,
    /// `ON DUPLICATE KEY UPDATE` on the `MySQL` family.
    ///
    /// **No dialect is left without an idempotent form.** The guarded form is
    /// weaker than the native ones under concurrency — two sessions can both
    /// find the row absent and both insert — which is why a platform that can
    /// let the engine decide should, and why this one leans on the key's own
    /// uniqueness constraint to catch the race rather than pretending it cannot
    /// happen. On an engine that enforces no key at all the guard is the whole
    /// of what there is, and it is worth saying so rather than implying more.
    fn render_insert_if_absent(&self, insert: &InsertIfAbsent<'_>) -> String {
        format!(
            "{}\nSELECT {}\nWHERE NOT EXISTS (SELECT 1 FROM {} WHERE {});",
            insert.target(),
            insert.values.join(", "),
            insert.table,
            insert.key_predicate("")
        )
    }

    /// Prefix for MERGE statements.
    fn render_merge_prefix(&self) -> &'static str {
        "MERGE INTO"
    }

    /// Render the platform's upsert strategy keyword.
    ///
    /// Returns `None` if platform doesn't support upsert natively.
    fn render_upsert_strategy(&self) -> Option<&str> {
        None
    }

    /// Render RETURNING / OUTPUT clause for INSERT/UPDATE.
    fn render_returning_clause(&self, _columns: &[&str]) -> Option<String> {
        None
    }

    /// Render a LIMIT clause.
    fn render_limit_clause(&self, n: usize) -> String {
        format!("LIMIT {n}")
    }

    /// Render a temporary table prefix or keyword.
    fn render_temp_table_prefix(&self) -> &'static str {
        "TEMPORARY"
    }
}

/// Level 5 — Stored procedure / function rendering with defaults.
pub trait ProcedureRenderer: SqlRenderer {
    /// Prefix for CREATE PROCEDURE.
    fn render_create_procedure_prefix(&self) -> &'static str {
        "CREATE OR REPLACE PROCEDURE"
    }

    /// Prefix for CREATE FUNCTION.
    fn render_create_function_prefix(&self) -> &'static str {
        "CREATE OR REPLACE FUNCTION"
    }

    /// Render a variable declaration inside a procedure body.
    fn render_variable_declaration(&self, name: &str, dt: &DataType) -> String {
        format!("DECLARE {} {};", name, self.render_data_type(dt))
    }

    /// Render BEGIN/END block delimiters.
    fn render_begin_end(&self, body: &str) -> String {
        format!("BEGIN\n{body}\nEND;")
    }

    /// Whether procedures use a language clause (e.g., Snowflake JavaScript).
    fn requires_language_clause(&self) -> bool {
        false
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::DialectCapabilities;
    use crate::sid_spelling::SidHelperLanguage;

    /// A test dialect that implements only the required `SqlRenderer` methods.
    /// All other traits use defaults.
    struct TestDialect;

    impl SqlRenderer for TestDialect {
        fn render_data_type(&self, dt: &DataType) -> String {
            match dt {
                DataType::Boolean(_) => "BOOLEAN".to_string(),
                DataType::Integer(_) => "INTEGER".to_string(),
                _ => "TEXT".to_string(),
            }
        }
        fn quote_identifier(&self, name: &str) -> String {
            format!("\"{name}\"")
        }
        fn qualify_name(&self, schema: Option<&str>, name: &str) -> String {
            match schema {
                Some(s) => format!("{}.{}", self.quote_identifier(s), self.quote_identifier(name)),
                None => self.quote_identifier(name),
            }
        }
        fn render_current_timestamp(&self) -> String {
            "CURRENT_TIMESTAMP".to_string()
        }
    }

    impl ExpressionRenderer for TestDialect {}
    impl DdlRenderer for TestDialect {}
    impl DmlRenderer for TestDialect {}
    impl ProcedureRenderer for TestDialect {}
    impl DialectCapabilities for TestDialect {}

    /// The same dialect with the two file-and-key facts stated. It exists to
    /// prove that a dialect Razeri never compiled against reaches the behaviour
    /// by *declaring* it — which is the whole property, and is not visible from
    /// a dialect that ships in this tree.
    struct StatedDialect;

    impl SqlRenderer for StatedDialect {
        fn render_data_type(&self, _dt: &DataType) -> String {
            "TEXT".to_string()
        }
        fn quote_identifier(&self, name: &str) -> String {
            format!("\"{name}\"")
        }
        fn qualify_name(&self, _schema: Option<&str>, name: &str) -> String {
            self.quote_identifier(name)
        }
        fn render_current_timestamp(&self) -> String {
            "CURRENT_TIMESTAMP".to_string()
        }
        fn sid_helper_body(&self) -> Option<SidHelperBody> {
            Some(SidHelperBody {
                language: SidHelperLanguage::Named("ecmascript"),
                body: "return 1;",
            })
        }
        fn delimited_file_relation(&self, path_literal: &str) -> Option<String> {
            Some(format!("SCAN({path_literal})"))
        }
    }

    /// **Silence is the default, and silence means Razeri composes.**
    ///
    /// Both facts are opt-in: a dialect that says nothing gets the SQL
    /// derivation for its key and no generated staging fill at all. Neither
    /// default may become a guess — a composed body on an engine with no hash
    /// keys a warehouse to a number nothing reproduces, and an invented file
    /// relation fails the load on its first statement.
    #[test]
    fn a_dialect_that_states_neither_fact_is_asked_for_nothing() {
        let d: &dyn SqlRenderer = &TestDialect;
        assert_eq!(d.sid_helper_body(), None);
        assert_eq!(d.delimited_file_relation("'/data/x.csv'"), None);
    }

    /// And a dialect that states them is heard through the trait object, which
    /// is the only way Razeri ever holds one.
    #[test]
    fn a_dialect_that_states_them_is_heard_through_the_trait_object() {
        let d: &dyn SqlRenderer = &StatedDialect;
        assert_eq!(
            d.sid_helper_body(),
            Some(SidHelperBody {
                language: SidHelperLanguage::Named("ecmascript"),
                body: "return 1;",
            })
        );
        assert_eq!(
            d.delimited_file_relation("'/data/x.csv'").as_deref(),
            Some("SCAN('/data/x.csv')")
        );
    }

    #[test]
    fn sql_renderer_core_methods_work() {
        let d = TestDialect;
        assert_eq!(d.render_data_type(&DataType::boolean()), "BOOLEAN");
        assert_eq!(d.quote_identifier("users"), "\"users\"");
        assert_eq!(d.qualify_name(Some("public"), "users"), "\"public\".\"users\"");
        assert_eq!(d.render_current_timestamp(), "CURRENT_TIMESTAMP");
    }

    #[test]
    fn dialect_name_returns_ansi_by_default() {
        let d = TestDialect;
        assert_eq!(d.dialect_name(), "ansi");
    }

    #[test]
    fn expression_renderer_defaults_produce_ansi_sql() {
        let d = TestDialect;
        assert_eq!(d.render_cast("age", &DataType::int()), "CAST(age AS INTEGER)");
        assert_eq!(d.render_concat(&["a".into(), "b".into()]), "CONCAT(a, b)");
        assert_eq!(d.render_coalesce(&["x".into(), "y".into()]), "COALESCE(x, y)");
    }

    #[test]
    fn ddl_renderer_defaults_produce_ansi_sql() {
        let d = TestDialect;
        assert_eq!(d.render_create_table_prefix(), "CREATE TABLE");
        assert_eq!(d.render_create_view_prefix(), "CREATE OR REPLACE VIEW");
        assert_eq!(
            d.render_column_definition("name", &DataType::boolean(), false),
            "\"name\" BOOLEAN NOT NULL"
        );
        assert_eq!(d.render_column_definition("age", &DataType::int(), true), "\"age\" INTEGER");
    }

    #[test]
    fn dml_renderer_defaults_produce_ansi_sql() {
        let d = TestDialect;
        assert_eq!(d.render_insert_prefix(), "INSERT INTO");
        assert_eq!(d.render_merge_prefix(), "MERGE INTO");
        assert_eq!(d.render_limit_clause(10), "LIMIT 10");
        assert!(d.render_upsert_strategy().is_none());
        assert!(d.render_returning_clause(&["id"]).is_none());
    }

    #[test]
    fn procedure_renderer_defaults_produce_ansi_sql() {
        let d = TestDialect;
        assert_eq!(d.render_create_procedure_prefix(), "CREATE OR REPLACE PROCEDURE");
        assert_eq!(
            d.render_variable_declaration("v_count", &DataType::int()),
            "DECLARE v_count INTEGER;"
        );
        assert!(!d.requires_language_clause());
    }

    #[test]
    fn trait_hierarchy_allows_selective_override() {
        struct MySqlLike;
        impl SqlRenderer for MySqlLike {
            fn render_data_type(&self, _: &DataType) -> String {
                "INT".into()
            }
            fn quote_identifier(&self, name: &str) -> String {
                format!("`{name}`")
            }
            fn qualify_name(&self, schema: Option<&str>, name: &str) -> String {
                match schema {
                    Some(s) => format!("`{s}`.`{name}`"),
                    None => format!("`{name}`"),
                }
            }
            fn render_current_timestamp(&self) -> String {
                "NOW()".into()
            }
        }
        impl ExpressionRenderer for MySqlLike {
            fn render_concat(&self, parts: &[String]) -> String {
                format!("CONCAT({})", parts.join(", "))
            }
        }
        impl DdlRenderer for MySqlLike {}
        impl DmlRenderer for MySqlLike {}
        impl ProcedureRenderer for MySqlLike {}
        impl DialectCapabilities for MySqlLike {}

        let d = MySqlLike;
        assert_eq!(d.quote_identifier("users"), "`users`");
        assert_eq!(d.render_current_timestamp(), "NOW()");
        // DDL defaults still work even though we only overrode expressions
        assert_eq!(d.render_create_table_prefix(), "CREATE TABLE");
    }

    #[test]
    fn sql_renderer_expression_extensions_produce_ansi_defaults() {
        let d = TestDialect;
        assert_sql_renderer_literal_defaults(&d);
        assert_sql_renderer_parameter_and_merge_defaults(&d);
        assert_sql_renderer_update_insert_defaults(&d);
        assert_sql_renderer_partition_and_window_defaults(&d);
    }

    /// Assert ANSI defaults for literal, date/time, and basic expression hooks.
    /// Parameters:
    /// - dialect: Renderer under test.
    fn assert_sql_renderer_literal_defaults(dialect: &TestDialect) {
        assert_eq!(dialect.render_boolean_literal(true), "TRUE");
        assert_eq!(dialect.render_boolean_literal(false), "FALSE");
        assert_eq!(dialect.render_date_literal("2024-01-15"), "DATE '2024-01-15'");
        assert_eq!(
            dialect.render_timestamp_literal("2024-01-15 12:00:00"),
            "TIMESTAMP '2024-01-15 12:00:00'"
        );
        assert_eq!(dialect.render_interval_literal("1 year"), "INTERVAL '1 year'");
        assert_eq!(dialect.render_current_date(), "CURRENT_DATE");
        assert_eq!(dialect.concat_operator(), "||");
        assert_eq!(dialect.render_nan_literal(&DataType::float()), "NULL");
        assert_eq!(dialect.render_infinity_literal(true, &DataType::float()), "NULL");
        assert_eq!(dialect.ifnull_function_name(), "COALESCE");
        assert_eq!(
            dialect.render_iif("x > 0", "pos", "neg"),
            "CASE WHEN x > 0 THEN pos ELSE neg END"
        );
        assert_eq!(
            dialect.render_date_trunc("month", "created_at"),
            "DATE_TRUNC('month', created_at)"
        );
        assert_eq!(
            dialect.render_date_extract("year", "created_at"),
            "EXTRACT(year FROM created_at)"
        );
        assert_eq!(dialect.render_try_cast("age", &DataType::int()), "TRY_CAST(age AS INTEGER)");
    }

    /// Assert ANSI defaults for parameter and merge-related extension hooks.
    /// Parameters:
    /// - dialect: Renderer under test.
    fn assert_sql_renderer_parameter_and_merge_defaults(dialect: &TestDialect) {
        assert_eq!(dialect.render_parameter_placeholder(1), "$1");
        assert_eq!(dialect.render_named_parameter("user_id"), ":user_id");
        assert_eq!(SqlRenderer::merge_not_matched_keyword(dialect), "WHEN NOT MATCHED");
        assert!(!SqlRenderer::supports_merge_not_matched_by_source(dialect));
        assert!(SqlRenderer::merge_supported(dialect));
        assert!(!SqlRenderer::merge_supports_schema_evolution_keyword(dialect));
        assert!(!SqlRenderer::merge_supports_table_hints(dialect));
        assert!(!SqlRenderer::merge_uses_output_clause(dialect));
        assert!(!SqlRenderer::merge_supports_returning_clause(dialect));
        assert_eq!(dialect.schema_separator(), ".");
        assert_eq!(dialect.statement_separator(), ";\n");
    }

    /// Assert ANSI defaults for update and insert behavior extension hooks.
    /// Parameters:
    /// - dialect: Renderer under test.
    fn assert_sql_renderer_update_insert_defaults(dialect: &TestDialect) {
        assert!(!SqlRenderer::supports_compound_assignment(dialect));
        assert!(!SqlRenderer::supports_update_from(dialect));
        assert!(!SqlRenderer::uses_alter_table_update(dialect));
        // How a mutation is SPELLED and what it may LOOK AT are
        // two facts, and the ANSI default is that a mutation may correlate.
        assert!(!SqlRenderer::mutation_reads_only_its_own_rows(dialect));
        assert!(!dialect.update_supports_top_clause());
        assert!(!dialect.update_supports_table_hints());
        assert!(!dialect.update_uses_output_clause());
        assert!(!dialect.update_supports_returning());
        assert!(!dialect.insert_uses_output_clause());
        assert!(!dialect.insert_supports_returning());
        assert!(!dialect.insert_supports_table_hints());
        assert!(!SqlRenderer::supports_insert_overwrite(dialect));
        assert!(!SqlRenderer::supports_on_conflict(dialect));
        assert!(!dialect.supports_overriding_clause());
        assert_eq!(dialect.returning_clause_keyword(), "RETURNING");
        assert!(!SqlRenderer::supports_returning_into(dialect));
        assert!(!SqlRenderer::supports_multi_table_insert(dialect));
    }

    /// Assert ANSI defaults for partitioning, generated columns, and window hooks.
    /// Parameters:
    /// - dialect: Renderer under test.
    fn assert_sql_renderer_partition_and_window_defaults(dialect: &TestDialect) {
        assert_eq!(
            dialect.render_time_partition_expr("event_ts", "monthly"),
            "date_trunc('month', event_ts)"
        );
        assert_eq!(dialect.render_partition_clause("event_ts"), "PARTITION BY (event_ts)");
        assert_eq!(
            dialect.render_generated_column("event_month", "DATE_TRUNC('month', event_ts)"),
            "event_month GENERATED ALWAYS AS (DATE_TRUNC('month', event_ts)) STORED"
        );
        assert!(!SqlRenderer::supports_window_frame_exclude(dialect));
        assert!(!SqlRenderer::supports_window_frame_groups(dialect));
        assert!(SqlRenderer::supports_named_windows(dialect));
    }

    #[test]
    fn ddl_renderer_extensions_produce_ansi_defaults() {
        let d = TestDialect;
        assert_ddl_renderer_transaction_and_view_defaults(&d);
        assert_ddl_renderer_drop_defaults(&d);
    }

    /// Assert ANSI DDL defaults for transaction and view keyword hooks.
    /// Parameters:
    /// - dialect: Renderer under test.
    fn assert_ddl_renderer_transaction_and_view_defaults(dialect: &TestDialect) {
        assert_eq!(dialect.render_begin_transaction(), "BEGIN");
        assert_eq!(dialect.render_commit(), "COMMIT");
        assert!(dialect.supports_ddl_transactions());
        assert_eq!(dialect.render_create_view_keyword(false, false), "CREATE OR REPLACE VIEW");
        assert_eq!(
            dialect.render_create_view_keyword(true, false),
            "CREATE OR REPLACE SECURE VIEW"
        );
        assert!(dialect.supports_alter_drop_if_exists());
    }

    /// Assert ANSI DDL defaults for drop-related behavior hooks.
    /// Parameters:
    /// - dialect: Renderer under test.
    fn assert_ddl_renderer_drop_defaults(dialect: &TestDialect) {
        assert_eq!(dialect.render_drop_object_keyword("table"), "TABLE");
        assert_eq!(
            dialect.render_drop_function("my_func", &[], true),
            "DROP FUNCTION IF EXISTS my_func"
        );
        assert!(!dialect.drop_index_uses_on_syntax());
        assert!(DdlRenderer::supports_cascade_drop(dialect));
        assert!(dialect.supports_drop_function_arg_types());
        assert!(!DdlRenderer::supports_sync_drop(dialect));
        assert!(!DdlRenderer::supports_force_drop(dialect));
        assert!(!dialect.supports_alter_drop_cascade());
    }

    /// **The one statement every engine takes**, written for a dialect that
    /// answered nothing. A plugin author gets the commonest evolution there is
    /// without writing a line for it.
    #[test]
    fn a_dialect_that_answers_nothing_still_adds_a_column() {
        let data_type = DataType::boolean();
        let written = TestDialect.render_column_evolution(&ColumnEvolution::AddColumn {
            schema: Some("telemetry_core"),
            table: "clients_daily",
            column: "is_default_browser",
            data_type: &data_type,
        });
        assert_eq!(
            written.as_deref(),
            Some(
                r#"ALTER TABLE "telemetry_core"."clients_daily" ADD COLUMN "is_default_browser" BOOLEAN"#
            )
        );
    }

    /// Everything else waits to be spelled. A default picked from one engine's
    /// grammar is a statement the others reject, handed to an operator who
    /// finds that out against their own warehouse.
    #[test]
    fn nothing_else_is_spelled_until_a_dialect_spells_it() {
        let data_type = DataType::text();
        assert!(
            TestDialect
                .render_column_evolution(&ColumnEvolution::WidenColumn {
                    schema: None,
                    table: "t",
                    column: "c",
                    data_type: &data_type,
                })
                .is_none()
        );
        assert!(
            TestDialect
                .render_column_evolution(&ColumnEvolution::AddNestedField {
                    schema: None,
                    table: "t",
                    column: "c",
                    field: "f",
                    data_type: &data_type,
                })
                .is_none()
        );
    }
}