razeri-plugin-contract 0.20.0

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
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
// 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::bulk_load_form::BulkLoadForm;
use crate::constraint_enforcement::ConstraintEnforcement;
use crate::date_format::DateFormat;
use crate::evolution::{ColumnEvolution, Written, WrittenObject};
use crate::flatten::{Flatten, FlattenRequest};
use crate::large_object::{HeldAs, TextLengthUnit};
use crate::number_format::NumberFormat;
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,
}

/// **One delimited source file, in every spelling an engine's file relation may
/// ask for it in** — what
/// [`SqlRenderer::delimited_file_relation_for`] is handed.
///
/// One struct rather than several arguments, because a slot that grows an
/// argument is a slot every dialect has to be recompiled for; one that grows a
/// field is not. Each is composed once, by the caller that knows the answer,
/// so no dialect has to take a path apart to find a file name in it.
///
/// A dialect reads the fields. One that builds a value, in its own tests,
/// starts from [`DelimitedFile::new`] and the `with_` methods, which is also
/// why it cannot be written out field by field outside this crate: the next
/// thing Razeri learns to say about a file arrives as a field with a default,
/// and no dialect's tests break for it.
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub struct DelimitedFile<'a> {
    /// The whole path to the file, already a single-quoted SQL string literal
    /// and already escaped. Put it where the relation takes a path, and do not
    /// quote it again.
    pub path_literal: &'a str,
    /// The directory the file sits in, already a single-quoted SQL string
    /// literal — for an engine that resolves a file name against a directory
    /// rather than opening a path.
    pub directory_literal: &'a str,
    /// The file's own name inside that directory, bare: no quotes and no path
    /// in front of it.
    pub name: &'a str,
    /// **The file's columns, in the order the file writes them**, spelled
    /// exactly as its header row spells them and with no quoting applied.
    ///
    /// Empty where the caller measured no header — a bundle assembled by hand.
    /// An engine that cannot read a file without its columns declared answers
    /// `None` to an empty list rather than guessing at one.
    ///
    /// A file with no header line ([`header`](Self::header) `false`) has no
    /// names of its own, and its columns arrive as `column0`, `column1` and
    /// on, counted from zero: the names `DuckDB` gives such a file, and the
    /// names a header cell with no name is read under everywhere.
    pub columns: &'a [String],
    /// **How the file's lines end**, as Razeri measured it when it read the
    /// file: [`LineEnding::CrLf`] for a carriage return and a newline,
    /// [`LineEnding::Lf`] for a newline alone.
    ///
    /// Put it wherever the engine's read names a record delimiter. An engine
    /// told `\n` for a file whose lines end `\r\n` either keeps the carriage
    /// return on the last field, so a name is stored one character too long
    /// and a number cannot be read, or, where the last field is quoted, reads
    /// past the closing quote into the next line. An engine whose read finds
    /// the ending itself can leave this alone, and should say so where it
    /// states its read.
    pub line_ending: LineEnding,
    /// **The character between the file's fields**, as the design declares
    /// it. Never a guess: an engine whose reader would otherwise sniff the
    /// delimiter is told this one.
    ///
    /// The four ASCII separators ([`FileDelimiter::is_control`]) are bytes no
    /// text editor shows, and engines differ in how a statement may name
    /// them: an escape, a hexadecimal literal, a function call, or not at
    /// all. Spell the one your engine was measured to take. Where it takes
    /// none, answer `None`: Razeri then declines the file by name and says
    /// which delimiter your engine does read.
    pub delimiter: FileDelimiter,
    /// **The character a field is quoted with**: `"` unless the design
    /// declares another. A field inside two of them may hold the delimiter
    /// and a line break, and two of them together inside it stand for one.
    pub quote: char,
    /// **Whether the file's first line names its columns.** `true` unless the
    /// design declares `header: false`; a file without one has its first row
    /// of values on its first line, and its
    /// [`columns`](Self::columns) are named by position.
    pub header: bool,
    /// **The encoding to read the bytes as**, where they are not UTF-8: the
    /// one name the encoding standard files it under (`windows-1252`,
    /// `shift_jis`). `None` on the ordinary day, which means UTF-8.
    ///
    /// Razeri asks
    /// [`delimited_file_relation_in_encoding`](SqlRenderer::delimited_file_relation_in_encoding)
    /// whether your engine has a word for the encoding before it hands one
    /// over here, so a dialect that answers that one `None` never meets an
    /// encoding in this field. One that answers it, and also overrides
    /// [`delimited_file_relation_for`](SqlRenderer::delimited_file_relation_for),
    /// reads this field there.
    pub encoding: Option<&'a str>,
}

impl<'a> DelimitedFile<'a> {
    /// **A file at `path_literal`, read the way every engine reads a file by
    /// default**: no columns measured, lines ending `\n`, split on commas,
    /// quoted with `"`, a header on its first line, and UTF-8.
    ///
    /// `path_literal` and `directory_literal` are finished single-quoted SQL
    /// string literals; `name` is the file's own name, bare.
    #[must_use]
    pub const fn new(path_literal: &'a str, directory_literal: &'a str, name: &'a str) -> Self {
        Self {
            path_literal,
            directory_literal,
            name,
            columns: &[],
            line_ending: LineEnding::Lf,
            delimiter: FileDelimiter::Comma,
            quote: '"',
            header: true,
            encoding: None,
        }
    }

    /// The same file, with its columns in the order the file writes them.
    #[must_use]
    pub const fn with_columns(mut self, columns: &'a [String]) -> Self {
        self.columns = columns;
        self
    }

    /// The same file, its lines ending as `line_ending` says.
    #[must_use]
    pub const fn with_line_ending(mut self, line_ending: LineEnding) -> Self {
        self.line_ending = line_ending;
        self
    }

    /// The same file, its fields split by `delimiter`.
    #[must_use]
    pub const fn with_delimiter(mut self, delimiter: FileDelimiter) -> Self {
        self.delimiter = delimiter;
        self
    }

    /// The same file, its fields quoted with `quote`.
    #[must_use]
    pub const fn with_quote(mut self, quote: char) -> Self {
        self.quote = quote;
        self
    }

    /// The same file, with a header line or without one.
    #[must_use]
    pub const fn with_header(mut self, header: bool) -> Self {
        self.header = header;
        self
    }

    /// The same file, its bytes read as `encoding`, or as UTF-8 for `None`.
    #[must_use]
    pub const fn with_encoding(mut self, encoding: Option<&'a str>) -> Self {
        self.encoding = encoding;
        self
    }

    /// **Whether the file is written the way a read that is told nothing
    /// reads it**: split on commas, quoted with `"`, and headed.
    ///
    /// The default [`delimited_file_relation_for`](SqlRenderer::delimited_file_relation_for)
    /// answers only for such a file, because the path-only
    /// [`delimited_file_relation`](SqlRenderer::delimited_file_relation) it
    /// hands over to has no way to be told anything else.
    #[must_use]
    pub fn is_plain(&self) -> bool {
        self.delimiter == FileDelimiter::Comma && self.quote == '"' && self.header
    }
}

/// **The character between a delimited file's fields** — one of the eight a
/// design names with a word, or any other single ASCII character.
///
/// The words are `comma`, `tab`, `pipe`, `semicolon`, and the four ASCII
/// separators `fs`, `gs`, `rs` and `us` (bytes `0x1C` to `0x1F`). A character
/// one of the words names always arrives as that word, never as
/// [`FileDelimiter::Literal`].
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub enum FileDelimiter {
    /// `,`
    #[default]
    Comma,
    /// The tab character.
    Tab,
    /// `|`
    Pipe,
    /// `;`
    Semicolon,
    /// The file separator, `0x1C`.
    Fs,
    /// The group separator, `0x1D`.
    Gs,
    /// The record separator, `0x1E`.
    Rs,
    /// The unit separator, `0x1F`.
    Us,
    /// Any other single ASCII character, written as itself.
    Literal(char),
}

impl FileDelimiter {
    /// The character itself.
    #[must_use]
    pub const fn as_char(self) -> char {
        match self {
            Self::Comma => ',',
            Self::Tab => '\t',
            Self::Pipe => '|',
            Self::Semicolon => ';',
            Self::Fs => '\u{1c}',
            Self::Gs => '\u{1d}',
            Self::Rs => '\u{1e}',
            Self::Us => '\u{1f}',
            Self::Literal(c) => c,
        }
    }

    /// The character as the one byte a reader splits on. Every delimiter a
    /// design can declare is ASCII.
    #[must_use]
    pub const fn as_byte(self) -> u8 {
        // ASCII for every value a design can declare.
        self.as_char() as u8
    }

    /// The word a design writes for this delimiter, or `None` for a literal.
    #[must_use]
    pub const fn word(self) -> Option<&'static str> {
        Some(match self {
            Self::Comma => "comma",
            Self::Tab => "tab",
            Self::Pipe => "pipe",
            Self::Semicolon => "semicolon",
            Self::Fs => "fs",
            Self::Gs => "gs",
            Self::Rs => "rs",
            Self::Us => "us",
            Self::Literal(_) => return None,
        })
    }

    /// **Whether this is one of the four ASCII separators**, `0x1C` to
    /// `0x1F` — the delimiters no text editor shows, which an engine's
    /// statement names, if at all, by an escape of its own.
    #[must_use]
    pub const fn is_control(self) -> bool {
        matches!(self, Self::Fs | Self::Gs | Self::Rs | Self::Us)
    }
}

/// **One setting a statement was written with, for the engine it names.**
///
/// Razeri's statement builders carry settings written for one engine — a
/// view's `security_barrier` for `PostgreSQL`, a table's data compression for
/// SQL Server. They reach every dialect tagged with the engine they were
/// written for, as that engine's dialect names itself
/// ([`SqlRenderer::dialect_name`]), and a dialect spells the ones written for
/// it and passes over the rest. Nothing in Razeri reads an engine's name to
/// decide which settings apply.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct EngineSetting<'a> {
    /// The engine the setting was written for, as its dialect names itself.
    pub engine: &'a str,
    /// The setting's name, in the engine's own words.
    pub name: &'a str,
    /// Its value, as the engine writes it.
    pub value: &'a str,
}

impl<'a> EngineSetting<'a> {
    /// One setting.
    #[must_use]
    pub const fn new(engine: &'a str, name: &'a str, value: &'a str) -> Self {
        Self { engine, name, value }
    }
}

/// **How the lines of a delimited file end.**
///
/// Measured, never assumed: [`LineEnding::of`] reads it off the file's own
/// bytes, and a file with no line break at all reads as [`LineEnding::Lf`],
/// which is what every engine reads by default.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub enum LineEnding {
    /// A newline alone, `\n`: every system but Windows.
    #[default]
    Lf,
    /// A carriage return and then a newline, `\r\n`: a file written on
    /// Windows.
    CrLf,
}

impl LineEnding {
    /// **How the lines of this text end**, decided by its first line break.
    ///
    /// The first break ends the header row, so it is written the way the rest
    /// of the file is. Text with no newline at all is [`LineEnding::Lf`].
    #[must_use]
    pub fn of(text: &[u8]) -> Self {
        match text.iter().position(|&byte| byte == b'\n') {
            Some(at) if at > 0 && text[at - 1] == b'\r' => Self::CrLf,
            _ => Self::Lf,
        }
    }

    /// The ending's characters, as they stand in the file.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Lf => "\n",
            Self::CrLf => "\r\n",
        }
    }

    /// The ending spelled with backslashes, `\n` or `\r\n`: the two or four
    /// characters an engine that reads backslash escapes in a string literal
    /// takes for it. Put it inside the quotes of a record delimiter, on an
    /// engine that reads them that way.
    #[must_use]
    pub const fn escaped(self) -> &'static str {
        match self {
            Self::Lf => "\\n",
            Self::CrLf => "\\r\\n",
        }
    }
}

/// **What a table's `CREATE TABLE` is about to say** — what
/// [`SqlRenderer::render_table_suffix`] is handed to decide the clause after
/// the column list.
///
/// One struct rather than several arguments, so the slot can learn more about a
/// table without changing its signature. Razeri builds it; a dialect reads it.
/// A dialect's own tests build one with [`TableSuffixRequest::new`] and the
/// `with_` methods, which is also why it cannot be written out field by field
/// outside this crate.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct TableSuffixRequest<'a> {
    /// Whether the table is dropped at the end of its session, its transaction
    /// or its batch. A transient table that outlives its session is not
    /// temporary.
    pub temporary: bool,
    /// The table's primary-key columns in key order, unquoted. Empty on a table
    /// with no primary key.
    pub primary_key: &'a [String],
    /// The columns the design's storage plan asked this table be clustered
    /// by, unquoted, and only those this table has. Empty on most tables.
    pub clustering_columns: &'a [String],
    /// The column whose greatest value survives when rows share a key, on the
    /// one table Razeri versions that way: the target of an engine whose
    /// [`MergeShape`](crate::MergeShape) is
    /// [`InsertDedup`](crate::InsertDedup). `None` on every other table.
    pub version_column: Option<&'a str>,
}

impl<'a> TableSuffixRequest<'a> {
    /// A persistent table with no primary key, no clustering columns and no
    /// version column.
    #[must_use]
    pub const fn new() -> Self {
        Self { temporary: false, primary_key: &[], clustering_columns: &[], version_column: None }
    }

    /// The same table, temporary or not.
    #[must_use]
    pub const fn with_temporary(mut self, temporary: bool) -> Self {
        self.temporary = temporary;
        self
    }

    /// The same table, with these primary-key columns.
    #[must_use]
    pub const fn with_primary_key(mut self, columns: &'a [String]) -> Self {
        self.primary_key = columns;
        self
    }

    /// The same table, with these clustering columns.
    #[must_use]
    pub const fn with_clustering_columns(mut self, columns: &'a [String]) -> Self {
        self.clustering_columns = columns;
        self
    }

    /// The same table, with this version column.
    #[must_use]
    pub const fn with_version_column(mut self, column: Option<&'a str>) -> Self {
        self.version_column = column;
        self
    }
}

impl Default for TableSuffixRequest<'_> {
    fn default() -> Self {
        Self::new()
    }
}

/// 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:
    ///
    /// ```rust,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.
    ///
    /// Most engines 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 engines 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, and every `nullable:` a
    /// design declares is discarded on that engine.
    ///
    /// # What a discarded `nullable:` costs, 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 comes 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 would be fabricated on that engine and honest on
    /// every other**, and the DDL is where that is prevented.
    ///
    /// # 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)
    }

    /// **A comment, written as this engine reads one.**
    ///
    /// Every comment Razeri writes into a script goes through here: the note
    /// over a statement, the heading of each part of a load, the banner at the
    /// top of a file. The default is [`crate::comment::block_comment`], `/* … */`,
    /// which closes itself, so a script whose line endings a tool turns into
    /// spaces still runs. A line comment, `-- …`, would turn every statement
    /// after it into comment.
    ///
    /// Override it only for an engine that cannot read a block comment, and
    /// say which in the override's own doc comment. No engine Razeri carries
    /// does: each of them reads `/* … */`. What comes back stands on lines of
    /// its own; Razeri indents it with the statement it describes.
    ///
    /// Parameters:
    /// - `text`: the comment's words, one or more lines, with no comment marks.
    fn render_comment(&self, text: &str) -> String {
        crate::comment::block_comment(text)
    }

    /// 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
    }

    /// **The name an object takes on an engine with no schemas**, where this
    /// dialect keeps a design's layers apart by folding the schema into it —
    /// `sales_raw` and `customers` become `sales_raw_customers` — or `None`,
    /// the default, where the schema is dropped.
    ///
    /// It is asked only of a dialect whose
    /// [`DialectCapabilities::supports_schemas`](crate::DialectCapabilities::supports_schemas)
    /// is `false`. With `None`, every object of every layer lives under its
    /// own bare name, so a design whose Raw and Core layers both hold a
    /// `customers` is refused: each load would write over the other's rows.
    /// Answer with a fold and Razeri keeps each object's schema and writes
    /// what this returns wherever it names the object — its `CREATE`, every
    /// statement that reads or writes it, every reference to it — so the same
    /// design renders, and two objects are refused only where their folded
    /// names are the same.
    ///
    /// Return the name unquoted; Razeri quotes it with
    /// [`Self::quote_identifier`]. [`Self::qualify_name`] given a schema has
    /// to answer the same object, quoted, because some statements are named
    /// through it; the conformance report checks that the two agree.
    fn fold_schema_into_name(&self, schema: &str, name: &str) -> Option<String> {
        let _ = (schema, name);
        None
    }

    /// 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;

    /// **The schemas a catalog scan passes over** — the engine's own
    /// bookkeeping, never a warehouse's contents.
    ///
    /// Read by [`Self::render_catalog_columns_query`] and
    /// [`Self::render_catalog_object_times_query`] when no single schema was
    /// named, so a scan of a whole warehouse sees the tables somebody created
    /// and not the catalog describing them. The default names the one schema
    /// the SQL standard puts the catalog in; an engine that keeps more of its
    /// own next to it adds them.
    fn catalog_system_schemas(&self) -> &'static [&'static str] {
        &["information_schema"]
    }

    /// **The query that lists what the warehouse holds** — one row per column,
    /// as `(schema, object, column)`.
    ///
    /// Razeri asks it to answer a question it cannot answer from a design: how
    /// much of this warehouse razeri itself rendered. Columns rather than
    /// object names alone, because the answer is read off both — a name carries
    /// the tier razeri mints (`…_staging`, `…_current`), and a column carries
    /// the bookkeeping only razeri writes (`…_sid`, `_loaded_at`). A scan that
    /// saw names alone would either miss an entity whose target table is a
    /// plain noun or count a table razeri never touched.
    ///
    /// The three columns are positional and in that order: every caller reads
    /// row `0`, `1`, `2` and nothing reads a column by name, so an engine whose
    /// catalog spells the headings differently needs no special case.
    ///
    /// `None` means **this engine states no catalog razeri can scan**, which is
    /// an answer rather than an omission: the caller says so by name instead of
    /// reporting an empty warehouse.
    ///
    /// Parameters:
    /// - `schema`: the one schema to look in. `None` means the whole warehouse,
    ///   minus [`Self::catalog_system_schemas`].
    fn render_catalog_columns_query(&self, schema: Option<&str>) -> Option<String> {
        Some(format!(
            "SELECT table_schema, table_name, column_name\nFROM \
             information_schema.columns\n{}\nORDER BY table_schema, table_name, column_name",
            self.catalog_scope_predicate("table_schema", schema)
        ))
    }

    /// **The query that says when each object was created**, as
    /// `(schema, object, created_at)` — where the engine records it at all.
    ///
    /// A second, independent reading of the same question
    /// [`Self::render_catalog_columns_query`] opens: the earliest moment razeri
    /// can prove it was here. It is a `None` on most engines, and deliberately
    /// so — `PostgreSQL` and `DuckDB` keep no creation time for a relation, and
    /// inventing one would be worse than having none.
    ///
    /// Parameters:
    /// - `schema`: the one schema to look in, or `None` for the whole
    ///   warehouse.
    fn render_catalog_object_times_query(&self, schema: Option<&str>) -> Option<String> {
        let _ = schema;
        None
    }

    /// The `WHERE` clause both catalog queries share: one named schema, or
    /// every schema that is not the engine's own.
    ///
    /// Parameters:
    /// - `column`: the catalog's own name for the schema column.
    /// - `schema`: the one schema to look in, or `None` for the whole
    ///   warehouse.
    fn catalog_scope_predicate(&self, column: &str, schema: Option<&str>) -> String {
        if let Some(one) = schema {
            return format!("WHERE {column} = '{}'", one.replace('\'', "''"));
        }
        let excluded: Vec<String> = self
            .catalog_system_schemas()
            .iter()
            .map(|name| format!("'{}'", name.replace('\'', "''")))
            .collect();
        format!("WHERE {column} NOT IN ({})", excluded.join(", "))
    }

    /// Return a stable string identifier for this dialect.
    ///
    /// A human-readable label in diagnostics and error messages, for **every
    /// dialect** registered in the `PlatformRegistry` (e.g. `"postgresql"`,
    /// `"sqlite"`, `"cockroachdb"`). For the engines Razeri ships, two
    /// renderings are chosen by this name rather than asked of a trait method —
    /// a bulk load's statement and a query's own syntax. Any other name gets
    /// the generic form: the bulk load in ANSI, the query spelled through your
    /// renderer. Keep it stable once a dialect is published.
    ///
    /// 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 — cast each part to text, escape and
    /// join the parts of a composite, hash the result, guard NULLs with a
    /// sentinel — and composes that derivation in exactly one place
    /// ([`crate::sid`]). What a dialect decides is the *vocabulary*: how this
    /// engine writes a replacement and a Unicode literal, 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 argument, as given — 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
    }

    /// **How this engine reads a delimited text file as a relation, told
    /// everything Razeri knows about the file** — or `None` where it cannot.
    ///
    /// The richer spelling of
    /// [`delimited_file_relation`](Self::delimited_file_relation), and the one
    /// the staging fill asks. The default hands the path to that method — or,
    /// for a file in a named [`encoding`](DelimitedFile::encoding), to
    /// [`delimited_file_relation_in_encoding`](Self::delimited_file_relation_in_encoding)
    /// — so a dialect that has stated those has stated this too, and its
    /// renders are byte for byte what they were.
    ///
    /// **The default reads only a plain file** ([`DelimitedFile::is_plain`]):
    /// split on commas, quoted with `"`, and headed. Neither method it hands
    /// over to can be told a delimiter, a quote or a missing header, so for
    /// any other file it answers `None`, and Razeri declines that file by name
    /// rather than reading a pipe-delimited file as one column. Override this
    /// method to read the others: put the file's
    /// [`delimiter`](DelimitedFile::delimiter),
    /// [`quote`](DelimitedFile::quote) and [`header`](DelimitedFile::header)
    /// where your engine's read takes them, and answer `None` for one it
    /// cannot be told.
    ///
    /// Override it, too, where the path alone is not enough. Two engines' file
    /// reads need more and cannot be given it any other way:
    ///
    /// - **the file's columns declared in the statement.** Oracle's external
    ///   table answers `ORA-00906: missing left parenthesis` without them, and
    ///   has no form that takes its column names from a header row;
    /// - **a directory rather than a path.** The same engine answers
    ///   `KUP-04125: no directory object specified for location 1 in LOCATION
    ///   clause` to an absolute path, and resolves a file name against a named
    ///   directory object instead — which
    ///   [`delimited_file_prerequisites`](Self::delimited_file_prerequisites)
    ///   is where such an object is made.
    ///
    /// Everything the returned relation owes, it owes for the reasons
    /// [`delimited_file_relation`](Self::delimited_file_relation) states:
    /// header from the first row, every column as text and unparsed, usable in
    /// a `FROM` clause. **Declaring the columns does not license declaring
    /// their types**: they are the source's text, and a reader that guessed
    /// would fail the load on its first row.
    fn delimited_file_relation_for(&self, file: &DelimitedFile<'_>) -> Option<String> {
        if !file.is_plain() {
            return None;
        }
        match file.encoding {
            None => self.delimited_file_relation(file.path_literal),
            Some(encoding) => self.delimited_file_relation_in_encoding(file.path_literal, encoding),
        }
    }

    /// **How this engine reads a parquet file as a relation of text** — or
    /// `None` where it cannot, which is the default.
    ///
    /// The relation owes what a delimited file's does: the file's own column
    /// names, every column as **text**, usable in a `FROM` clause. A parquet
    /// file carries its types, and the fill still reads each value as text so
    /// that one set of conversions, cleanings and checks serves every file;
    /// the text is the engine's own cast of each value (`2024-01-01 00:57:55`
    /// for a timestamp, `2.0` for a whole double), which is also the text
    /// Razeri counts and totals the file by before a build.
    ///
    /// `path_literal` arrives as a finished single-quoted SQL string literal,
    /// already escaped. An engine that answers `None` has its parquet sources
    /// declined by name, with the conversion that would load them.
    fn parquet_file_relation(&self, path_literal: &str) -> Option<String> {
        let _ = path_literal;
        None
    }

    /// **Statements this engine needs run once before any of its file relations
    /// resolve**, in order — and none by default.
    ///
    /// An engine that opens a path needs nothing here. An engine that opens a
    /// file only through an object somebody made — Oracle's `DIRECTORY` — needs
    /// that object made first, and the generated staging file is where it
    /// belongs: it is the one file that knows which directory the sources were
    /// read from.
    ///
    /// Each string is one statement without its terminator. Every one must be
    /// safe to run again, because the file it lands in runs on every deploy.
    ///
    /// `directory_literal` arrives as a finished single-quoted SQL string
    /// literal, already escaped.
    ///
    /// **Say what the statement costs.** An object like this is often
    /// privileged, and a statement an operator cannot run is better read than
    /// guessed at — put the privilege in a comment inside the statement, where
    /// it travels with it.
    fn delimited_file_prerequisites(&self, directory_literal: &str) -> Vec<String> {
        let _ = directory_literal;
        Vec::new()
    }

    /// **Statements this engine needs run before it can read THIS file**, in
    /// order — and none by default.
    ///
    /// The per-file companion of
    /// [`delimited_file_prerequisites`](Self::delimited_file_prerequisites),
    /// and the slot an engine with no file relation at all reads a file
    /// through. Where that method makes what every read shares — a directory
    /// object, a permitted path — this one makes what belongs to one file, and
    /// the staging fill emits it directly in front of the fill that reads it.
    ///
    /// Two kinds of engine answer it.
    ///
    /// - One whose file read is a **statement rather than a relation**. SAP
    ///   HANA's is `IMPORT FROM CSV FILE`, which writes into a table that
    ///   already exists; there is nothing to put in a `FROM` clause. Such a
    ///   dialect lands the file's rows in a table here and answers that table
    ///   from
    ///   [`delimited_file_relation_for`](Self::delimited_file_relation_for).
    /// - One whose relation needs a per-file object made first — a format, an
    ///   external stage, a descriptor.
    ///
    /// Each string is one statement without its terminator. **Every one must be
    /// safe to run again**, because the file it lands in runs on every deploy,
    /// and safe to run beside the others: a second deploy stages what the
    /// source holds now rather than adding a second copy of it.
    ///
    /// **Say what the statement costs.** A read like this is often privileged,
    /// and a statement an operator cannot run is better read than guessed at —
    /// put the privilege in a comment inside the statement, where it travels
    /// with it.
    fn delimited_file_statements_for(&self, file: &DelimitedFile<'_>) -> Vec<String> {
        let _ = file;
        Vec::new()
    }

    /// **The one-row table a query reads when it has nothing else to read**,
    /// or `None` on an engine that takes a `SELECT` with no `FROM` at all.
    ///
    /// Some of what Razeri measures is a value rather than a row of a table —
    /// the grand total a reconciliation compares against its sources is a sum
    /// of counts, and there is nothing to select it from. Most engines take
    /// `SELECT <value>` as it stands. SAP HANA refuses it at the next word and
    /// wants `FROM DUMMY`, the one-row table it keeps for exactly this; Oracle
    /// kept `DUAL` for the same reason until it began accepting the bare form.
    ///
    /// Answer the table's name, as a query would write it after `FROM`. Every
    /// engine that answers `None` renders exactly what it rendered before.
    fn render_one_row_source(&self) -> Option<String> {
        None
    }

    /// **How this engine reads a delimited text file whose bytes are not
    /// UTF-8**, or `None` where it states no way to.
    ///
    /// UTF-8 is the canonical form and every engine reads it, so
    /// [`delimited_file_relation`](Self::delimited_file_relation) answers for
    /// it and this is asked only about the other days. A design can name the
    /// encoding to fall back to when a file's bytes are not UTF-8, and razeri
    /// resolves that name once, to the one name the encoding standard files it
    /// under — `windows-1252`, `shift_jis`, `koi8-r`. That name arrives here,
    /// and an engine that has its own word for the same encoding translates it
    /// the way an engine translates every other name razeri hands it.
    ///
    /// Everything the returned relation owes, it owes for the same reasons
    /// [`delimited_file_relation`](Self::delimited_file_relation) says: header
    /// from the first row, every column as text, usable in a `FROM` clause.
    ///
    /// **`None` is a complete answer, and the common one.** An engine that
    /// reads no file at all says nothing here; so does an engine that reads
    /// files but has no word for this particular encoding. Razeri then declines
    /// that source by name and says what to do instead — convert the file to
    /// UTF-8, or write the load by hand — rather than pointing the engine at
    /// bytes it will read as some other language.
    ///
    /// **Answer only for encodings you have run.** An engine that accepts the
    /// name and reads the bytes as something else is worse than one that
    /// refuses the name: the first is a warehouse of plausible nonsense and the
    /// second is a sentence on a terminal.
    ///
    /// **Razeri asks it two ways.** First with a path of `''`, to learn
    /// whether your engine has a word for the encoding at all; a file it has
    /// none for is declined there. Then the read itself goes through
    /// [`delimited_file_relation_for`](Self::delimited_file_relation_for)
    /// with the file's [`encoding`](DelimitedFile::encoding) set, whose
    /// default hands a plain file back here.
    ///
    /// `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. `encoding` does not: it is a bare name, and an engine
    /// that puts it in a string literal writes the quotes itself.
    fn delimited_file_relation_in_encoding(
        &self,
        path_literal: &str,
        encoding: &str,
    ) -> Option<String> {
        let _ = (path_literal, encoding);
        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:
    ///
    /// ```rust,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 of Razeri's bulk-load grammars this engine speaks**, or `None`
    /// where it speaks none of them.
    ///
    /// The bulk-load builder writes its statement in the form named here. The
    /// default is `None`, and the builder then writes Razeri's own annotated
    /// form, which no engine runs: name a form only where your engine takes
    /// that statement as written.
    fn bulk_load_form(&self) -> Option<BulkLoadForm> {
        None
    }

    /// **The clause a view's settings are written in**, between its name and
    /// `AS` — `PostgreSQL`'s `WITH (security_barrier = true)` — or `None` where
    /// none of `settings` is this engine's, which is the default.
    ///
    /// See [`EngineSetting`]: spell the settings written for your engine and
    /// pass over the rest.
    fn render_view_options(&self, settings: &[EngineSetting<'_>]) -> Option<String> {
        let _ = settings;
        None
    }

    /// **The words a join's settings are written in**, in front of its join
    /// keyword — `ClickHouse`'s `GLOBAL ANY` — or `None` where none of
    /// `settings` is this engine's, which is the default.
    fn render_join_options(&self, settings: &[EngineSetting<'_>]) -> Option<String> {
        let _ = settings;
        None
    }

    /// **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})")
    }

    /// **One part of a date or a timestamp, as a whole number.**
    ///
    /// A design's `date_part('<part>', <column>)` hands this one of ten words,
    /// and each must answer the number named here, the same on every engine:
    ///
    /// | `field` | the number |
    /// |---|---|
    /// | `YEAR` | the year, such as 2026 |
    /// | `QUARTER` | 1 to 4 |
    /// | `MONTH` | 1 to 12 |
    /// | `ISOWEEK` | the ISO 8601 week, 1 to 53, weeks starting on Monday |
    /// | `DAY` | the day of the month, 1 to 31 |
    /// | `HOUR` | 0 to 23 |
    /// | `MINUTE` | 0 to 59 |
    /// | `SECOND` | 0 to 59, the whole second |
    /// | `ISODOW` | the ISO day of the week, Monday 1 to Sunday 7 |
    /// | `DOY` | the day of the year, 1 to 366 |
    ///
    /// The default writes `EXTRACT(<field> FROM <column>)`, which most engines
    /// refuse for `ISOWEEK`, `ISODOW` or `DOY`: override it, spelling each word
    /// your engine's way — `DATEPART(ISO_WEEK, c)` on SQL Server,
    /// `toISOWeek(c)` on `ClickHouse` — and run each of the ten on your engine.
    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 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
    }

    /// **The longest line this engine's own client reads intact from a script
    /// file**, or `None` where it reads any line.
    ///
    /// A generated statement can put a long expression on one line. An engine
    /// whose client misreads a line past some length is handed its scripts
    /// with every longer line broken between two words, outside any quoted
    /// text and outside any comment, which changes nothing the statement
    /// says.
    fn longest_script_line(&self) -> Option<usize> {
        None
    }

    /// **How this engine writes a short name for a relation.**
    ///
    /// A composed load gives a table, a view, a common table expression or a
    /// subquery a short name and then addresses it by that name for the rest
    /// of the statement. Most engines take the word `AS` in front of it, and
    /// most of those also take the name on its own. One takes only the name:
    /// `FROM orders AS src` is refused outright, in a `FROM` and again in a
    /// `MERGE`.
    ///
    /// So the two words are the dialect's to write. `relation` arrives already
    /// quoted and qualified; `alias` arrives already quoted. Nothing here
    /// changes what the statement means — only how this engine spells it.
    fn render_relation_alias(&self, relation: &str, alias: &str) -> String {
        format!("{relation} AS {alias}")
    }

    /// **Whether this engine reserves `word`**, so a name spelled that way
    /// has to be quoted to be read as a name.
    ///
    /// Razeri writes a few short names of its own inside a statement: the
    /// marker column a load's anti-join selects (`1 AS matched`), and the
    /// relation that carries it (`standing.matched`). It writes them bare,
    /// and asks this first: a word the engine reserves is written through
    /// [`render_alias`](Self::render_alias), quoted.
    ///
    /// The default is the SQL standard's list,
    /// [`SQL_STANDARD_RESERVED_WORDS`](crate::reserved_words::SQL_STANDARD_RESERVED_WORDS),
    /// in any case. An engine that reserves a word the standard leaves free
    /// answers `true` for it too, and keeps the standard's answer for the
    /// rest:
    ///
    /// ```text
    /// fn is_reserved_word(&self, word: &str) -> bool {
    ///     word.eq_ignore_ascii_case("matched")
    ///         || razeri_plugin_contract::reserved_words::is_standard_reserved_word(word)
    /// }
    /// ```
    fn is_reserved_word(&self, word: &str) -> bool {
        crate::reserved_words::is_standard_reserved_word(word)
    }

    /// **A short name Razeri gives a column or a relation inside one
    /// statement, written so this engine reads it as a name.**
    ///
    /// Bare where [`is_reserved_word`](Self::is_reserved_word) says the word
    /// is free, and through [`quote_identifier`](Self::quote_identifier)
    /// where it is reserved. Every place a statement writes the name asks
    /// this, so the name and every reference to it are spelled alike.
    fn render_alias(&self, alias: &str) -> String {
        if self.is_reserved_word(alias) { self.quote_identifier(alias) } else { alias.to_owned() }
    }

    /// **How a statement that changes the shape of the warehouse is written
    /// inside a routine's body.**
    ///
    /// A generated load empties its landing table when it is finished, and on
    /// most engines that statement stands in the body exactly as it would
    /// stand on its own. One engine runs no such statement directly in a
    /// block: `TRUNCATE TABLE …` there is a parse error, and the same words
    /// handed back to the SQL engine as a string run. `statement` arrives
    /// terminated the way the rest of the body is.
    fn render_ddl_within_routine_body(&self, statement: &str) -> String {
        statement.to_owned()
    }

    /// **How this engine empties a table and keeps it.**
    ///
    /// A generated load empties the staging table it fills before it writes
    /// the next batch into it. Most engines do that with `TRUNCATE TABLE`, and
    /// that is the default. One has no such statement and answers a syntax
    /// error at the word; it empties a table with `DELETE FROM` instead.
    ///
    /// `relation` arrives already quoted and qualified. The answer is one whole
    /// statement, ended with `;`.
    fn render_empty_table(&self, relation: &str) -> String {
        format!("TRUNCATE TABLE {relation};")
    }

    /// **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
    }

    /// **How this engine writes the condition a `MERGE` matches rows on.**
    ///
    /// Most take the condition after the word `ON` and nothing else. One
    /// requires it in parentheses and answers `ORA-00969: missing ON keyword`
    /// without them — pointing at the condition rather than at the word, which
    /// is there.
    ///
    /// `condition` is the whole predicate, which may run over several lines.
    fn render_merge_on(&self, condition: &str) -> String {
        format!("ON {condition}")
    }

    /// **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 an `UPDATE … FROM` takes a joined source whose columns carry
    /// the target's own names**, under an unqualified `SET`:
    /// `UPDATE t SET v = source.v FROM (SELECT k, v FROM s) source WHERE
    /// t.k = source.k`.
    ///
    /// Asked only where [`supports_update_from`](Self::supports_update_from)
    /// is `true`. The default is `true`. Oracle refuses that shape as
    /// ambiguous (*"ORA-00918: column ambiguously specified"*) and `PostgreSQL`
    /// refuses the qualified `SET` that would cure it, so an engine like
    /// Oracle answers `false` and Razeri writes the correlated update, which
    /// every engine runs.
    fn update_from_takes_a_source_naming_the_targets_columns(&self) -> bool {
        true
    }

    /// **The statement that tells this engine's planner what a table now
    /// holds**, after Razeri wrote it in bulk, or `None` where the engine needs
    /// none.
    ///
    /// `table` is spelled and qualified as the statement names it. Razeri runs
    /// the answer after a staging fill and at the end of every load, inside
    /// the load's transaction, so answer only with a statement your engine
    /// takes there. The default is `None`: an engine that keeps what its
    /// planner needs as it writes. `PostgreSQL` answers `ANALYZE <table>;` —
    /// with nothing to go on, its planner joins a hundred thousand rows to a
    /// hundred thousand one pair at a time.
    fn render_refresh_statistics(&self, table: &str) -> Option<String> {
        let _ = table;
        None
    }

    /// 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 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. **An engine with no statement that
    /// writes a message answers `None`**, and the line is left out of the
    /// routine rather than written as a comment or a statement it refuses.
    fn render_procedure_log(&self, level: ProcedureLogLevel, message: &str) -> Option<String> {
        let word = match level {
            ProcedureLogLevel::Debug => "DEBUG",
            ProcedureLogLevel::Info => "NOTICE",
            ProcedureLogLevel::Warning => "WARNING",
            ProcedureLogLevel::Error => "EXCEPTION",
        };
        Some(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 a one-row temporary table capturing
    /// [`Self::render_current_timestamp`], read back through a scalar
    /// subquery. Not every engine takes it: `CockroachDB` 24.3 answers
    /// *"temporary tables are only supported experimentally"*, and an engine
    /// like that overrides this with a session value of its own (`set_config`
    /// and `current_setting` there). Engines with a native variable idiom
    /// override it too (`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, moment: &str) -> InlineClockBinding {
        InlineClockBinding {
            statements: vec![
                format!("DROP TABLE IF EXISTS {name};"),
                format!("CREATE TEMPORARY TABLE {name} AS SELECT {moment} AS load_clock;"),
            ],
            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
    }

    /// **The clause written after a table's column list**, or `None` on an
    /// engine whose `CREATE TABLE` is complete at the closing parenthesis.
    ///
    /// Most engines take `CREATE TABLE t (…)` as it stands. Some refuse it
    /// without a clause the column list cannot carry — `ClickHouse` answers
    /// `ORDER BY or PRIMARY KEY clause is missing` — so its dialect answers the
    /// table's engine and sorting key here: `ENGINE = MergeTree()` and
    /// `ORDER BY (…)`, `ReplacingMergeTree(<version column>)` on a versioned
    /// table, and `ENGINE = Memory` on a temporary one. An engine with a
    /// mandatory clause of its own spells it here too.
    ///
    /// Razeri writes the answer on its own line, directly after the closing
    /// parenthesis of every `CREATE TABLE` it renders, and before the storage
    /// plan's clause from
    /// [`render_table_storage_clause`](crate::StorageRenderer::render_table_storage_clause).
    /// **What you answer here, the storage clause must not repeat**, and the
    /// reverse: two engine clauses in one statement is `Code: 62 … Syntax
    /// error` on `ClickHouse`. A sorting key belongs here rather than there,
    /// because it usually has to begin with the table's primary key, and only
    /// this method is handed it.
    ///
    /// Answer without a terminator; more than one line is fine.
    ///
    /// ```
    /// use razeri_plugin_contract::{SqlRenderer, TableSuffixRequest};
    ///
    /// struct Columnar;
    ///
    /// impl SqlRenderer for Columnar {
    ///     # fn render_data_type(&self, _: &razeri_plugin_contract::DataType) -> String { "TEXT".into() }
    ///     # fn quote_identifier(&self, name: &str) -> String { format!("\"{name}\"") }
    ///     # fn qualify_name(&self, _: Option<&str>, name: &str) -> String { self.quote_identifier(name) }
    ///     # fn render_current_timestamp(&self) -> String { "CURRENT_TIMESTAMP".into() }
    ///     fn render_table_suffix(&self, table: &TableSuffixRequest<'_>) -> Option<String> {
    ///         if table.temporary {
    ///             return Some("USING MEMORY".to_owned());
    ///         }
    ///         let key: Vec<String> =
    ///             table.primary_key.iter().map(|c| self.quote_identifier(c)).collect();
    ///         Some(format!("USING COLUMNSTORE\nSORT KEY ({})", key.join(", ")))
    ///     }
    /// }
    ///
    /// let key = ["id".to_owned()];
    /// let table = TableSuffixRequest::new().with_primary_key(&key);
    /// assert_eq!(
    ///     Columnar.render_table_suffix(&table).as_deref(),
    ///     Some("USING COLUMNSTORE\nSORT KEY (\"id\")"),
    /// );
    /// ```
    fn render_table_suffix(&self, table: &TableSuffixRequest<'_>) -> Option<String> {
        let _ = table;
        None
    }

    /// 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))
    }

    /// **This engine's canonical text for a value**: the same characters on
    /// every engine, whatever the session is set to.
    ///
    /// `expr` holds a value of `value_type`. The answer is its text as
    /// [`CanonicalText::of`](crate::CanonicalText::of) defines it for that
    /// type — `2026-01-05` for a date, `2026-01-05 12:34:56.12` for a
    /// timestamp, `2026-01-05 12:34:56.12+00:00` for a zoned moment, `10.00`
    /// for a `DECIMAL(12, 2)` ten, `10` for a floating ten, `true` for a truth
    /// value — and `NULL` where `expr` is `NULL`. `text` is the text type the value would otherwise be cast
    /// to, and every type written by the engine's own cast is cast to it.
    ///
    /// A load that refuses its rows names their values in this text, and a
    /// reconciliation writes a decimal measurement in it before comparing it
    /// with the source's by string equality. So an engine that writes a date
    /// by a format its session sets, drops a decimal's trailing zeros, writes
    /// every digit of a timestamp's precision, writes a zoned moment in the
    /// session's zone, writes a floating number to more or fewer digits, or
    /// holds a truth value as a number answers here with an explicit format. The default is the plain cast to `text`, which is the
    /// canonical text on an engine that does none of those things.
    fn render_value_text(&self, expr: &str, value_type: &DataType, text: &DataType) -> String {
        let _ = value_type;
        self.render_cast(expr, text)
    }

    /// **The functions [`Self::render_value_text`] calls, and the statements
    /// that create them**, or `None` where it calls none.
    ///
    /// An engine with no `printf` computes a floating number's text from its
    /// own arithmetic ([`computed_float_text`](crate::computed_float_text)),
    /// and that arithmetic is several thousand characters long. Written into
    /// every place a value is named, it makes a statement hard to read and a
    /// line some clients misread. So such an engine writes it once, as
    /// [`FLOAT_TEXT_FUNCTION`](crate::FLOAT_TEXT_FUNCTION) and
    /// [`SINGLE_FLOAT_TEXT_FUNCTION`](crate::SINGLE_FLOAT_TEXT_FUNCTION), and
    /// its value text calls them by those names.
    ///
    /// A generated script creates them before anything that calls them, and
    /// only where something does. The default is `None`: the engine writes
    /// every value's text inline.
    fn value_text_functions(&self) -> Option<crate::ValueTextFunctions> {
        None
    }

    /// **An expression that stops the statement with `sentence`**, where
    /// `sentence` is not `NULL`, and is `NULL` where it is.
    ///
    /// A generated load refuses rows it cannot write honestly by building a
    /// sentence about them and asking the engine for this expression. The
    /// engine's error then carries the sentence to whoever reads it. The
    /// default converts the sentence to a whole number, which most engines
    /// refuse and quote back: *Could not convert string '…' to INT64*. An
    /// engine that answers that conversion without an error spells a refusal
    /// of its own here, or says through
    /// [`DialectCapabilities::refusal_stops_the_statement`](crate::DialectCapabilities::refusal_stops_the_statement)
    /// that its refusal only warns.
    fn render_refusal(&self, sentence: &str) -> String {
        self.render_cast(sentence, &DataType::bigint())
    }

    /// **A statement that reads `relation`, changes nothing, and stops with
    /// `sentence` where a row meets `condition`** — or `None`, the default,
    /// where the engine has none, and a load's refusal stays a statement that
    /// would write and stops on [`Self::render_refusal`].
    ///
    /// `condition` is true of a row holding a value the load refuses, and
    /// `sentence` is a text expression over that row: the words the engine's
    /// error should carry, and nothing around them. A statement that only
    /// reads is one an engine may run on several workers, which a statement
    /// that writes is not; the refusal ahead of a load reads every staged row,
    /// so on a large file that is most of what it costs. And an error raised
    /// with its own message carries the sentence alone, where a failed
    /// conversion wraps it in the engine's words about a type the column is
    /// not.
    fn render_read_only_refusal(
        &self,
        relation: &str,
        condition: &str,
        sentence: &str,
    ) -> Option<String> {
        let _ = (relation, condition, sentence);
        None
    }

    /// **Whether a number written as text fits a decimal column, asked in
    /// this engine's own words** — or `None`, the default, where Razeri asks
    /// it portably: the digits stripped one `REPLACE` at a time to see what is
    /// left, and nine `LIKE` patterns, one for each digit but `0`, wherever a
    /// digit's place is asked.
    ///
    /// `text` is a text expression, the value as the file wrote it with its
    /// surrounding spaces and the marks a plain number may carry already
    /// taken out. The column is `decimal(precision, scale)`. The answer is
    /// three conditions over `text`; see [`DecimalFit`] for what each is true
    /// of. A load refuses a value too large for the column and one with more
    /// places than it keeps, in sentences of their own, rather than letting
    /// the engine cap, round or refuse it in its own words. Each condition is
    /// asked of every staged value, so an engine whose `LIKE` takes a
    /// character class, or which matches a regular expression, answers here
    /// in one or two tests where the portable form takes thirty.
    ///
    /// A try-conversion (`TRY_CONVERT`, `TRY_CAST`, `SAFE_CAST`) is no
    /// answer: it rounds a value with more places than the type keeps, so it
    /// cannot say that it has them.
    fn render_decimal_fit(&self, text: &str, precision: u8, scale: u8) -> Option<DecimalFit> {
        let _ = (text, precision, scale);
        None
    }

    /// **How many characters `expr` holds**, counted the way a person counts
    /// them: one for each character, whatever the bytes that store it, and
    /// every space inside or at either end of the value included.
    ///
    /// A reconciliation totals this over a text column and compares the total
    /// with the one razeri counted in the source file, so a value that gained
    /// a carriage return, lost its last letters or was padded on the way in
    /// shows up as a different number. `expr` is a text value; `NULL` counts
    /// as `NULL`, which a total leaves out.
    ///
    /// The default is the standard `CHAR_LENGTH`. An engine without it
    /// answers with its own function, and an engine whose usual length leaves
    /// out trailing spaces, counts bytes, or counts a character outside the
    /// basic plane as two answers with one that does none of those.
    fn render_text_length(&self, expr: &str) -> String {
        format!("CHAR_LENGTH({expr})")
    }

    /// **The unit [`render_text_length`](Self::render_text_length) counts a
    /// value of this type in**, held where `held` says.
    ///
    /// A reconciliation compares the total with one counted from the source
    /// file, and counts the file in the same unit, so the two agree and the
    /// engine is asked for nothing it does not do quickly. The default is
    /// [`TextLengthUnit::Characters`]. An engine whose length of a large
    /// object counts UTF-16 code units — a character outside the basic plane
    /// counting two — answers [`TextLengthUnit::Utf16CodeUnits`] for the types
    /// it holds as one.
    fn text_length_unit(&self, data_type: &DataType, held: HeldAs) -> TextLengthUnit {
        let _ = (data_type, held);
        TextLengthUnit::Characters
    }

    /// **The expression a load compares in place of `value`**, a column of
    /// this type held where `held` says, or `None` where this engine cannot
    /// compare such a value at all.
    ///
    /// A load looks for a row that arrives twice: it collapses the rows it
    /// reads with `SELECT DISTINCT` and counts each column's distinct values,
    /// so every column it reads is compared. The default answers `value`
    /// itself, which is right wherever the engine compares the type
    /// directly. An engine that holds the type as a large object it cannot
    /// group or compare answers `None`, and Razeri refuses such a column by
    /// name when it writes the load, saying to give it a length; or it answers
    /// an expression that stands for the value wherever two values are
    /// compared — the same text for the same value, and different text for
    /// different values.
    fn render_comparable(&self, value: &str, data_type: &DataType, held: HeldAs) -> Option<String> {
        let _ = (data_type, held);
        Some(value.to_owned())
    }

    /// **A test that is true where a value of a date or timestamp column is
    /// not written as an ISO 8601 date**, on an engine that holds such a
    /// column as text it does not check — or `None`, the default, where the
    /// engine's date type checks every value written into it.
    ///
    /// On such an engine a fill written by hand can put `17/09/2026` in a
    /// load's day column and nothing refuses it: the load matches no row, the
    /// day loads empty, and every count agrees with itself. The reconciliation
    /// counts the values this test finds, and expects none. `value` is the
    /// column as the statement names it; `data_type` is the type the design
    /// declares, a date or a timestamp.
    fn render_not_an_iso_day(&self, value: &str, data_type: &DataType) -> Option<String> {
        let _ = (value, data_type);
        None
    }

    /// **`text`, or a missing value where it is exactly one of `words`**: how
    /// a load reads a source field that holds a word meaning "no value", such
    /// as `NULL`, `n/a` or `?`.
    ///
    /// A source file names its own words for a missing value, and one design
    /// has to load the same warehouse on every engine, so a word matches
    /// letter for letter and in the same case, whatever the engine's usual
    /// comparison. `text` is a text value, already trimmed; `words` are the
    /// words as the file writes them, and the empty word is among them.
    ///
    /// The default writes each word as a standard string literal, its quotes
    /// doubled, and compares with the standard `IN`. An engine whose usual
    /// comparison ignores case or accents answers with a comparison that does
    /// not, and one whose string literals treat a backslash as an escape
    /// writes each word so that a backslash in it stays a backslash.
    fn render_missing_value(&self, text: &str, words: &[&str]) -> String {
        let listed = words
            .iter()
            .map(|word| format!("'{}'", word.replace('\'', "''")))
            .collect::<Vec<_>>()
            .join(", ");
        format!("CASE WHEN {text} IN ({listed}) THEN NULL ELSE {text} END")
    }

    /// **Read a value the source spells its own way** into `target`, which is
    /// a date or a timestamp.
    ///
    /// An import arrives with `1/1/2015` in one column and
    /// `2015-01-01T00:00:00Z` in the next, and no engine reads either of them
    /// the same way as the engine beside it. So the design states the
    /// spelling, razeri reads it once into a [`DateFormat`], and this
    /// translates that list into whatever this engine's own pattern language
    /// is — `MM/DD/YYYY`, `MM/dd/yyyy`, a style number, or a format string
    /// this engine calls its own.
    ///
    /// **A value that is not spelled that way has to come back as NULL.**
    /// razeri reads the NULL as *this row did not parse* and writes the row
    /// into the table it sets rows aside in, naming the column and the format
    /// it was told to expect. An expression that stops the load instead leaves
    /// a warehouse half-loaded over one bad row, and one that answers a
    /// different day than the value says is worse than either. An engine whose
    /// parse reads a value it cannot read — rolling the forty-fifth of a month
    /// forward rather than answering nothing — writes its own guard beside the
    /// parse; [`DateFormat::shape_pattern`] and
    /// [`DateFormat::capture_pattern`] come from the same directive list, so
    /// the guard and the parse cannot hold two opinions about one spelling.
    ///
    /// **A directive this engine cannot say is a refusal, not a guess.**
    /// [`DateFormat::translate`] hands back the first directive this engine
    /// answered nothing for, and answering `None` here is how that reaches
    /// the author — by name, at the door, rather than as a wrong day in the
    /// warehouse.
    ///
    /// `None` — the default — is this engine stating nothing about how it
    /// reads a spelled value. razeri then refuses the column and names the
    /// engine.
    fn render_parse_datetime(
        &self,
        _expr: &str,
        _format: &DateFormat,
        _target: &DataType,
    ) -> Option<String> {
        None
    }

    /// **Read a value the source writes its own way** into `target`, which is
    /// a number.
    ///
    /// A file writes a price `$2,899.99 `. The symbol, the thousands mark and
    /// the space around it are not part of the number, and no two engines
    /// agree about what to do with them — one converts the text to nothing,
    /// one to `2`, one raises. So the design states the picture, razeri reads
    /// it once into a [`NumberFormat`], and this renders the reading in
    /// whatever this engine's own words for *take this out* and *convert this*
    /// are.
    ///
    /// **A value that is not written that way has to come back as NULL.**
    /// razeri reads the NULL as *this row did not parse* and writes the row
    /// into the table it sets rows aside in, naming the column and the picture
    /// it was told to expect. An expression that stops the load instead leaves
    /// a warehouse half-loaded over one bad row, and one that answers `0` for
    /// text that was never a number is worse than either. An engine whose
    /// conversion raises, or answers a number for text that is not one, writes
    /// a guard in front of it; [`NumberFormat::shape_pattern`] is built from
    /// the same picture the marks come from, so the guard and the reading
    /// cannot hold two opinions about one spelling.
    ///
    /// `None` — the default — is this engine stating nothing about how it
    /// reads a written amount. razeri then refuses the column and names the
    /// engine. `None` is also the right answer for a target that is not a
    /// number: a picture says how an amount is written, and there is nothing
    /// else for it to be about.
    ///
    /// [`NumberFormat`]: crate::number_format::NumberFormat
    /// [`NumberFormat::shape_pattern`]: crate::number_format::NumberFormat::shape_pattern
    fn render_parse_number(
        &self,
        _expr: &str,
        _format: &NumberFormat,
        _target: &DataType,
    ) -> Option<String> {
        None
    }

    /// 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 a column's `DEFAULT` is written before its `NOT NULL`.**
    ///
    /// The default, `false`, writes `NOT NULL DEFAULT …`, which is what every
    /// engine that does not override this has always been given. An engine
    /// that refuses that order and takes only `DEFAULT … NOT NULL` answers
    /// `true`.
    fn column_default_precedes_not_null(&self) -> bool {
        false
    }

    /// 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"
    }

    /// **Whether `CREATE OR REPLACE VIEW` replaces a view that other objects
    /// read.**
    ///
    /// The default, `true`, is what most engines do, and Razeri writes each
    /// view's statement as it stands. Answer `false` for an engine that
    /// refuses to replace a view while a later view, function or procedure
    /// depends on it, and Razeri asks
    /// [`render_view_replacement`](Self::render_view_replacement) for each
    /// view instead, naming the objects that read it. See
    /// [`view_replacement`](crate::view_replacement).
    fn replaces_a_view_that_is_read(&self) -> bool {
        true
    }

    /// **The statements that make a view other objects read**, on an engine
    /// that answers `false` to
    /// [`replaces_a_view_that_is_read`](Self::replaces_a_view_that_is_read).
    ///
    /// The default drops each reader, the last made first, and then writes
    /// the view's own statement. The file makes every reader again when it
    /// reaches it. A view is dropped with
    /// [`render_drop_view`](Self::render_drop_view), a function with
    /// [`render_drop_function`](Self::render_drop_function), and a procedure
    /// with `DROP PROCEDURE IF EXISTS`; a routine's parameter types are
    /// written where
    /// [`supports_drop_function_arg_types`](Self::supports_drop_function_arg_types)
    /// says the engine takes them. Each statement but the last ends with
    /// [`statement_separator`](SqlRenderer::statement_separator); the caller
    /// ends the last.
    ///
    /// Override it for an engine that replaces such a view some other way.
    fn render_view_replacement(&self, replacement: &crate::ViewReplacement<'_>) -> String {
        let separator = self.statement_separator();
        let mut statements = String::new();
        for reader in replacement.readers {
            let types: Vec<&str> = if self.supports_drop_function_arg_types() {
                reader.parameter_types.iter().map(String::as_str).collect()
            } else {
                Vec::new()
            };
            let drop = match reader.kind {
                crate::ReaderKind::View => {
                    self.render_drop_view(reader.object(), true).map_or_else(
                        || format!("{} {}", self.render_drop_view_prefix(true), reader.relation),
                        |written| written.text().to_owned(),
                    )
                }
                crate::ReaderKind::Function => {
                    self.render_drop_function(&reader.relation, &types, true)
                }
                crate::ReaderKind::Procedure => {
                    let keyword = self.render_drop_object_keyword("procedure");
                    if types.is_empty() {
                        format!("DROP {keyword} IF EXISTS {}", reader.relation)
                    } else {
                        format!(
                            "DROP {keyword} IF EXISTS {}({})",
                            reader.relation,
                            types.join(", ")
                        )
                    }
                }
            };
            statements.push_str(drop.trim_end().trim_end_matches(';'));
            statements.push_str(separator);
        }
        statements.push_str(replacement.create);
        statements
    }

    /// 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 spelling most engines take,
    /// so a dialect that answers nothing still writes the commonest evolution
    /// there is: a column that was not there yesterday. Some engines write
    /// `ADD` without `COLUMN` and refuse this one — Firebird answers *"Token
    /// unknown"* at `COLUMN` — so run it on yours, and override this method
    /// where it is refused.
    /// 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 { .. }
            | ColumnEvolution::RequireColumn { .. } => None,
        }
    }

    /// Render the surrogate identity column — a plain, ungenerated `NOT NULL`
    /// column of the type it is given, 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 type is the engine's own word for it
    ///
    /// The word `BIGINT` is not written here, because not every engine has it:
    /// Oracle refuses it outright — `ORA-00902: invalid datatype` — so the
    /// table holding the column could not be created and nothing downstream
    /// of it could load. The shape is the decision here, a plain ungenerated
    /// column; how this engine spells a 64-bit integer is the dialect's answer
    /// to [`render_data_type`](SqlRenderer::render_data_type), asked for
    /// rather than assumed. An engine whose word for it *is* `BIGINT` gets a
    /// `BIGINT` column.
    fn render_identity_column(&self, name: &str, data_type: &DataType) -> String {
        let quoted = self.quote_identifier(name);
        let rendered = self.render_data_type(data_type);
        format!("{quoted} {rendered} 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 it was
    /// measured on 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 across the ten platforms measured, 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 every platform 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 it was measured on.
    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 every registered platform, `agnostic`
    /// included, on every rendering path, and a regression test pins it.
    ///
    /// # Why the keyword lives in here
    ///
    /// The answer carries the keyword so that the hook can **decline a clause**
    /// as well as rewrite a value. Were the caller to add `DEFAULT` in front of
    /// whatever came back, a dialect returning `""` would emit a bare dangling
    /// `DEFAULT`. The same holds 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 where a dialect
    /// translates it. [`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 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.
    ///
    /// Rendered **verbatim**, it 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 is right, and this is where it is
    /// translated.
    ///
    /// The default returns the value unchanged, so a dialect that says nothing
    /// renders the author's words as written.
    ///
    /// # 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(" ")
    }

    /// Whether `ALTER TABLE … DROP COLUMN IF EXISTS` is part of the grammar.
    ///
    /// The default [`render_drop_column`](Self::render_drop_column) reads it:
    /// where it is `false`, a drop asked to run only where the column stands
    /// is one the default cannot write.
    fn supports_alter_drop_if_exists(&self) -> bool {
        true
    }

    /// **The statement that drops one column of a table that holds rows.**
    ///
    /// `table` is spelled as the statement writes it, and `column` too.
    /// `only_where_it_stands` asks for a drop that does nothing where the
    /// column is already gone, so a file of drops that stopped part way runs
    /// again whole: Razeri asks for it on an engine that commits each
    /// statement on its own. Answer `None` where this engine cannot say
    /// that, and Razeri writes the plain drop and tells the operator to run
    /// the file again from the statement that stopped.
    ///
    /// The default writes `ALTER TABLE … DROP COLUMN …`, with `IF EXISTS`
    /// where [`supports_alter_drop_if_exists`](Self::supports_alter_drop_if_exists)
    /// says the engine takes it. An engine with neither `IF EXISTS` nor the
    /// `COLUMN` word answers in its own words: a guard over its catalogue, a
    /// prepared statement chosen by `information_schema`, or a block.
    fn render_drop_column(
        &self,
        table: WrittenObject<'_>,
        column: &str,
        only_where_it_stands: bool,
    ) -> Option<Written> {
        let relation = table.relation;
        if !only_where_it_stands {
            return Some(Written::Statement(format!(
                "ALTER TABLE {relation} DROP COLUMN {column}"
            )));
        }
        self.supports_alter_drop_if_exists().then(|| {
            Written::Statement(format!("ALTER TABLE {relation} DROP COLUMN IF EXISTS {column}"))
        })
    }

    /// **The statement that drops one of Razeri's views**, spelled as the
    /// statement writes it.
    ///
    /// `only_where_it_stands` asks for a drop that does nothing where the
    /// view is already gone. The default is
    /// [`render_drop_view_prefix`](Self::render_drop_view_prefix) and the
    /// view; an engine with no `DROP VIEW IF EXISTS` answers with a guard of
    /// its own, or `None` where it has none.
    fn render_drop_view(
        &self,
        view: WrittenObject<'_>,
        only_where_it_stands: bool,
    ) -> Option<Written> {
        Some(Written::Statement(format!(
            "{} {}",
            self.render_drop_view_prefix(only_where_it_stands),
            view.relation
        )))
    }

    /// **A `CREATE TABLE` that runs only where the table is not there yet**,
    /// on an engine whose grammar has no `CREATE TABLE IF NOT EXISTS`.
    ///
    /// A deploy runs again over the warehouse it made, so each table it makes
    /// has to pass over one that already stands. Where
    /// [`supports_if_not_exists`](Self::supports_if_not_exists) is `true` the
    /// statement says so itself and this is never asked. Where it is `false`,
    /// `create` is the whole plain statement and `table` its name as written:
    /// answer with the statement behind a question of your engine's
    /// catalogue, or `None` — the default — where you have none, and a second
    /// deploy is refused at the first table by the engine, with nothing
    /// changed.
    fn render_create_table_if_absent(
        &self,
        table: WrittenObject<'_>,
        create: &str,
    ) -> Option<Written> {
        let _ = (table, create);
        None
    }

    /// **The statement that copies a table, every row it holds, into a new
    /// table beside it.**
    ///
    /// Razeri asks for it before a change destroys data, where the operator
    /// asks to keep a copy first (`razeri evolve --rescue`): `source` is the
    /// table, `copy` the new table's name, both spelled as the statement
    /// writes them. The copy takes the source's columns and types as the
    /// engine reads them; it needs no key, no index and no constraint.
    ///
    /// The default is `CREATE TABLE … AS SELECT * FROM …`, with
    /// [`render_create_table_prefix`](Self::render_create_table_prefix) and,
    /// on its own line before `AS`, the clause
    /// [`render_table_suffix`](crate::SqlRenderer::render_table_suffix)
    /// answers for a plain table with no key — so an engine that needs an
    /// engine clause on every table has it here too. An engine with no
    /// `CREATE TABLE … AS` answers in its own words: SQL Server's
    /// `SELECT * INTO … FROM …`, or SAP HANA's `AS (…) WITH DATA`.
    fn render_copy_table(&self, source: WrittenObject<'_>, copy: WrittenObject<'_>) -> Written {
        let suffix = self
            .render_table_suffix(&TableSuffixRequest::new())
            .map(|clause| format!("\n{clause}"))
            .unwrap_or_default();
        Written::Statement(format!(
            "{} {}{suffix}\nAS SELECT * FROM {}",
            self.render_create_table_prefix(),
            copy.relation,
            source.relation
        ))
    }

    /// **The clause a table's storage settings are written in**, after its
    /// column list — SQL Server's `WITH (DATA_COMPRESSION = PAGE)` — or `None`
    /// where none of `settings` is this engine's, which is the default.
    ///
    /// See [`EngineSetting`]: spell the settings written for your engine and
    /// pass over the rest.
    fn render_table_storage_options(&self, settings: &[EngineSetting<'_>]) -> Option<String> {
        let _ = settings;
        None
    }

    // ═══════════════════════════════════════════════════════════════
    // 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 `PRIMARY KEY` is part of the grammar.**
    ///
    /// `false` on an engine that has no primary key at all — one that refuses
    /// the declaration, not one that accepts it and checks nothing (that is
    /// [`Self::constraint_enforcement`]). The key is left out of
    /// the `CREATE TABLE` and named in a comment beside it, and the loads still
    /// match rows on its columns, as they do everywhere. Default `true`.
    fn supports_primary_key_constraint(&self) -> bool {
        true
    }

    /// **Whether a `FOREIGN KEY … REFERENCES` is part of the grammar.**
    ///
    /// `false` on an engine that refuses the declaration; it is left out and
    /// named in a comment beside the table. Default `true`.
    fn supports_foreign_key_constraint(&self) -> bool {
        true
    }

    /// 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. `CockroachDB` 24.3 refuses
    /// it the same way. 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. Pass this answer to
    /// [`render_procedure_as`](crate::routine_render::render_procedure_as)
    /// when you spell a procedure through it, and it leaves the description
    /// out too.
    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
    }
}

/// **Three questions a load asks of a number written as text**, each a
/// condition over the value, for a column declared `decimal(precision,
/// scale)` ([`ExpressionRenderer::render_decimal_fit`]).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DecimalFit {
    /// True of a value written as a plain number: digits, at most one point,
    /// and at most one sign, ahead of them. It may be true of a value with no
    /// digits at all, such as the empty text or a lone point.
    pub plain: String,
    /// True where a digit other than `0` stands more places before the point
    /// than the column leaves room for, `precision - scale`, counted from the
    /// point (or from the end, where there is none). Asked of any text; false
    /// of every plain number that fits.
    pub past_room: String,
    /// True where a digit other than `0` stands more places after the point
    /// than `scale`. Asked of any text; false of every plain number that fits.
    pub past_scale: String,
}

impl DecimalFit {
    /// **The three questions as regular expressions**, each pattern handed
    /// to `matches` to be written as the engine matches one somewhere in the
    /// value (`text ~ 'pattern'`, `regexp_matches(text, 'pattern')`): a plain
    /// number is an optional sign, digits and at most one point; a digit
    /// other than `0` followed by the column's room in digits, before any
    /// point, is too large; one past the scale after the point is a place the
    /// column does not keep. The patterns hold no backslash and no quote, so
    /// they read the same under every string-literal setting.
    pub fn by_regular_expression(
        precision: u8,
        scale: u8,
        matches: impl Fn(&str) -> String,
    ) -> Self {
        let room = precision.saturating_sub(scale);
        Self {
            plain: matches("^[+-]?[0-9]*[.]?[0-9]*$"),
            past_room: matches(&format!("^[^.]*[1-9][0-9]{{{room}}}")),
            past_scale: matches(&format!("[.][0-9]{{{scale}}}[0-9]*[1-9]")),
        }
    }
}

/// **A table a procedure writes once and reads by name**
/// ([`ProcedureRenderer::render_procedure_table`]).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProcedureTable {
    /// The statements that write it, each ended for a procedure's body.
    pub statements: Vec<String>,
    /// The name the statements after them read it by.
    pub reference: String,
}

/// **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"
    }

    /// **One row holding an array becomes one row per element.**
    ///
    /// Razeri hands over the relation it is reading, the array column, and the
    /// element fields the statement needs; the engine answers with the `FROM`
    /// item that produces the rows and the expressions that read them. The
    /// three parts come back together because on at least one engine they
    /// depend on each other: its field expressions name an alias its own
    /// `FROM` item introduced.
    ///
    /// **The ordinal is one for the first element, on every engine.** Engines
    /// disagree about where an array starts — some count from one, some from
    /// zero, one answers in text — and the element's surrogate key is derived
    /// from its position. An engine answering in its own base would give one
    /// element two different keys depending on where it was stored, so the
    /// normalization belongs here, where the engine that counts from zero pays
    /// for it with one addition.
    ///
    /// `None` — the default — is this engine stating no flatten. Razeri then
    /// refuses the declaration and names the engine, rather than guessing an
    /// idiom or emitting a statement that does not run.
    fn render_flatten(&self, _request: &FlattenRequest<'_>) -> Option<Flatten> {
        None
    }
}

/// 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"
    }

    /// **Rows a procedure writes once and reads by name**: the statements,
    /// inside a procedure's body, that keep `query`'s rows in a table only
    /// this call sees, and the name the statements after them read it by —
    /// or `None`, the default, where the engine has no such table and each
    /// statement reads `query` itself.
    ///
    /// A core table's load converts its staged text into the design's types
    /// once, here, and its refusals and its write read the converted rows by
    /// name: one pass over the staged rows rather than one for each
    /// statement. `name` is a plain identifier, unique within the procedure.
    /// The table must not outlive the call, and two calls running at once
    /// must not see each other's.
    fn render_procedure_table(&self, name: &str, query: &str) -> Option<ProcedureTable> {
        let _ = (name, query);
        None
    }

    /// 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
    }

    /// **A statement that calls each of `calls` once for every row of
    /// `query`**, or `None` where this engine has none to write, the default.
    ///
    /// `query` answers one column; each row's value is held in `variable`, of
    /// the type `variable_type` spells in this engine, and each call names
    /// `variable` where it takes the value. A generated fill asks this to make
    /// a staging partition for every day a file holds before it stages a row
    /// of any, on an engine that keeps nowhere for a row whose day has no
    /// partition. Where the answer is `None`, the fill is refused by name,
    /// with the calls to make by hand.
    fn render_call_for_each_row(
        &self,
        variable: &str,
        variable_type: &str,
        query: &str,
        calls: &[String],
    ) -> Option<String> {
        let _ = (variable, variable_type, query, calls);
        None
    }
}

#[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 {}

    /// **An alias the engine reserves is quoted, and one it leaves free is
    /// not** — by the standard's list until the dialect says otherwise.
    #[test]
    fn an_alias_is_quoted_only_where_the_engine_reserves_the_word() {
        let d = TestDialect;
        assert_eq!(d.render_alias("matched"), "matched");
        assert_eq!(d.render_alias("standing"), "standing");
        assert_eq!(d.render_alias("year"), "\"year\"");
        assert_eq!(d.render_alias("VALUE"), "\"VALUE\"");
    }

    /// **A view nothing reads is made by its own statement, and a view that
    /// is read is made after its readers are dropped, the last made first.**
    #[test]
    fn a_view_that_is_read_is_made_after_its_readers_are_dropped() {
        use crate::{ReaderKind, ViewReader, ViewReplacement, WrittenObject};
        let d = TestDialect;
        let create = "CREATE OR REPLACE VIEW core.\"customers_identity_current\" AS SELECT 1";
        let view = WrittenObject::new(
            Some("core"),
            "\"customers_identity_current\"",
            "core.\"customers_identity_current\"",
        );
        assert_eq!(d.render_view_replacement(&ViewReplacement::new(view, create, &[])), create);
        let readers = [
            ViewReader::new(
                ReaderKind::Procedure,
                Some("core".to_owned()),
                "\"customers_load\"".to_owned(),
                "core.\"customers_load\"".to_owned(),
                Vec::new(),
            ),
            ViewReader::new(
                ReaderKind::Function,
                Some("core".to_owned()),
                "\"customers_as_of\"".to_owned(),
                "core.\"customers_as_of\"".to_owned(),
                vec!["TIMESTAMP".to_owned()],
            ),
            ViewReader::new(
                ReaderKind::View,
                Some("core".to_owned()),
                "\"customers_current\"".to_owned(),
                "core.\"customers_current\"".to_owned(),
                Vec::new(),
            ),
        ];
        assert_eq!(
            d.render_view_replacement(&ViewReplacement::new(view, create, &readers)),
            format!(
                "DROP PROCEDURE IF EXISTS core.\"customers_load\";\n\
                 DROP FUNCTION IF EXISTS core.\"customers_as_of\"(TIMESTAMP);\n\
                 DROP VIEW IF EXISTS core.\"customers_current\";\n\
                 {create}"
            )
        );
        assert!(d.replaces_a_view_that_is_read(), "most engines replace in place");
    }

    /// **No engine is handed the statement that requires a column until its
    /// dialect writes one.**
    #[test]
    fn requiring_a_column_is_no_statement_until_a_dialect_writes_one() {
        let data_type = DataType::boolean();
        let change = ColumnEvolution::RequireColumn {
            schema: Some("core"),
            table: "customers",
            column: "is_active",
            data_type: &data_type,
        };
        assert_eq!(change.column(), "is_active");
        assert!(TestDialect.render_column_evolution(&change).is_none());
    }

    /// 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})"))
        }
    }

    /// **A dialect that says nothing writes a value by its plain cast**, and
    /// renders exactly what it rendered before the question existed.
    #[test]
    fn a_dialect_that_states_no_value_text_casts_the_value() {
        let d: &dyn ExpressionRenderer = &TestDialect;
        for value_type in [DataType::date(), DataType::timestamp(), DataType::decimal(12, 2)] {
            assert_eq!(
                d.render_value_text("x", &value_type, &DataType::varchar(64)),
                d.render_cast("x", &DataType::varchar(64)),
            );
        }
        assert!(d.value_text_functions().is_none(), "a plain cast calls no function");
    }

    /// **A dialect that says nothing refuses by converting the sentence to a
    /// number**, which is what every engine that refuses the conversion
    /// needs.
    #[test]
    fn a_dialect_that_states_no_refusal_converts_the_sentence() {
        let d: &dyn ExpressionRenderer = &TestDialect;
        assert_eq!(d.render_refusal("s"), d.render_cast("s", &DataType::bigint()));
    }

    /// **A dialect that says nothing counts characters with the standard
    /// function.**
    #[test]
    fn a_dialect_that_states_no_text_length_counts_with_char_length() {
        let d: &dyn ExpressionRenderer = &TestDialect;
        assert_eq!(d.render_text_length("name"), "CHAR_LENGTH(name)");
    }

    /// **A dialect that says nothing reads a missing word with the standard
    /// `IN`**, each word a standard literal with its quotes doubled.
    #[test]
    fn a_dialect_that_states_no_missing_value_reading_compares_with_in() {
        let d: &dyn ExpressionRenderer = &TestDialect;
        assert_eq!(
            d.render_missing_value("TRIM(x)", &["", "NULL", "it's"]),
            "CASE WHEN TRIM(x) IN ('', 'NULL', 'it''s') THEN NULL ELSE TRIM(x) END"
        );
    }

    /// **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);
    }

    /// **A dialect that says nothing adds nothing after the column list.** The
    /// default is what every engine that takes a bare `CREATE TABLE t (…)`
    /// needs, whatever the table is.
    #[test]
    fn a_dialect_that_spells_no_table_suffix_is_asked_for_none() {
        let d: &dyn SqlRenderer = &TestDialect;
        let key = ["id".to_owned()];
        let cluster = ["region".to_owned()];
        for table in [
            TableSuffixRequest::new(),
            TableSuffixRequest::new().with_temporary(true),
            TableSuffixRequest::new()
                .with_primary_key(&key)
                .with_clustering_columns(&cluster)
                .with_version_column(Some("_loaded_at")),
        ] {
            assert_eq!(d.render_table_suffix(&table), None, "{table:?}");
        }
    }

    /// 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_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()
        );
    }

    /// **The first line break decides how a file's lines end.** A header that
    /// ends `\r\n` is a Windows file; one that ends `\n`, or a file with no
    /// line break at all, reads with a newline alone.
    #[test]
    fn the_first_line_break_decides_how_the_lines_end() {
        assert_eq!(LineEnding::of(b"id,name\r\n1,Alpha\r\n"), LineEnding::CrLf);
        assert_eq!(LineEnding::of(b"id,name\r\n1,Alpha"), LineEnding::CrLf);
        assert_eq!(LineEnding::of(b"id,name\n1,Alpha\n"), LineEnding::Lf);
        assert_eq!(LineEnding::of(b"id,name"), LineEnding::Lf);
        assert_eq!(LineEnding::of(b""), LineEnding::Lf);
        assert_eq!(LineEnding::of(b"\n"), LineEnding::Lf);
        assert_eq!(LineEnding::default(), LineEnding::Lf);
        assert_eq!(LineEnding::CrLf.as_str(), "\r\n");
        assert_eq!(LineEnding::CrLf.escaped(), "\\r\\n");
        assert_eq!(LineEnding::Lf.escaped(), "\\n");
    }

    /// **A dialect that states only the path-only read reads only a plain
    /// file.** A pipe, a quote other than `"` or a missing header is answered
    /// `None`, because the path-only read cannot be told it; a plain file
    /// reads byte for byte as before.
    #[test]
    fn the_default_reads_only_a_plain_file() {
        let d: &dyn SqlRenderer = &StatedDialect;
        let plain = DelimitedFile::new("'/data/x.csv'", "'/data'", "x.csv");
        assert!(plain.is_plain());
        assert_eq!(d.delimited_file_relation_for(&plain).as_deref(), Some("SCAN('/data/x.csv')"));
        for unplain in [
            plain.with_delimiter(FileDelimiter::Pipe),
            plain.with_quote('\''),
            plain.with_header(false),
        ] {
            assert!(!unplain.is_plain());
            assert_eq!(d.delimited_file_relation_for(&unplain), None, "{unplain:?}");
        }
        // A named encoding goes where the dialect reads one, and this dialect
        // reads none.
        assert_eq!(d.delimited_file_relation_for(&plain.with_encoding(Some("windows-1252"))), None);
    }

    /// **A file is read the default way until a `with_` method says
    /// otherwise.**
    #[test]
    fn a_new_file_is_comma_delimited_quoted_headed_and_utf8() {
        let columns = vec!["a".to_owned()];
        let file = DelimitedFile::new("'/d/x.csv'", "'/d'", "x.csv");
        assert_eq!(file.delimiter, FileDelimiter::Comma);
        assert_eq!(file.quote, '"');
        assert!(file.header && file.columns.is_empty() && file.encoding.is_none());
        assert_eq!(file.line_ending, LineEnding::Lf);
        let told = file
            .with_columns(&columns)
            .with_line_ending(LineEnding::CrLf)
            .with_delimiter(FileDelimiter::Fs)
            .with_quote('\'')
            .with_header(false)
            .with_encoding(Some("shift_jis"));
        assert_eq!(told.columns, columns.as_slice());
        assert_eq!(told.line_ending, LineEnding::CrLf);
        assert_eq!(told.delimiter, FileDelimiter::Fs);
        assert_eq!((told.quote, told.header, told.encoding), ('\'', false, Some("shift_jis")));
    }

    /// **Each delimiter is its character, its byte and its word**, and the
    /// four ASCII separators are the four control characters.
    #[test]
    fn each_delimiter_is_its_character_its_byte_and_its_word() {
        let all = [
            (FileDelimiter::Comma, ',', Some("comma")),
            (FileDelimiter::Tab, '\t', Some("tab")),
            (FileDelimiter::Pipe, '|', Some("pipe")),
            (FileDelimiter::Semicolon, ';', Some("semicolon")),
            (FileDelimiter::Fs, '\u{1c}', Some("fs")),
            (FileDelimiter::Gs, '\u{1d}', Some("gs")),
            (FileDelimiter::Rs, '\u{1e}', Some("rs")),
            (FileDelimiter::Us, '\u{1f}', Some("us")),
            (FileDelimiter::Literal('~'), '~', None),
        ];
        for (delimiter, character, word) in all {
            assert_eq!(delimiter.as_char(), character);
            assert_eq!(char::from(delimiter.as_byte()), character);
            assert_eq!(delimiter.word(), word);
            assert_eq!(delimiter.is_control(), ('\u{1c}'..='\u{1f}').contains(&character));
        }
        assert_eq!(FileDelimiter::default(), FileDelimiter::Comma);
    }
}