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
//! Snowflake Dialect
//!
//! Snowflake-specific transformations based on sqlglot patterns.
//! Key differences:
//! - TRY_ prefix for safe operations (TRY_CAST, TRY_TO_NUMBER)
//! - FLATTEN for unnesting arrays
//! - QUALIFY clause support
//! - ARRAY_CONSTRUCT, OBJECT_CONSTRUCT for arrays/objects
//! - Variant type handling
//! - Default case-insensitive identifiers (unquoted)
use super::{DialectImpl, DialectType};
use crate::error::Result;
use crate::expressions::{
AggFunc, BinaryOp, Cast, CeilFunc, DataType, Expression, Function, IntervalUnit, ListAggFunc,
Literal, UnaryFunc, VarArgFunc,
};
use crate::generator::GeneratorConfig;
use crate::tokens::TokenizerConfig;
/// Convert IntervalUnit to string for Snowflake syntax
fn interval_unit_to_str(unit: &IntervalUnit) -> String {
match unit {
IntervalUnit::Year => "YEAR".to_string(),
IntervalUnit::Quarter => "QUARTER".to_string(),
IntervalUnit::Month => "MONTH".to_string(),
IntervalUnit::Week => "WEEK".to_string(),
IntervalUnit::Day => "DAY".to_string(),
IntervalUnit::Hour => "HOUR".to_string(),
IntervalUnit::Minute => "MINUTE".to_string(),
IntervalUnit::Second => "SECOND".to_string(),
IntervalUnit::Millisecond => "MILLISECOND".to_string(),
IntervalUnit::Microsecond => "MICROSECOND".to_string(),
IntervalUnit::Nanosecond => "NANOSECOND".to_string(),
}
}
/// Snowflake dialect
pub struct SnowflakeDialect;
impl DialectImpl for SnowflakeDialect {
fn dialect_type(&self) -> DialectType {
DialectType::Snowflake
}
fn tokenizer_config(&self) -> TokenizerConfig {
let mut config = TokenizerConfig::default();
// Snowflake uses double quotes for identifiers
config.identifiers.insert('"', '"');
// Snowflake supports $$ string literals
config.quotes.insert("$$".to_string(), "$$".to_string());
// Snowflake does NOT support nested comments (per Python sqlglot)
config.nested_comments = false;
// Snowflake supports // as single-line comments (in addition to --)
config.comments.insert("//".to_string(), None);
config
}
fn generator_config(&self) -> GeneratorConfig {
use crate::generator::IdentifierQuoteStyle;
GeneratorConfig {
identifier_quote: '"',
identifier_quote_style: IdentifierQuoteStyle::DOUBLE_QUOTE,
dialect: Some(DialectType::Snowflake),
// Snowflake-specific settings from Python sqlglot
parameter_token: "$",
matched_by_source: false,
single_string_interval: true,
join_hints: false,
table_hints: false,
query_hints: false,
aggregate_filter_supported: false,
supports_table_copy: false,
collate_is_func: true,
limit_only_literals: true,
json_key_value_pair_sep: ",",
insert_overwrite: " OVERWRITE INTO",
struct_delimiter: ("(", ")"),
copy_params_are_wrapped: false,
copy_params_eq_required: true,
star_except: "EXCLUDE",
supports_exploding_projections: false,
array_concat_is_var_len: false,
supports_convert_timezone: true,
except_intersect_support_all_clause: false,
supports_median: true,
array_size_name: "ARRAY_SIZE",
supports_decode_case: true,
is_bool_allowed: false,
// Snowflake supports TRY_ prefix operations
try_supported: true,
// Snowflake supports NVL2
nvl2_supported: true,
// Snowflake uses FLATTEN for unnest
unnest_with_ordinality: false,
// Snowflake uses space before paren: ALL (subquery)
quantified_no_paren_space: false,
// Snowflake uses bracket-only array syntax: [1, 2, 3]
array_bracket_only: true,
..Default::default()
}
}
fn transform_expr(&self, expr: Expression) -> Result<Expression> {
match expr {
// ===== Data Type Mappings =====
Expression::DataType(dt) => self.transform_data_type(dt),
// ===== NOT IN transformation =====
// Snowflake treats `value NOT IN (subquery)` as `VALUE <> ALL (subquery)`
// See: https://docs.snowflake.com/en/sql-reference/functions/in
Expression::In(in_expr) if in_expr.not && in_expr.query.is_some() => {
// Transform NOT IN (subquery) -> <> ALL (subquery)
let inner = in_expr.query.unwrap();
// Wrap in Subquery so generator outputs ALL (subquery) with space
let subquery = Expression::Subquery(Box::new(crate::expressions::Subquery {
this: inner,
alias: None,
column_aliases: Vec::new(),
order_by: None,
limit: None,
offset: None,
distribute_by: None,
sort_by: None,
cluster_by: None,
lateral: false,
modifiers_inside: false,
trailing_comments: Vec::new(),
inferred_type: None,
}));
Ok(Expression::All(Box::new(
crate::expressions::QuantifiedExpr {
this: in_expr.this,
subquery,
op: Some(crate::expressions::QuantifiedOp::Neq),
},
)))
}
// NOT IN (values) -> NOT x IN (values)
Expression::In(in_expr) if in_expr.not => {
// Transform NOT x IN (values) by wrapping the In expression with not=false inside a Not
let in_without_not = crate::expressions::In {
this: in_expr.this,
expressions: in_expr.expressions,
query: in_expr.query,
not: false,
global: in_expr.global,
unnest: in_expr.unnest,
is_field: in_expr.is_field,
};
Ok(Expression::Not(Box::new(crate::expressions::UnaryOp {
this: Expression::In(Box::new(in_without_not)),
inferred_type: None,
})))
}
// ===== Interval unit expansion =====
// Expand abbreviated units in interval string values (e.g., '1 w' -> '1 WEEK')
Expression::Interval(interval) => self.transform_interval(*interval),
// ===== Null handling =====
// IFNULL -> COALESCE (both work in Snowflake, but COALESCE is standard)
Expression::IfNull(f) => Ok(Expression::Coalesce(Box::new(VarArgFunc {
original_name: None,
expressions: vec![f.this, f.expression],
inferred_type: None,
}))),
// NVL -> COALESCE (both work in Snowflake, but COALESCE is standard)
Expression::Nvl(f) => Ok(Expression::Coalesce(Box::new(VarArgFunc {
original_name: None,
expressions: vec![f.this, f.expression],
inferred_type: None,
}))),
// Coalesce with original_name (e.g., IFNULL parsed as Coalesce) -> clear original_name
Expression::Coalesce(mut f) => {
f.original_name = None;
Ok(Expression::Coalesce(f))
}
// GROUP_CONCAT -> LISTAGG in Snowflake
Expression::GroupConcat(f) => Ok(Expression::ListAgg(Box::new(ListAggFunc {
this: f.this,
separator: f.separator,
on_overflow: None,
order_by: f.order_by,
distinct: f.distinct,
filter: f.filter,
inferred_type: None,
}))),
// ===== Cast operations =====
// CAST(x AS GEOGRAPHY) -> TO_GEOGRAPHY(x)
// CAST(x AS GEOMETRY) -> TO_GEOMETRY(x)
Expression::Cast(c) => {
use crate::expressions::DataType;
// First, recursively transform the inner expression
let transformed_this = self.transform_expr(c.this)?;
match &c.to {
DataType::Geography { .. } => Ok(Expression::Function(Box::new(
Function::new("TO_GEOGRAPHY".to_string(), vec![transformed_this]),
))),
DataType::Geometry { .. } => Ok(Expression::Function(Box::new(Function::new(
"TO_GEOMETRY".to_string(),
vec![transformed_this],
)))),
_ => {
// Transform the data type
let transformed_dt = match self.transform_data_type(c.to.clone())? {
Expression::DataType(dt) => dt,
_ => c.to.clone(),
};
Ok(Expression::Cast(Box::new(Cast {
this: transformed_this,
to: transformed_dt,
double_colon_syntax: false, // Normalize :: to CAST()
trailing_comments: c.trailing_comments,
format: c.format,
default: c.default,
inferred_type: None,
})))
}
}
}
// TryCast stays as TryCast (Snowflake supports TRY_CAST)
// Recursively transform the inner expression
Expression::TryCast(c) => {
let transformed_this = self.transform_expr(c.this)?;
Ok(Expression::TryCast(Box::new(Cast {
this: transformed_this,
to: c.to,
double_colon_syntax: false, // Normalize :: to CAST()
trailing_comments: c.trailing_comments,
format: c.format,
default: c.default,
inferred_type: None,
})))
}
// SafeCast -> Cast in Snowflake (Snowflake CAST is safe by default)
// Also convert TIMESTAMP to TIMESTAMPTZ (BigQuery TIMESTAMP = tz-aware)
Expression::SafeCast(c) => {
let to = match c.to {
DataType::Timestamp { .. } => DataType::Custom {
name: "TIMESTAMPTZ".to_string(),
},
DataType::Custom { name } if name.eq_ignore_ascii_case("TIMESTAMP") => {
DataType::Custom {
name: "TIMESTAMPTZ".to_string(),
}
}
other => other,
};
let transformed_this = self.transform_expr(c.this)?;
Ok(Expression::Cast(Box::new(Cast {
this: transformed_this,
to,
double_colon_syntax: c.double_colon_syntax,
trailing_comments: c.trailing_comments,
format: c.format,
default: c.default,
inferred_type: None,
})))
}
// ===== Typed Literals -> CAST =====
// TIMESTAMP '...' -> CAST('...' AS TIMESTAMP)
Expression::Literal(lit) if matches!(lit.as_ref(), Literal::Timestamp(_)) => {
let Literal::Timestamp(s) = lit.as_ref() else {
unreachable!()
};
Ok(Expression::Cast(Box::new(Cast {
this: Expression::Literal(Box::new(Literal::String(s.clone()))),
to: DataType::Timestamp {
precision: None,
timezone: false,
},
double_colon_syntax: false,
trailing_comments: Vec::new(),
format: None,
default: None,
inferred_type: None,
})))
}
// DATE '...' -> CAST('...' AS DATE)
Expression::Literal(lit) if matches!(lit.as_ref(), Literal::Date(_)) => {
let Literal::Date(s) = lit.as_ref() else {
unreachable!()
};
Ok(Expression::Cast(Box::new(Cast {
this: Expression::Literal(Box::new(Literal::String(s.clone()))),
to: DataType::Date,
double_colon_syntax: false,
trailing_comments: Vec::new(),
format: None,
default: None,
inferred_type: None,
})))
}
// TIME '...' -> CAST('...' AS TIME)
Expression::Literal(lit) if matches!(lit.as_ref(), Literal::Time(_)) => {
let Literal::Time(s) = lit.as_ref() else {
unreachable!()
};
Ok(Expression::Cast(Box::new(Cast {
this: Expression::Literal(Box::new(Literal::String(s.clone()))),
to: DataType::Time {
precision: None,
timezone: false,
},
double_colon_syntax: false,
trailing_comments: Vec::new(),
format: None,
default: None,
inferred_type: None,
})))
}
// DATETIME '...' -> CAST('...' AS DATETIME)
Expression::Literal(lit) if matches!(lit.as_ref(), Literal::Datetime(_)) => {
let Literal::Datetime(s) = lit.as_ref() else {
unreachable!()
};
Ok(Expression::Cast(Box::new(Cast {
this: Expression::Literal(Box::new(Literal::String(s.clone()))),
to: DataType::Custom {
name: "DATETIME".to_string(),
},
double_colon_syntax: false,
trailing_comments: Vec::new(),
format: None,
default: None,
inferred_type: None,
})))
}
// ===== Pattern matching =====
// ILIKE is native to Snowflake (no transformation needed)
Expression::ILike(op) => Ok(Expression::ILike(op)),
// ===== Array operations =====
// EXPLODE -> FLATTEN in Snowflake
Expression::Explode(f) => Ok(Expression::Function(Box::new(Function::new(
"FLATTEN".to_string(),
vec![f.this],
)))),
// ExplodeOuter -> FLATTEN with OUTER => TRUE
Expression::ExplodeOuter(f) => Ok(Expression::Function(Box::new(Function::new(
"FLATTEN".to_string(),
vec![f.this],
)))),
// UNNEST -> TABLE(FLATTEN(INPUT => x)) AS _t0(seq, key, path, index, value, this)
Expression::Unnest(f) => {
// Create INPUT => x named argument
let input_arg =
Expression::NamedArgument(Box::new(crate::expressions::NamedArgument {
name: crate::expressions::Identifier::new("INPUT"),
value: f.this,
separator: crate::expressions::NamedArgSeparator::DArrow,
}));
// Create FLATTEN(INPUT => x)
let flatten = Expression::Function(Box::new(Function::new(
"FLATTEN".to_string(),
vec![input_arg],
)));
// Wrap in TABLE(...)
let table_func =
Expression::TableFromRows(Box::new(crate::expressions::TableFromRows {
this: Box::new(flatten),
alias: None,
joins: vec![],
pivots: None,
sample: None,
}));
// Add alias _t0(seq, key, path, index, value, this)
Ok(Expression::Alias(Box::new(crate::expressions::Alias {
this: table_func,
alias: crate::expressions::Identifier::new("_t0"),
column_aliases: vec![
crate::expressions::Identifier::new("seq"),
crate::expressions::Identifier::new("key"),
crate::expressions::Identifier::new("path"),
crate::expressions::Identifier::new("index"),
crate::expressions::Identifier::new("value"),
crate::expressions::Identifier::new("this"),
],
pre_alias_comments: vec![],
trailing_comments: vec![],
inferred_type: None,
})))
}
// Array constructor:
// - If bracket notation ([1, 2, 3]), preserve it in Snowflake
// - If ARRAY[...] syntax, convert to ARRAY_CONSTRUCT
Expression::ArrayFunc(arr) => {
if arr.bracket_notation {
// Keep bracket notation in Snowflake
Ok(Expression::ArrayFunc(arr))
} else {
// Convert ARRAY[...] to ARRAY_CONSTRUCT
Ok(Expression::Function(Box::new(Function::new(
"ARRAY_CONSTRUCT".to_string(),
arr.expressions,
))))
}
}
// ArrayConcat -> ARRAY_CAT
Expression::ArrayConcat(f) => Ok(Expression::Function(Box::new(Function::new(
"ARRAY_CAT".to_string(),
f.expressions,
)))),
// ArrayConcatAgg -> ARRAY_FLATTEN
Expression::ArrayConcatAgg(f) => Ok(Expression::Function(Box::new(Function::new(
"ARRAY_FLATTEN".to_string(),
vec![f.this],
)))),
// ArrayContains -> ARRAY_CONTAINS
Expression::ArrayContains(f) => Ok(Expression::Function(Box::new(Function::new(
"ARRAY_CONTAINS".to_string(),
vec![f.this, f.expression],
)))),
// ArrayIntersect -> ARRAY_INTERSECTION
Expression::ArrayIntersect(f) => Ok(Expression::Function(Box::new(Function::new(
"ARRAY_INTERSECTION".to_string(),
f.expressions,
)))),
// SortArray -> ARRAY_SORT
Expression::ArraySort(f) => Ok(Expression::Function(Box::new(Function::new(
"ARRAY_SORT".to_string(),
vec![f.this],
)))),
// StringToArray -> STRTOK_TO_ARRAY
Expression::StringToArray(f) => {
let mut args = vec![*f.this];
if let Some(expr) = f.expression {
args.push(*expr);
}
Ok(Expression::Function(Box::new(Function::new(
"STRTOK_TO_ARRAY".to_string(),
args,
))))
}
// ===== Bitwise operations =====
// BitwiseOr -> BITOR
Expression::BitwiseOr(f) => Ok(Expression::Function(Box::new(Function::new(
"BITOR".to_string(),
vec![f.left, f.right],
)))),
// BitwiseXor -> BITXOR
Expression::BitwiseXor(f) => Ok(Expression::Function(Box::new(Function::new(
"BITXOR".to_string(),
vec![f.left, f.right],
)))),
// BitwiseAnd -> BITAND
Expression::BitwiseAnd(f) => Ok(Expression::Function(Box::new(Function::new(
"BITAND".to_string(),
vec![f.left, f.right],
)))),
// BitwiseNot -> BITNOT
Expression::BitwiseNot(f) => Ok(Expression::Function(Box::new(Function::new(
"BITNOT".to_string(),
vec![f.this],
)))),
// BitwiseLeftShift -> BITSHIFTLEFT
Expression::BitwiseLeftShift(f) => Ok(Expression::Function(Box::new(Function::new(
"BITSHIFTLEFT".to_string(),
vec![f.left, f.right],
)))),
// BitwiseRightShift -> BITSHIFTRIGHT
Expression::BitwiseRightShift(f) => Ok(Expression::Function(Box::new(Function::new(
"BITSHIFTRIGHT".to_string(),
vec![f.left, f.right],
)))),
// BitwiseAndAgg -> BITAND_AGG
Expression::BitwiseAndAgg(f) => Ok(Expression::Function(Box::new(Function::new(
"BITAND_AGG".to_string(),
vec![f.this],
)))),
// BitwiseOrAgg -> BITOR_AGG
Expression::BitwiseOrAgg(f) => Ok(Expression::Function(Box::new(Function::new(
"BITOR_AGG".to_string(),
vec![f.this],
)))),
// BitwiseXorAgg -> BITXOR_AGG
Expression::BitwiseXorAgg(f) => Ok(Expression::Function(Box::new(Function::new(
"BITXOR_AGG".to_string(),
vec![f.this],
)))),
// ===== Boolean aggregates =====
// LogicalAnd -> BOOLAND_AGG
Expression::LogicalAnd(f) => Ok(Expression::Function(Box::new(Function::new(
"BOOLAND_AGG".to_string(),
vec![f.this],
)))),
// LogicalOr -> BOOLOR_AGG
Expression::LogicalOr(f) => Ok(Expression::Function(Box::new(Function::new(
"BOOLOR_AGG".to_string(),
vec![f.this],
)))),
// Booland -> BOOLAND
Expression::Booland(f) => Ok(Expression::Function(Box::new(Function::new(
"BOOLAND".to_string(),
vec![*f.this, *f.expression],
)))),
// Boolor -> BOOLOR
Expression::Boolor(f) => Ok(Expression::Function(Box::new(Function::new(
"BOOLOR".to_string(),
vec![*f.this, *f.expression],
)))),
// Xor -> BOOLXOR
Expression::Xor(f) => {
let mut args = Vec::new();
if let Some(this) = f.this {
args.push(*this);
}
if let Some(expr) = f.expression {
args.push(*expr);
}
Ok(Expression::Function(Box::new(Function::new(
"BOOLXOR".to_string(),
args,
))))
}
// ===== Date/time functions =====
// DayOfMonth -> DAYOFMONTH
Expression::DayOfMonth(f) => Ok(Expression::Function(Box::new(Function::new(
"DAYOFMONTH".to_string(),
vec![f.this],
)))),
// DayOfWeek -> DAYOFWEEK
Expression::DayOfWeek(f) => Ok(Expression::Function(Box::new(Function::new(
"DAYOFWEEK".to_string(),
vec![f.this],
)))),
// DayOfWeekIso -> DAYOFWEEKISO
Expression::DayOfWeekIso(f) => Ok(Expression::Function(Box::new(Function::new(
"DAYOFWEEKISO".to_string(),
vec![f.this],
)))),
// DayOfYear -> DAYOFYEAR
Expression::DayOfYear(f) => Ok(Expression::Function(Box::new(Function::new(
"DAYOFYEAR".to_string(),
vec![f.this],
)))),
// WeekOfYear -> WEEK (Snowflake native function)
Expression::WeekOfYear(f) => Ok(Expression::Function(Box::new(Function::new(
"WEEK".to_string(),
vec![f.this],
)))),
// YearOfWeek -> YEAROFWEEK
Expression::YearOfWeek(f) => Ok(Expression::Function(Box::new(Function::new(
"YEAROFWEEK".to_string(),
vec![f.this],
)))),
// YearOfWeekIso -> YEAROFWEEKISO
Expression::YearOfWeekIso(f) => Ok(Expression::Function(Box::new(Function::new(
"YEAROFWEEKISO".to_string(),
vec![f.this],
)))),
// ByteLength -> OCTET_LENGTH
Expression::ByteLength(f) => Ok(Expression::Function(Box::new(Function::new(
"OCTET_LENGTH".to_string(),
vec![f.this],
)))),
// TimestampDiff -> TIMESTAMPDIFF
Expression::TimestampDiff(f) => {
let mut args = vec![];
// If unit is set (from cross-dialect normalize), use unit as first arg, this as second, expression as third
if let Some(ref unit_str) = f.unit {
args.push(Expression::Identifier(crate::expressions::Identifier::new(
unit_str.clone(),
)));
args.push(*f.this);
args.push(*f.expression);
} else {
args.push(*f.this);
args.push(*f.expression);
}
Ok(Expression::Function(Box::new(Function::new(
"TIMESTAMPDIFF".to_string(),
args,
))))
}
// TimestampAdd -> TIMESTAMPADD
Expression::TimestampAdd(f) => {
let mut args = vec![];
if let Some(ref unit_str) = f.unit {
args.push(Expression::Identifier(crate::expressions::Identifier::new(
unit_str.clone(),
)));
args.push(*f.this);
args.push(*f.expression);
} else {
args.push(*f.this);
args.push(*f.expression);
}
Ok(Expression::Function(Box::new(Function::new(
"TIMESTAMPADD".to_string(),
args,
))))
}
// ToArray -> TO_ARRAY
Expression::ToArray(f) => Ok(Expression::Function(Box::new(Function::new(
"TO_ARRAY".to_string(),
vec![f.this],
)))),
// DateAdd -> DATEADD (with unit, amount, date order)
Expression::DateAdd(f) => {
let unit_str = interval_unit_to_str(&f.unit);
let unit = Expression::Identifier(crate::expressions::Identifier {
name: unit_str,
quoted: false,
trailing_comments: Vec::new(),
span: None,
});
Ok(Expression::Function(Box::new(Function::new(
"DATEADD".to_string(),
vec![unit, f.interval, f.this],
))))
}
// DateSub -> DATEADD with negated amount: val * -1
Expression::DateSub(f) => {
let unit_str = interval_unit_to_str(&f.unit);
let unit = Expression::Identifier(crate::expressions::Identifier {
name: unit_str,
quoted: false,
trailing_comments: Vec::new(),
span: None,
});
// Negate using val * -1 format (matching Python sqlglot output)
let neg_expr = Expression::Mul(Box::new(crate::expressions::BinaryOp::new(
f.interval,
Expression::Neg(Box::new(crate::expressions::UnaryOp {
this: Expression::number(1),
inferred_type: None,
})),
)));
Ok(Expression::Function(Box::new(Function::new(
"DATEADD".to_string(),
vec![unit, neg_expr, f.this],
))))
}
// DateDiff -> DATEDIFF
Expression::DateDiff(f) => {
let unit_str =
interval_unit_to_str(&f.unit.unwrap_or(crate::expressions::IntervalUnit::Day));
let unit = Expression::Identifier(crate::expressions::Identifier {
name: unit_str,
quoted: false,
trailing_comments: Vec::new(),
span: None,
});
Ok(Expression::Function(Box::new(Function::new(
"DATEDIFF".to_string(),
vec![unit, f.expression, f.this],
))))
}
// ===== String functions =====
// StringAgg -> LISTAGG in Snowflake
Expression::StringAgg(f) => {
let mut args = vec![f.this.clone()];
if let Some(separator) = &f.separator {
args.push(separator.clone());
}
Ok(Expression::Function(Box::new(Function::new(
"LISTAGG".to_string(),
args,
))))
}
// StartsWith -> STARTSWITH
Expression::StartsWith(f) => Ok(Expression::Function(Box::new(Function::new(
"STARTSWITH".to_string(),
vec![f.this, f.expression],
)))),
// EndsWith -> keep as EndsWith AST node; generator outputs per-dialect
Expression::EndsWith(f) => Ok(Expression::EndsWith(f)),
// Stuff -> INSERT
Expression::Stuff(f) => {
let mut args = vec![*f.this];
if let Some(start) = f.start {
args.push(*start);
}
if let Some(length) = f.length {
args.push(Expression::number(length));
}
args.push(*f.expression);
Ok(Expression::Function(Box::new(Function::new(
"INSERT".to_string(),
args,
))))
}
// ===== Hash functions =====
// SHA -> SHA1
Expression::SHA(f) => Ok(Expression::Function(Box::new(Function::new(
"SHA1".to_string(),
vec![f.this],
)))),
// SHA1Digest -> SHA1_BINARY
Expression::SHA1Digest(f) => Ok(Expression::Function(Box::new(Function::new(
"SHA1_BINARY".to_string(),
vec![f.this],
)))),
// SHA2Digest -> SHA2_BINARY
Expression::SHA2Digest(f) => Ok(Expression::Function(Box::new(Function::new(
"SHA2_BINARY".to_string(),
vec![*f.this],
)))),
// MD5Digest -> MD5_BINARY
Expression::MD5Digest(f) => Ok(Expression::Function(Box::new(Function::new(
"MD5_BINARY".to_string(),
vec![*f.this],
)))),
// MD5NumberLower64 -> MD5_NUMBER_LOWER64
Expression::MD5NumberLower64(f) => Ok(Expression::Function(Box::new(Function::new(
"MD5_NUMBER_LOWER64".to_string(),
vec![f.this],
)))),
// MD5NumberUpper64 -> MD5_NUMBER_UPPER64
Expression::MD5NumberUpper64(f) => Ok(Expression::Function(Box::new(Function::new(
"MD5_NUMBER_UPPER64".to_string(),
vec![f.this],
)))),
// ===== Vector functions =====
// CosineDistance -> VECTOR_COSINE_SIMILARITY
Expression::CosineDistance(f) => Ok(Expression::Function(Box::new(Function::new(
"VECTOR_COSINE_SIMILARITY".to_string(),
vec![*f.this, *f.expression],
)))),
// DotProduct -> VECTOR_INNER_PRODUCT
Expression::DotProduct(f) => Ok(Expression::Function(Box::new(Function::new(
"VECTOR_INNER_PRODUCT".to_string(),
vec![*f.this, *f.expression],
)))),
// EuclideanDistance -> VECTOR_L2_DISTANCE
Expression::EuclideanDistance(f) => Ok(Expression::Function(Box::new(Function::new(
"VECTOR_L2_DISTANCE".to_string(),
vec![*f.this, *f.expression],
)))),
// ManhattanDistance -> VECTOR_L1_DISTANCE
Expression::ManhattanDistance(f) => Ok(Expression::Function(Box::new(Function::new(
"VECTOR_L1_DISTANCE".to_string(),
vec![*f.this, *f.expression],
)))),
// ===== JSON/Struct functions =====
// JSONFormat -> TO_JSON
Expression::JSONFormat(f) => {
let mut args = Vec::new();
if let Some(this) = f.this {
args.push(*this);
}
Ok(Expression::Function(Box::new(Function::new(
"TO_JSON".to_string(),
args,
))))
}
// JSONKeys -> OBJECT_KEYS
Expression::JSONKeys(f) => Ok(Expression::Function(Box::new(Function::new(
"OBJECT_KEYS".to_string(),
vec![*f.this],
)))),
// GetExtract -> GET
Expression::GetExtract(f) => Ok(Expression::Function(Box::new(Function::new(
"GET".to_string(),
vec![*f.this, *f.expression],
)))),
// StarMap -> OBJECT_CONSTRUCT
Expression::StarMap(f) => Ok(Expression::Function(Box::new(Function::new(
"OBJECT_CONSTRUCT".to_string(),
vec![f.this, f.expression],
)))),
// LowerHex -> TO_CHAR
Expression::LowerHex(f) => Ok(Expression::Function(Box::new(Function::new(
"TO_CHAR".to_string(),
vec![f.this],
)))),
// Skewness -> SKEW
Expression::Skewness(f) => Ok(Expression::Function(Box::new(Function::new(
"SKEW".to_string(),
vec![f.this],
)))),
// StPoint -> ST_MAKEPOINT
Expression::StPoint(f) => Ok(Expression::Function(Box::new(Function::new(
"ST_MAKEPOINT".to_string(),
vec![*f.this, *f.expression],
)))),
// FromTimeZone -> CONVERT_TIMEZONE
Expression::FromTimeZone(f) => Ok(Expression::Function(Box::new(Function::new(
"CONVERT_TIMEZONE".to_string(),
vec![*f.this],
)))),
// ===== Conversion functions =====
// Unhex -> HEX_DECODE_BINARY
Expression::Unhex(f) => Ok(Expression::Function(Box::new(Function::new(
"HEX_DECODE_BINARY".to_string(),
vec![*f.this],
)))),
// UnixToTime -> TO_TIMESTAMP
Expression::UnixToTime(f) => {
let mut args = vec![*f.this];
if let Some(scale) = f.scale {
args.push(Expression::number(scale));
}
Ok(Expression::Function(Box::new(Function::new(
"TO_TIMESTAMP".to_string(),
args,
))))
}
// ===== Conditional =====
// IfFunc -> keep as IfFunc with IFF name for Snowflake
Expression::IfFunc(f) => Ok(Expression::IfFunc(Box::new(crate::expressions::IfFunc {
condition: f.condition,
true_value: f.true_value,
false_value: Some(
f.false_value
.unwrap_or(Expression::Null(crate::expressions::Null)),
),
original_name: Some("IFF".to_string()),
inferred_type: None,
}))),
// ===== Aggregate functions =====
// ApproxDistinct -> APPROX_COUNT_DISTINCT
Expression::ApproxDistinct(f) => Ok(Expression::Function(Box::new(Function::new(
"APPROX_COUNT_DISTINCT".to_string(),
vec![f.this],
)))),
// ArgMax -> MAX_BY
Expression::ArgMax(f) => Ok(Expression::Function(Box::new(Function::new(
"MAX_BY".to_string(),
vec![*f.this, *f.expression],
)))),
// ArgMin -> MIN_BY
Expression::ArgMin(f) => Ok(Expression::Function(Box::new(Function::new(
"MIN_BY".to_string(),
vec![*f.this, *f.expression],
)))),
// ===== Random =====
// RANDOM is native to Snowflake - keep as-is
Expression::Random(_) => Ok(Expression::Random(crate::expressions::Random)),
// Rand - keep as-is (generator outputs RANDOM for Snowflake)
Expression::Rand(r) => Ok(Expression::Rand(r)),
// ===== UUID =====
// Uuid -> keep as Uuid node; generator will output UUID_STRING for Snowflake
Expression::Uuid(u) => Ok(Expression::Uuid(u)),
// ===== Map/Object =====
// Map -> OBJECT_CONSTRUCT
Expression::Map(f) => Ok(Expression::Function(Box::new(Function::new(
"OBJECT_CONSTRUCT".to_string(),
f.keys
.into_iter()
.zip(f.values.into_iter())
.flat_map(|(k, v)| vec![k, v])
.collect(),
)))),
// MapFunc (curly brace syntax) -> OBJECT_CONSTRUCT
Expression::MapFunc(f) => Ok(Expression::Function(Box::new(Function::new(
"OBJECT_CONSTRUCT".to_string(),
f.keys
.into_iter()
.zip(f.values.into_iter())
.flat_map(|(k, v)| vec![k, v])
.collect(),
)))),
// VarMap -> OBJECT_CONSTRUCT
Expression::VarMap(f) => Ok(Expression::Function(Box::new(Function::new(
"OBJECT_CONSTRUCT".to_string(),
f.keys
.into_iter()
.zip(f.values.into_iter())
.flat_map(|(k, v)| vec![k, v])
.collect(),
)))),
// ===== JSON =====
// JSONObject -> OBJECT_CONSTRUCT_KEEP_NULL
Expression::JsonObject(f) => Ok(Expression::Function(Box::new(Function::new(
"OBJECT_CONSTRUCT_KEEP_NULL".to_string(),
f.pairs.into_iter().flat_map(|(k, v)| vec![k, v]).collect(),
)))),
// JSONExtractScalar -> JSON_EXTRACT_PATH_TEXT
Expression::JsonExtractScalar(f) => Ok(Expression::Function(Box::new(Function::new(
"JSON_EXTRACT_PATH_TEXT".to_string(),
vec![f.this, f.path],
)))),
// ===== Struct =====
// Struct -> OBJECT_CONSTRUCT
Expression::Struct(f) => Ok(Expression::Function(Box::new(Function::new(
"OBJECT_CONSTRUCT".to_string(),
f.fields
.into_iter()
.flat_map(|(name, expr)| {
let key = match name {
Some(n) => Expression::string(n),
None => Expression::Null(crate::expressions::Null),
};
vec![key, expr]
})
.collect(),
)))),
// ===== JSON Path =====
// JSONPathRoot -> empty string ($ is implicit in Snowflake)
Expression::JSONPathRoot(_) => Ok(Expression::Literal(Box::new(
crate::expressions::Literal::String(String::new()),
))),
// ===== VarSamp -> VARIANCE (Snowflake) =====
// Snowflake uses VARIANCE instead of VAR_SAMP
Expression::VarSamp(agg) => Ok(Expression::Variance(agg)),
// ===== VarPop -> keep as VarPop =====
// The generator handles dialect-specific naming (VARIANCE_POP for Snowflake)
Expression::VarPop(agg) => Ok(Expression::VarPop(agg)),
// ===== EXTRACT -> DATE_PART =====
// Snowflake uses DATE_PART instead of EXTRACT
Expression::Extract(f) => {
use crate::expressions::DateTimeField;
// Recursively transform the inner expression (e.g., CAST(... AS TIMESTAMP_NTZ) -> CAST(... AS TIMESTAMPNTZ))
let transformed_this = self.transform_expr(f.this)?;
let field_name = match &f.field {
DateTimeField::Year => "YEAR",
DateTimeField::Month => "MONTH",
DateTimeField::Day => "DAY",
DateTimeField::Hour => "HOUR",
DateTimeField::Minute => "MINUTE",
DateTimeField::Second => "SECOND",
DateTimeField::Millisecond => "MILLISECOND",
DateTimeField::Microsecond => "MICROSECOND",
DateTimeField::Week => "WEEK",
DateTimeField::WeekWithModifier(m) => {
return Ok(Expression::Function(Box::new(Function::new(
"DATE_PART".to_string(),
vec![
Expression::Identifier(crate::expressions::Identifier {
name: format!("WEEK({})", m),
quoted: false,
trailing_comments: Vec::new(),
span: None,
}),
transformed_this,
],
))))
}
DateTimeField::DayOfWeek => "DAYOFWEEK",
DateTimeField::DayOfYear => "DAYOFYEAR",
DateTimeField::Quarter => "QUARTER",
DateTimeField::Epoch => "EPOCH",
DateTimeField::Timezone => "TIMEZONE",
DateTimeField::TimezoneHour => "TIMEZONE_HOUR",
DateTimeField::TimezoneMinute => "TIMEZONE_MINUTE",
DateTimeField::Date => "DATE",
DateTimeField::Time => "TIME",
DateTimeField::Custom(s) => {
// Map common EXTRACT field names to Snowflake DATE_PART names
match s.to_uppercase().as_str() {
"DAYOFMONTH" => "DAY",
"DOW" => "DAYOFWEEK",
"DOY" => "DAYOFYEAR",
"ISODOW" => "DAYOFWEEKISO",
"EPOCH_SECOND" | "EPOCH_SECONDS" => "EPOCH_SECOND",
"EPOCH_MILLISECOND" | "EPOCH_MILLISECONDS" => "EPOCH_MILLISECOND",
"EPOCH_MICROSECOND" | "EPOCH_MICROSECONDS" => "EPOCH_MICROSECOND",
"EPOCH_NANOSECOND" | "EPOCH_NANOSECONDS" => "EPOCH_NANOSECOND",
_ => {
return {
let field_ident =
Expression::Identifier(crate::expressions::Identifier {
name: s.to_string(),
quoted: false,
trailing_comments: Vec::new(),
span: None,
});
Ok(Expression::Function(Box::new(Function::new(
"DATE_PART".to_string(),
vec![field_ident, transformed_this],
))))
}
}
}
}
};
let field_ident = Expression::Identifier(crate::expressions::Identifier {
name: field_name.to_string(),
quoted: false,
trailing_comments: Vec::new(),
span: None,
});
Ok(Expression::Function(Box::new(Function::new(
"DATE_PART".to_string(),
vec![field_ident, transformed_this],
))))
}
// Generic function transformations
Expression::Function(f) => self.transform_function(*f),
// SUM - recursively transform inner expression
Expression::Sum(mut agg) => {
agg.this = self.transform_expr(agg.this)?;
Ok(Expression::Sum(agg))
}
// Generic aggregate function transformations
Expression::AggregateFunction(f) => self.transform_aggregate_function(f),
// Handle NamedArgument - recursively transform the value
Expression::NamedArgument(na) => {
let transformed_value = self.transform_expr(na.value)?;
Ok(Expression::NamedArgument(Box::new(
crate::expressions::NamedArgument {
name: na.name,
value: transformed_value,
separator: na.separator,
},
)))
}
// Handle CreateTable - transform column data types and default/computed expressions
Expression::CreateTable(mut ct) => {
for col in &mut ct.columns {
if let Expression::DataType(new_dt) =
self.transform_data_type(col.data_type.clone())?
{
col.data_type = new_dt;
}
// Also transform computed/default expressions (e.g., AS (parse_json(x):COL3::number))
if let Some(default_expr) = col.default.take() {
col.default = Some(self.transform_expr(default_expr)?);
}
// Transform expressions in column constraints (computed columns)
for constraint in &mut col.constraints {
if let crate::expressions::ColumnConstraint::ComputedColumn(cc) = constraint
{
let transformed = self.transform_expr(*cc.expression.clone())?;
cc.expression = Box::new(transformed);
}
}
}
// For EXTERNAL tables, convert with_properties to Raw properties
// with proper Snowflake formatting (no WITH wrapper, specific key casing)
if ct.table_modifier.as_deref() == Some("EXTERNAL")
&& !ct.with_properties.is_empty()
{
for (key, value) in ct.with_properties.drain(..) {
let formatted = Self::format_external_table_property(&key, &value);
ct.properties
.push(Expression::Raw(crate::expressions::Raw { sql: formatted }));
}
}
Ok(Expression::CreateTable(ct))
}
// Handle AlterTable - transform column data types in ADD operations
Expression::AlterTable(mut at) => {
for action in &mut at.actions {
if let crate::expressions::AlterTableAction::AddColumn { column, .. } = action {
if let Expression::DataType(new_dt) =
self.transform_data_type(column.data_type.clone())?
{
column.data_type = new_dt;
}
}
}
Ok(Expression::AlterTable(at))
}
// Handle Table reference - transform HistoricalData (AT/BEFORE time travel clauses)
Expression::Table(mut t) => {
if let Some(when) = t.when.take() {
// Recursively transform the expression inside HistoricalData
let transformed_expr = self.transform_expr(*when.expression)?;
t.when = Some(Box::new(crate::expressions::HistoricalData {
this: when.this,
kind: when.kind,
expression: Box::new(transformed_expr),
}));
}
Ok(Expression::Table(t))
}
// Handle Subscript - recursively transform inner expression
Expression::Subscript(s) => {
let transformed_this = self.transform_expr(s.this)?;
let transformed_index = self.transform_expr(s.index)?;
Ok(Expression::Subscript(Box::new(
crate::expressions::Subscript {
this: transformed_this,
index: transformed_index,
},
)))
}
// Recursively transform parenthesized expressions
Expression::Paren(p) => {
let transformed = self.transform_expr(p.this)?;
Ok(Expression::Paren(Box::new(crate::expressions::Paren {
this: transformed,
trailing_comments: p.trailing_comments,
})))
}
// ===== ORDER BY null ordering normalization =====
// Snowflake is nulls_are_large: ASC defaults to NULLS LAST, DESC defaults to NULLS FIRST
// Fill in implicit nulls_first so target dialects can properly strip/add as needed
Expression::Select(mut select) => {
if let Some(ref mut order) = select.order_by {
for ord in &mut order.expressions {
if ord.nulls_first.is_none() {
ord.nulls_first = Some(ord.desc);
}
}
}
Ok(Expression::Select(select))
}
// Fill in NULLS ordering for window function ORDER BY clauses
Expression::WindowFunction(mut wf) => {
for ord in &mut wf.over.order_by {
if ord.nulls_first.is_none() {
ord.nulls_first = Some(ord.desc);
}
}
Ok(Expression::WindowFunction(wf))
}
// Also handle Expression::Window (WindowSpec)
Expression::Window(mut w) => {
for ord in &mut w.order_by {
if ord.nulls_first.is_none() {
ord.nulls_first = Some(ord.desc);
}
}
Ok(Expression::Window(w))
}
// LATERAL FLATTEN: add default column aliases (SEQ, KEY, PATH, INDEX, VALUE, THIS)
Expression::Lateral(mut lat) => {
// Check if the inner expression is a FLATTEN function
let is_flatten = match lat.this.as_ref() {
Expression::Function(f) => f.name.to_uppercase() == "FLATTEN",
_ => false,
};
if is_flatten && lat.column_aliases.is_empty() {
// Add default column aliases
lat.column_aliases = vec![
"SEQ".to_string(),
"KEY".to_string(),
"PATH".to_string(),
"INDEX".to_string(),
"VALUE".to_string(),
"THIS".to_string(),
];
// If no alias, add _flattened
if lat.alias.is_none() {
lat.alias = Some("_flattened".to_string());
}
}
Ok(Expression::Lateral(lat))
}
// Pass through everything else
_ => Ok(expr),
}
}
}
impl SnowflakeDialect {
/// Format a Snowflake external table property for output.
/// Some properties like LOCATION and FILE_FORMAT are uppercased keywords.
fn format_external_table_property(key: &str, value: &str) -> String {
let lower_key = key.to_lowercase();
match lower_key.as_str() {
"location" => format!("LOCATION={}", value),
"file_format" => {
// Format file_format value: remove spaces around =, uppercase booleans
let formatted_value = Self::format_file_format_value(value);
format!("FILE_FORMAT={}", formatted_value)
}
_ => format!("{}={}", key, value),
}
}
/// Format file_format property value:
/// - Remove spaces around = signs
/// - Uppercase boolean values (false -> FALSE, true -> TRUE)
fn format_file_format_value(value: &str) -> String {
if !value.starts_with('(') {
return value.to_string();
}
// Strip outer parens, process inner key=value pairs
let inner = value[1..value.len() - 1].trim();
// Parse space-separated key=value pairs (may have spaces around =)
let mut result = String::from("(");
let mut parts: Vec<String> = Vec::new();
// Split by whitespace and reconstruct key=value pairs
let tokens: Vec<&str> = inner.split_whitespace().collect();
let mut i = 0;
while i < tokens.len() {
let token = tokens[i];
if i + 2 < tokens.len() && tokens[i + 1] == "=" {
// key = value pattern
let val = Self::format_property_value(tokens[i + 2]);
parts.push(format!("{}={}", token, val));
i += 3;
} else if token.contains('=') {
// key=value already joined
let eq_pos = token.find('=').unwrap();
let k = &token[..eq_pos];
let v = Self::format_property_value(&token[eq_pos + 1..]);
parts.push(format!("{}={}", k, v));
i += 1;
} else {
parts.push(token.to_string());
i += 1;
}
}
result.push_str(&parts.join(" "));
result.push(')');
result
}
/// Format a property value - uppercase boolean literals
fn format_property_value(value: &str) -> String {
match value.to_lowercase().as_str() {
"true" => "TRUE".to_string(),
"false" => "FALSE".to_string(),
_ => value.to_string(),
}
}
/// Transform data types according to Snowflake TYPE_MAPPING
fn transform_data_type(&self, dt: crate::expressions::DataType) -> Result<Expression> {
use crate::expressions::DataType;
let transformed = match dt {
// TEXT -> VARCHAR
DataType::Text => DataType::VarChar {
length: None,
parenthesized_length: false,
},
// STRUCT -> OBJECT
DataType::Struct { fields, .. } => {
// Snowflake uses OBJECT for struct types
let _ = fields; // Snowflake OBJECT doesn't preserve field names in the same way
DataType::Custom {
name: "OBJECT".to_string(),
}
}
// Custom type transformations
DataType::Custom { name } => {
let upper_name = name.to_uppercase();
match upper_name.as_str() {
// NVARCHAR -> VARCHAR (SQL Server type)
"NVARCHAR" | "NCHAR" | "NATIONAL CHARACTER VARYING" | "NATIONAL CHAR" => {
DataType::VarChar {
length: None,
parenthesized_length: false,
}
}
// STRING -> VARCHAR (Snowflake accepts both, but normalizes to VARCHAR)
"STRING" => DataType::VarChar {
length: None,
parenthesized_length: false,
},
// BIGDECIMAL -> DOUBLE
"BIGDECIMAL" => DataType::Double {
precision: None,
scale: None,
},
// NESTED -> OBJECT
"NESTED" => DataType::Custom {
name: "OBJECT".to_string(),
},
// BYTEINT -> INT
"BYTEINT" => DataType::Int {
length: None,
integer_spelling: false,
},
// CHAR VARYING -> VARCHAR
"CHAR VARYING" | "CHARACTER VARYING" => DataType::VarChar {
length: None,
parenthesized_length: false,
},
// SQL_DOUBLE -> DOUBLE
"SQL_DOUBLE" => DataType::Double {
precision: None,
scale: None,
},
// SQL_VARCHAR -> VARCHAR
"SQL_VARCHAR" => DataType::VarChar {
length: None,
parenthesized_length: false,
},
// TIMESTAMP_NTZ -> TIMESTAMPNTZ (normalize underscore form)
"TIMESTAMP_NTZ" => DataType::Custom {
name: "TIMESTAMPNTZ".to_string(),
},
// TIMESTAMP_LTZ -> TIMESTAMPLTZ (normalize underscore form)
"TIMESTAMP_LTZ" => DataType::Custom {
name: "TIMESTAMPLTZ".to_string(),
},
// TIMESTAMP_TZ -> TIMESTAMPTZ (normalize underscore form)
"TIMESTAMP_TZ" => DataType::Custom {
name: "TIMESTAMPTZ".to_string(),
},
// NCHAR VARYING -> VARCHAR
"NCHAR VARYING" => DataType::VarChar {
length: None,
parenthesized_length: false,
},
// NUMBER -> DECIMAL(38, 0) (Snowflake's default NUMBER is DECIMAL(38, 0))
"NUMBER" => DataType::Decimal {
precision: Some(38),
scale: Some(0),
},
_ if name.starts_with("NUMBER(") => {
// NUMBER(precision, scale) -> DECIMAL(precision, scale)
// Parse: "NUMBER(38, 0)" -> precision=38, scale=0
let inner = &name[7..name.len() - 1]; // strip "NUMBER(" and ")"
let parts: Vec<&str> = inner.split(',').map(|s| s.trim()).collect();
let precision = parts.first().and_then(|p| p.parse::<u32>().ok());
let scale = parts.get(1).and_then(|s| s.parse::<u32>().ok());
DataType::Decimal { precision, scale }
}
_ => DataType::Custom { name },
}
}
// DECIMAL without precision -> DECIMAL(38, 0) (Snowflake default)
DataType::Decimal {
precision: None,
scale: None,
} => DataType::Decimal {
precision: Some(38),
scale: Some(0),
},
// FLOAT -> DOUBLE (Snowflake FLOAT is actually 64-bit DOUBLE)
DataType::Float { .. } => DataType::Double {
precision: None,
scale: None,
},
// Keep all other types as-is (Snowflake is quite flexible)
other => other,
};
Ok(Expression::DataType(transformed))
}
/// Map date part abbreviation to canonical form (from Python SQLGlot DATE_PART_MAPPING)
fn map_date_part(abbr: &str) -> Option<&'static str> {
match abbr.to_uppercase().as_str() {
// Year
"Y" | "YY" | "YYY" | "YYYY" | "YR" | "YEARS" | "YRS" => Some("YEAR"),
// Month
"MM" | "MON" | "MONS" | "MONTHS" => Some("MONTH"),
// Day
"D" | "DD" | "DAYS" | "DAYOFMONTH" => Some("DAY"),
// Day of week
"DAY OF WEEK" | "WEEKDAY" | "DOW" | "DW" => Some("DAYOFWEEK"),
"WEEKDAY_ISO" | "DOW_ISO" | "DW_ISO" | "DAYOFWEEK_ISO" => Some("DAYOFWEEKISO"),
// Day of year
"DAY OF YEAR" | "DOY" | "DY" => Some("DAYOFYEAR"),
// Week
"W" | "WK" | "WEEKOFYEAR" | "WOY" | "WY" => Some("WEEK"),
"WEEK_ISO" | "WEEKOFYEARISO" | "WEEKOFYEAR_ISO" => Some("WEEKISO"),
// Quarter
"Q" | "QTR" | "QTRS" | "QUARTERS" => Some("QUARTER"),
// Hour
"H" | "HH" | "HR" | "HOURS" | "HRS" => Some("HOUR"),
// Minute (note: 'M' could be minute in some contexts, but we keep it simple)
"MI" | "MIN" | "MINUTES" | "MINS" => Some("MINUTE"),
// Second
"S" | "SEC" | "SECONDS" | "SECS" => Some("SECOND"),
// Millisecond
"MS" | "MSEC" | "MSECS" | "MSECOND" | "MSECONDS" | "MILLISEC" | "MILLISECS"
| "MILLISECON" | "MILLISECONDS" => Some("MILLISECOND"),
// Microsecond
"US" | "USEC" | "USECS" | "MICROSEC" | "MICROSECS" | "USECOND" | "USECONDS"
| "MICROSECONDS" => Some("MICROSECOND"),
// Nanosecond
"NS" | "NSEC" | "NANOSEC" | "NSECOND" | "NSECONDS" | "NANOSECS" => Some("NANOSECOND"),
// Epoch variants
"EPOCH_SECOND" | "EPOCH_SECONDS" => Some("EPOCH_SECOND"),
"EPOCH_MILLISECOND" | "EPOCH_MILLISECONDS" => Some("EPOCH_MILLISECOND"),
"EPOCH_MICROSECOND" | "EPOCH_MICROSECONDS" => Some("EPOCH_MICROSECOND"),
"EPOCH_NANOSECOND" | "EPOCH_NANOSECONDS" => Some("EPOCH_NANOSECOND"),
// Timezone
"TZH" => Some("TIMEZONE_HOUR"),
"TZM" => Some("TIMEZONE_MINUTE"),
// Decade
"DEC" | "DECS" | "DECADES" => Some("DECADE"),
// Millennium
"MIL" | "MILS" | "MILLENIA" => Some("MILLENNIUM"),
// Century
"C" | "CENT" | "CENTS" | "CENTURIES" => Some("CENTURY"),
// No mapping needed (already canonical or unknown)
_ => None,
}
}
/// Transform a date part identifier/expression using the mapping
fn transform_date_part_arg(&self, expr: Expression) -> Expression {
match &expr {
// Handle string literal: 'minute' -> minute (unquoted identifier, preserving case)
Expression::Literal(lit)
if matches!(lit.as_ref(), crate::expressions::Literal::String(_)) =>
{
let crate::expressions::Literal::String(s) = lit.as_ref() else {
unreachable!()
};
Expression::Identifier(crate::expressions::Identifier {
name: s.clone(),
quoted: false,
trailing_comments: Vec::new(),
span: None,
})
}
// Handle Identifier (rare case)
Expression::Identifier(id) => {
if let Some(canonical) = Self::map_date_part(&id.name) {
Expression::Identifier(crate::expressions::Identifier {
name: canonical.to_string(),
quoted: false,
trailing_comments: Vec::new(),
span: None,
})
} else {
// No mapping needed, keep original (Python sqlglot preserves case)
expr
}
}
Expression::Var(v) => {
if let Some(canonical) = Self::map_date_part(&v.this) {
Expression::Identifier(crate::expressions::Identifier {
name: canonical.to_string(),
quoted: false,
trailing_comments: Vec::new(),
span: None,
})
} else {
expr
}
}
// Handle Column (more common - parser treats unqualified names as columns)
Expression::Column(col) if col.table.is_none() => {
if let Some(canonical) = Self::map_date_part(&col.name.name) {
Expression::Identifier(crate::expressions::Identifier {
name: canonical.to_string(),
quoted: false,
trailing_comments: Vec::new(),
span: None,
})
} else {
// No mapping needed, keep original (Python sqlglot preserves case)
expr
}
}
_ => expr,
}
}
/// Like transform_date_part_arg but only handles Identifier/Column, never String literals.
/// Used for native Snowflake DATE_PART where string args should stay as strings.
fn transform_date_part_arg_identifiers_only(&self, expr: Expression) -> Expression {
match &expr {
Expression::Identifier(id) => {
if let Some(canonical) = Self::map_date_part(&id.name) {
Expression::Identifier(crate::expressions::Identifier {
name: canonical.to_string(),
quoted: false,
trailing_comments: Vec::new(),
span: None,
})
} else {
expr
}
}
Expression::Var(v) => {
if let Some(canonical) = Self::map_date_part(&v.this) {
Expression::Identifier(crate::expressions::Identifier {
name: canonical.to_string(),
quoted: false,
trailing_comments: Vec::new(),
span: None,
})
} else {
expr
}
}
Expression::Column(col) if col.table.is_none() => {
if let Some(canonical) = Self::map_date_part(&col.name.name) {
Expression::Identifier(crate::expressions::Identifier {
name: canonical.to_string(),
quoted: false,
trailing_comments: Vec::new(),
span: None,
})
} else {
expr
}
}
_ => expr,
}
}
/// Transform JSON path for Snowflake GET_PATH function
/// - Convert colon notation to dot notation (y[0]:z -> y[0].z)
/// - Wrap unsafe keys in brackets ($id -> ["$id"])
fn transform_json_path(path: &str) -> String {
// Check if path is just a single key that needs bracket wrapping
// A safe identifier is alphanumeric + underscore, starting with letter/underscore
fn is_safe_identifier(s: &str) -> bool {
if s.is_empty() {
return false;
}
let mut chars = s.chars();
match chars.next() {
Some(c) if c.is_ascii_alphabetic() || c == '_' => {}
_ => return false,
}
chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
}
// Simple path: just a key like "$id" or "field"
// If no dots, brackets, or colons, it's a simple key
if !path.contains('.') && !path.contains('[') && !path.contains(':') {
if is_safe_identifier(path) {
return path.to_string();
} else {
// Wrap unsafe key in bracket notation
return format!("[\"{}\"]", path);
}
}
// Complex path: replace colons with dots
// e.g., y[0]:z -> y[0].z
let result = path.replace(':', ".");
result
}
/// Transform interval to expand abbreviated units (e.g., 'w' -> 'WEEK')
fn transform_interval(&self, interval: crate::expressions::Interval) -> Result<Expression> {
use crate::expressions::{Interval, Literal};
// Unit abbreviation mapping (from Python SQLGlot UNABBREVIATED_UNIT_NAME)
fn expand_unit(abbr: &str) -> &'static str {
match abbr.to_uppercase().as_str() {
"D" => "DAY",
"H" => "HOUR",
"M" => "MINUTE",
"MS" => "MILLISECOND",
"NS" => "NANOSECOND",
"Q" => "QUARTER",
"S" => "SECOND",
"US" => "MICROSECOND",
"W" => "WEEK",
"Y" => "YEAR",
// Full forms (normalize to singular, uppercase)
"WEEK" | "WEEKS" => "WEEK",
"DAY" | "DAYS" => "DAY",
"HOUR" | "HOURS" => "HOUR",
"MINUTE" | "MINUTES" => "MINUTE",
"SECOND" | "SECONDS" => "SECOND",
"MONTH" | "MONTHS" => "MONTH",
"YEAR" | "YEARS" => "YEAR",
"QUARTER" | "QUARTERS" => "QUARTER",
"MILLISECOND" | "MILLISECONDS" => "MILLISECOND",
"MICROSECOND" | "MICROSECONDS" => "MICROSECOND",
"NANOSECOND" | "NANOSECONDS" => "NANOSECOND",
_ => "", // Unknown unit, return empty to indicate no match
}
}
/// Parse an interval string like "1 w" into (value, unit)
fn parse_interval_string(s: &str) -> Option<(&str, &str)> {
let s = s.trim();
// Find where the number ends and the unit begins
// Number can be: optional -, digits, optional decimal point, more digits
let mut num_end = 0;
let mut chars = s.chars().peekable();
// Skip leading minus
if chars.peek() == Some(&'-') {
chars.next();
num_end += 1;
}
// Skip digits
while let Some(&c) = chars.peek() {
if c.is_ascii_digit() {
chars.next();
num_end += 1;
} else {
break;
}
}
// Skip optional decimal point and more digits
if chars.peek() == Some(&'.') {
chars.next();
num_end += 1;
while let Some(&c) = chars.peek() {
if c.is_ascii_digit() {
chars.next();
num_end += 1;
} else {
break;
}
}
}
if num_end == 0 || (num_end == 1 && s.starts_with('-')) {
return None; // No number found
}
let value = &s[..num_end];
let rest = s[num_end..].trim();
// Rest should be alphabetic (the unit)
if rest.is_empty() || !rest.chars().all(|c| c.is_ascii_alphabetic()) {
return None;
}
Some((value, rest))
}
// Check if the interval value is a string literal with embedded value+unit
if let Some(Expression::Literal(ref lit)) = interval.this {
if let Literal::String(ref s) = lit.as_ref() {
if let Some((value, unit)) = parse_interval_string(s) {
let expanded = expand_unit(unit);
if !expanded.is_empty() {
// Construct new string with expanded unit
let new_value = format!("{} {}", value, expanded);
return Ok(Expression::Interval(Box::new(Interval {
this: Some(Expression::Literal(Box::new(Literal::String(new_value)))),
unit: None, // Unit is now part of the string (SINGLE_STRING_INTERVAL style)
})));
}
}
}
}
// No transformation needed
Ok(Expression::Interval(Box::new(interval)))
}
fn transform_function(&self, f: Function) -> Result<Expression> {
// First, recursively transform all function arguments
let transformed_args: Vec<Expression> = f
.args
.into_iter()
.map(|arg| self.transform_expr(arg))
.collect::<Result<Vec<_>>>()?;
let f = Function {
name: f.name,
args: transformed_args,
distinct: f.distinct,
trailing_comments: f.trailing_comments,
use_bracket_syntax: f.use_bracket_syntax,
no_parens: f.no_parens,
quoted: f.quoted,
span: None,
inferred_type: None,
};
let name_upper = f.name.to_uppercase();
match name_upper.as_str() {
// IFNULL -> COALESCE (standardize to COALESCE)
"IFNULL" if f.args.len() == 2 => Ok(Expression::Coalesce(Box::new(VarArgFunc {
original_name: None,
expressions: f.args,
inferred_type: None,
}))),
// NVL -> COALESCE (both work in Snowflake, but COALESCE is standard per SQLGlot)
"NVL" if f.args.len() == 2 => Ok(Expression::Coalesce(Box::new(VarArgFunc {
original_name: None,
expressions: f.args,
inferred_type: None,
}))),
// NVL2 is native to Snowflake
"NVL2" => Ok(Expression::Function(Box::new(f))),
// GROUP_CONCAT -> LISTAGG in Snowflake
"GROUP_CONCAT" if !f.args.is_empty() => Ok(Expression::Function(Box::new(
Function::new("LISTAGG".to_string(), f.args),
))),
// STRING_AGG -> LISTAGG in Snowflake
"STRING_AGG" if !f.args.is_empty() => Ok(Expression::Function(Box::new(
Function::new("LISTAGG".to_string(), f.args),
))),
// SUBSTR -> SUBSTRING (both work in Snowflake)
"SUBSTR" => Ok(Expression::Function(Box::new(Function::new(
"SUBSTRING".to_string(),
f.args,
)))),
// UNNEST -> FLATTEN
"UNNEST" => Ok(Expression::Function(Box::new(Function::new(
"FLATTEN".to_string(),
f.args,
)))),
// EXPLODE -> FLATTEN
"EXPLODE" => Ok(Expression::Function(Box::new(Function::new(
"FLATTEN".to_string(),
f.args,
)))),
// CURRENT_DATE is native
"CURRENT_DATE" => Ok(Expression::CurrentDate(crate::expressions::CurrentDate)),
// NOW -> CURRENT_TIMESTAMP (preserving parens style)
"NOW" => Ok(Expression::Function(Box::new(Function {
name: "CURRENT_TIMESTAMP".to_string(),
args: f.args,
distinct: false,
trailing_comments: Vec::new(),
use_bracket_syntax: false,
no_parens: f.no_parens,
quoted: false,
span: None,
inferred_type: None,
}))),
// GETDATE -> CURRENT_TIMESTAMP (preserving parens style)
"GETDATE" => Ok(Expression::Function(Box::new(Function {
name: "CURRENT_TIMESTAMP".to_string(),
args: f.args,
distinct: false,
trailing_comments: Vec::new(),
use_bracket_syntax: false,
no_parens: f.no_parens,
quoted: false,
span: None,
inferred_type: None,
}))),
// CURRENT_TIMESTAMP - always output with parens in Snowflake
// Note: LOCALTIMESTAMP converts to CURRENT_TIMESTAMP without parens,
// but explicit CURRENT_TIMESTAMP calls should have parens
"CURRENT_TIMESTAMP" if f.args.is_empty() => {
Ok(Expression::Function(Box::new(Function {
name: "CURRENT_TIMESTAMP".to_string(),
args: Vec::new(),
distinct: false,
trailing_comments: Vec::new(),
use_bracket_syntax: false,
no_parens: false, // Always output with parens
quoted: false,
span: None,
inferred_type: None,
})))
}
// TO_DATE with single string arg that looks like a date -> CAST(arg AS DATE)
// Per Python SQLGlot: TO_DATE('2013-04-05') -> CAST('2013-04-05' AS DATE)
// But TO_DATE('12345') stays as is (doesn't look like a date)
"TO_DATE" => {
if f.args.len() == 1 {
if let Expression::Literal(lit) = &f.args[0] {
if let crate::expressions::Literal::String(s) = lit.as_ref() {
// Check if the string looks like a date (contains dashes like 2013-04-05)
if s.contains('-') && s.len() >= 8 && s.len() <= 12 {
return Ok(Expression::Cast(Box::new(Cast {
this: f.args.into_iter().next().unwrap(),
to: crate::expressions::DataType::Date,
double_colon_syntax: false,
trailing_comments: Vec::new(),
format: None,
default: None,
inferred_type: None,
})));
}
}
}
}
// Normalize format string (2nd arg) if present
let mut args = f.args;
if args.len() >= 2 {
args[1] = Self::normalize_format_arg(args[1].clone());
}
Ok(Expression::Function(Box::new(Function::new(
"TO_DATE".to_string(),
args,
))))
}
// TO_TIME with single string arg -> CAST(arg AS TIME)
"TO_TIME" => {
if f.args.len() == 1 {
if let Expression::Literal(lit) = &f.args[0] {
if let crate::expressions::Literal::String(_) = lit.as_ref() {
return Ok(Expression::Cast(Box::new(Cast {
this: f.args.into_iter().next().unwrap(),
to: crate::expressions::DataType::Time {
precision: None,
timezone: false,
},
double_colon_syntax: false,
trailing_comments: Vec::new(),
format: None,
default: None,
inferred_type: None,
})));
}
}
}
// Normalize format string (2nd arg) if present
let mut args = f.args;
if args.len() >= 2 {
args[1] = Self::normalize_format_arg(args[1].clone());
}
Ok(Expression::Function(Box::new(Function::new(
"TO_TIME".to_string(),
args,
))))
}
// TO_TIMESTAMP: Snowflake has multiple forms:
// 1. TO_TIMESTAMP('datetime_string') -> CAST('...' AS TIMESTAMP)
// 2. TO_TIMESTAMP('epoch_string') -> UnixToTime(epoch_string)
// 3. TO_TIMESTAMP(number) -> UnixToTime(number)
// 4. TO_TIMESTAMP(number, scale) where scale is int -> UnixToTime(number, scale)
// 5. TO_TIMESTAMP(string, format) where format is string -> StrToTime(string, format)
"TO_TIMESTAMP" => {
let args = f.args;
if args.len() == 1 {
let arg = &args[0];
match arg {
Expression::Literal(lit) if matches!(lit.as_ref(), Literal::String(s) if Self::looks_like_datetime(s)) =>
{
let Literal::String(_) = lit.as_ref() else {
unreachable!()
};
// Case 1: datetime string -> CAST AS TIMESTAMP
return Ok(Expression::Cast(Box::new(Cast {
this: args.into_iter().next().unwrap(),
to: DataType::Timestamp {
precision: None,
timezone: false,
},
double_colon_syntax: false,
trailing_comments: vec![],
format: None,
default: None,
inferred_type: None,
})));
}
Expression::Literal(lit) if matches!(lit.as_ref(), Literal::String(s) if Self::looks_like_epoch(s)) =>
{
let Literal::String(_) = lit.as_ref() else {
unreachable!()
};
// Case 2: epoch number as string -> UnixToTime
return Ok(Expression::UnixToTime(Box::new(
crate::expressions::UnixToTime {
this: Box::new(args.into_iter().next().unwrap()),
scale: None,
zone: None,
hours: None,
minutes: None,
format: None,
target_type: None,
},
)));
}
Expression::Literal(lit) if matches!(lit.as_ref(), Literal::Number(_)) => {
// Case 3: number -> UnixToTime
return Ok(Expression::UnixToTime(Box::new(
crate::expressions::UnixToTime {
this: Box::new(args.into_iter().next().unwrap()),
scale: None,
zone: None,
hours: None,
minutes: None,
format: None,
target_type: None,
},
)));
}
Expression::Neg(_) => {
// Case 3: number -> UnixToTime
return Ok(Expression::UnixToTime(Box::new(
crate::expressions::UnixToTime {
this: Box::new(args.into_iter().next().unwrap()),
scale: None,
zone: None,
hours: None,
minutes: None,
format: None,
target_type: None,
},
)));
}
_ => {
// Unknown single arg, keep as function
return Ok(Expression::Function(Box::new(Function::new(
"TO_TIMESTAMP".to_string(),
args,
))));
}
}
} else if args.len() == 2 {
let second_arg = &args[1];
// Check if second arg is an integer (scale) or a format string
let is_int_scale = match second_arg {
Expression::Literal(lit) if matches!(lit.as_ref(), Literal::Number(_)) => {
let Literal::Number(n) = lit.as_ref() else {
unreachable!()
};
n.parse::<i64>().is_ok()
}
_ => false,
};
if is_int_scale {
// Case 4: TO_TIMESTAMP(number, scale) -> UnixToTime
let mut args_iter = args.into_iter();
let value = args_iter.next().unwrap();
let scale_expr = args_iter.next().unwrap();
let scale = if let Expression::Literal(lit) = &scale_expr {
if let Literal::Number(n) = lit.as_ref() {
n.parse::<i64>().ok()
} else {
None
}
} else {
None
};
return Ok(Expression::UnixToTime(Box::new(
crate::expressions::UnixToTime {
this: Box::new(value),
scale,
zone: None,
hours: None,
minutes: None,
format: None,
target_type: None,
},
)));
} else {
// Case 5: TO_TIMESTAMP(string, format) -> StrToTime
let mut args_iter = args.into_iter();
let value = args_iter.next().unwrap();
let format_expr = args_iter.next().unwrap();
let format_str = match &format_expr {
Expression::Literal(lit)
if matches!(lit.as_ref(), Literal::String(_)) =>
{
let Literal::String(s) = lit.as_ref() else {
unreachable!()
};
s.clone()
}
_ => {
// Non-string format, keep as function
return Ok(Expression::Function(Box::new(Function::new(
"TO_TIMESTAMP".to_string(),
vec![value, format_expr],
))));
}
};
// Normalize Snowflake format to target-neutral
let normalized_format = Self::normalize_snowflake_format(&format_str);
return Ok(Expression::StrToTime(Box::new(
crate::expressions::StrToTime {
this: Box::new(value),
format: normalized_format,
zone: None,
safe: None,
target_type: None,
},
)));
}
}
// More than 2 args or other cases, keep as function
Ok(Expression::Function(Box::new(Function::new(
"TO_TIMESTAMP".to_string(),
args,
))))
}
// TO_CHAR is native to Snowflake
"TO_CHAR" => Ok(Expression::Function(Box::new(f))),
// ROUND with named args: ROUND(EXPR => x, SCALE => y, ROUNDING_MODE => z)
// -> ROUND(x, y) or ROUND(x, y, z)
"ROUND"
if f.args
.iter()
.any(|a| matches!(a, Expression::NamedArgument(_))) =>
{
let mut expr_val = None;
let mut scale_val = None;
let mut rounding_mode_val = None;
for arg in &f.args {
if let Expression::NamedArgument(na) = arg {
match na.name.name.to_uppercase().as_str() {
"EXPR" => expr_val = Some(na.value.clone()),
"SCALE" => scale_val = Some(na.value.clone()),
"ROUNDING_MODE" => rounding_mode_val = Some(na.value.clone()),
_ => {}
}
}
}
if let Some(expr) = expr_val {
let mut args = vec![expr];
if let Some(scale) = scale_val {
args.push(scale);
}
if let Some(mode) = rounding_mode_val {
args.push(mode);
}
Ok(Expression::Function(Box::new(Function::new(
"ROUND".to_string(),
args,
))))
} else {
Ok(Expression::Function(Box::new(f)))
}
}
// DATE_FORMAT -> TO_CHAR in Snowflake
// Also converts strftime format to Snowflake format and wraps first arg in CAST AS TIMESTAMP
"DATE_FORMAT" => {
let mut args = f.args;
// Wrap first arg in CAST AS TIMESTAMP if it's a string literal
if !args.is_empty() {
if matches!(&args[0], Expression::Literal(lit) if matches!(lit.as_ref(), Literal::String(_)))
{
args[0] = Expression::Cast(Box::new(crate::expressions::Cast {
this: args[0].clone(),
to: DataType::Timestamp {
precision: None,
timezone: false,
},
trailing_comments: Vec::new(),
double_colon_syntax: false,
format: None,
default: None,
inferred_type: None,
}));
}
}
// Convert strftime format to Snowflake format
if args.len() >= 2 {
if let Expression::Literal(ref lit) = args[1] {
if let Literal::String(ref fmt) = lit.as_ref() {
let sf_fmt = strftime_to_snowflake_format(fmt);
args[1] = Expression::Literal(Box::new(Literal::String(sf_fmt)));
}
}
}
Ok(Expression::Function(Box::new(Function::new(
"TO_CHAR".to_string(),
args,
))))
}
// ARRAY -> ARRAY_CONSTRUCT
"ARRAY" => Ok(Expression::Function(Box::new(Function::new(
"ARRAY_CONSTRUCT".to_string(),
f.args,
)))),
// STRUCT -> OBJECT_CONSTRUCT
// Convert STRUCT(value AS name, ...) to OBJECT_CONSTRUCT('name', value, ...)
"STRUCT" => {
let mut oc_args = Vec::new();
for arg in f.args {
match arg {
Expression::Alias(a) => {
// Named field: value AS name -> 'name', value
oc_args.push(Expression::Literal(Box::new(
crate::expressions::Literal::String(a.alias.name.clone()),
)));
oc_args.push(a.this);
}
other => {
// Unnamed field: just pass through
oc_args.push(other);
}
}
}
Ok(Expression::Function(Box::new(Function::new(
"OBJECT_CONSTRUCT".to_string(),
oc_args,
))))
}
// JSON_EXTRACT -> GET_PATH or GET in Snowflake
"JSON_EXTRACT" => Ok(Expression::Function(Box::new(Function::new(
"GET_PATH".to_string(),
f.args,
)))),
// JSON_EXTRACT_SCALAR -> JSON_EXTRACT_PATH_TEXT
"JSON_EXTRACT_SCALAR" => Ok(Expression::Function(Box::new(Function::new(
"JSON_EXTRACT_PATH_TEXT".to_string(),
f.args,
)))),
// LEN -> LENGTH
"LEN" if f.args.len() == 1 => Ok(Expression::Length(Box::new(UnaryFunc::new(
f.args.into_iter().next().unwrap(),
)))),
// CEILING -> CEIL (both work)
"CEILING" if f.args.len() == 1 => Ok(Expression::Ceil(Box::new(CeilFunc {
this: f.args.into_iter().next().unwrap(),
decimals: None,
to: None,
}))),
// CHARINDEX -> POSITION or CHARINDEX (native)
"CHARINDEX" => Ok(Expression::Function(Box::new(f))),
// SPLIT is native to Snowflake - keep as-is
"SPLIT" => Ok(Expression::Function(Box::new(f))),
// ARRAY_AGG is native to Snowflake
"ARRAY_AGG" => Ok(Expression::Function(Box::new(f))),
// PARSE_JSON for JSON parsing
"JSON_PARSE" | "PARSE_JSON" => Ok(Expression::Function(Box::new(Function::new(
"PARSE_JSON".to_string(),
f.args,
)))),
// RAND -> Rand (to use RANDOM in Snowflake)
"RAND" => {
let seed = f.args.first().cloned().map(Box::new);
Ok(Expression::Rand(Box::new(crate::expressions::Rand {
seed,
lower: None,
upper: None,
})))
}
// SHA -> SHA1
"SHA" => Ok(Expression::Function(Box::new(Function::new(
"SHA1".to_string(),
f.args,
)))),
// APPROX_COUNT_DISTINCT is native
"APPROX_DISTINCT" => Ok(Expression::Function(Box::new(Function::new(
"APPROX_COUNT_DISTINCT".to_string(),
f.args,
)))),
// GEN_RANDOM_UUID/UUID -> Uuid AST node
"GEN_RANDOM_UUID" | "UUID" => {
Ok(Expression::Uuid(Box::new(crate::expressions::Uuid {
this: None,
name: None,
is_string: None,
})))
}
// NEWID -> Uuid AST node
"NEWID" => Ok(Expression::Uuid(Box::new(crate::expressions::Uuid {
this: None,
name: None,
is_string: None,
}))),
// UUID_STRING -> Uuid AST node (without args only; with args keep as Function for identity)
"UUID_STRING" => {
if f.args.is_empty() {
Ok(Expression::Uuid(Box::new(crate::expressions::Uuid {
this: None,
name: None,
is_string: None,
})))
} else {
Ok(Expression::Function(Box::new(Function::new(
"UUID_STRING".to_string(),
f.args,
))))
}
}
// IF -> IFF (convert to IfFunc AST node)
"IF" if f.args.len() >= 2 => {
let mut args = f.args;
let condition = args.remove(0);
let true_val = args.remove(0);
let false_val = if !args.is_empty() {
Some(args.remove(0))
} else {
None
};
Ok(Expression::IfFunc(Box::new(crate::expressions::IfFunc {
condition,
true_value: true_val,
false_value: Some(
false_val.unwrap_or(Expression::Null(crate::expressions::Null)),
),
original_name: Some("IFF".to_string()),
inferred_type: None,
})))
}
// SQUARE(x) -> POWER(x, 2)
"SQUARE" if f.args.len() == 1 => {
let x = f.args.into_iter().next().unwrap();
Ok(Expression::Power(Box::new(
crate::expressions::BinaryFunc {
original_name: None,
this: x,
expression: Expression::number(2),
inferred_type: None,
},
)))
}
// POW(x, y) -> POWER(x, y)
"POW" if f.args.len() == 2 => {
let mut args = f.args.into_iter();
let x = args.next().unwrap();
let y = args.next().unwrap();
Ok(Expression::Power(Box::new(
crate::expressions::BinaryFunc {
original_name: None,
this: x,
expression: y,
inferred_type: None,
},
)))
}
// MOD(x, y) -> x % y (modulo operator)
"MOD" if f.args.len() == 2 => {
let mut args = f.args.into_iter();
let x = args.next().unwrap();
let y = args.next().unwrap();
Ok(Expression::Mod(Box::new(crate::expressions::BinaryOp {
left: x,
right: y,
left_comments: Vec::new(),
operator_comments: Vec::new(),
trailing_comments: Vec::new(),
inferred_type: None,
})))
}
// APPROXIMATE_JACCARD_INDEX -> APPROXIMATE_SIMILARITY
"APPROXIMATE_JACCARD_INDEX" => Ok(Expression::Function(Box::new(Function::new(
"APPROXIMATE_SIMILARITY".to_string(),
f.args,
)))),
// ARRAY_CONSTRUCT -> Array with bracket notation in Snowflake
"ARRAY_CONSTRUCT" => Ok(Expression::ArrayFunc(Box::new(
crate::expressions::ArrayConstructor {
expressions: f.args,
bracket_notation: true,
use_list_keyword: false,
},
))),
// APPROX_TOP_K - add default k=1 if not provided
"APPROX_TOP_K" if f.args.len() == 1 => {
let mut args = f.args;
args.push(Expression::number(1));
Ok(Expression::Function(Box::new(Function::new(
"APPROX_TOP_K".to_string(),
args,
))))
}
// TO_DECIMAL, TO_NUMERIC -> TO_NUMBER
"TO_DECIMAL" | "TO_NUMERIC" => Ok(Expression::Function(Box::new(Function::new(
"TO_NUMBER".to_string(),
f.args,
)))),
// TRY_TO_DECIMAL, TRY_TO_NUMERIC -> TRY_TO_NUMBER
"TRY_TO_DECIMAL" | "TRY_TO_NUMERIC" => Ok(Expression::Function(Box::new(
Function::new("TRY_TO_NUMBER".to_string(), f.args),
))),
// STDDEV_SAMP -> STDDEV
"STDDEV_SAMP" => Ok(Expression::Function(Box::new(Function::new(
"STDDEV".to_string(),
f.args,
)))),
// STRTOK -> SPLIT_PART (with default delimiter and position)
"STRTOK" if f.args.len() >= 1 => {
let mut args = f.args;
// Add default delimiter (space) if missing
if args.len() == 1 {
args.push(Expression::string(" ".to_string()));
}
// Add default position (1) if missing
if args.len() == 2 {
args.push(Expression::number(1));
}
Ok(Expression::Function(Box::new(Function::new(
"STRTOK".to_string(),
args,
))))
}
// WEEKOFYEAR -> WEEK
"WEEKOFYEAR" => Ok(Expression::Function(Box::new(Function::new(
"WEEK".to_string(),
f.args,
)))),
// LIKE(col, pattern, escape) -> col LIKE pattern ESCAPE escape
"LIKE" if f.args.len() >= 2 => {
let mut args = f.args.into_iter();
let left = args.next().unwrap();
let right = args.next().unwrap();
let escape = args.next();
Ok(Expression::Like(Box::new(crate::expressions::LikeOp {
left,
right,
escape,
quantifier: None,
inferred_type: None,
})))
}
// ILIKE(col, pattern, escape) -> col ILIKE pattern ESCAPE escape
"ILIKE" if f.args.len() >= 2 => {
let mut args = f.args.into_iter();
let left = args.next().unwrap();
let right = args.next().unwrap();
let escape = args.next();
Ok(Expression::ILike(Box::new(crate::expressions::LikeOp {
left,
right,
escape,
quantifier: None,
inferred_type: None,
})))
}
// RLIKE -> REGEXP_LIKE
"RLIKE" if f.args.len() >= 2 => {
let mut args = f.args.into_iter();
let left = args.next().unwrap();
let pattern = args.next().unwrap();
let flags = args.next();
Ok(Expression::RegexpLike(Box::new(
crate::expressions::RegexpFunc {
this: left,
pattern,
flags,
},
)))
}
// IFF -> convert to IfFunc AST node for proper cross-dialect handling
"IFF" if f.args.len() >= 2 => {
let mut args = f.args;
let condition = args.remove(0);
let true_value = args.remove(0);
let false_value = if !args.is_empty() {
Some(args.remove(0))
} else {
None
};
Ok(Expression::IfFunc(Box::new(crate::expressions::IfFunc {
condition,
true_value,
false_value,
original_name: Some("IFF".to_string()),
inferred_type: None,
})))
}
// TIMESTAMP_NTZ_FROM_PARTS, TIMESTAMPFROMPARTS, TIMESTAMPNTZFROMPARTS -> TIMESTAMP_FROM_PARTS
"TIMESTAMP_NTZ_FROM_PARTS" | "TIMESTAMPFROMPARTS" | "TIMESTAMPNTZFROMPARTS" => {
Ok(Expression::Function(Box::new(Function::new(
"TIMESTAMP_FROM_PARTS".to_string(),
f.args,
))))
}
// TIMESTAMPLTZFROMPARTS -> TIMESTAMP_LTZ_FROM_PARTS
"TIMESTAMPLTZFROMPARTS" => Ok(Expression::Function(Box::new(Function::new(
"TIMESTAMP_LTZ_FROM_PARTS".to_string(),
f.args,
)))),
// TIMESTAMPTZFROMPARTS -> TIMESTAMP_TZ_FROM_PARTS
"TIMESTAMPTZFROMPARTS" => Ok(Expression::Function(Box::new(Function::new(
"TIMESTAMP_TZ_FROM_PARTS".to_string(),
f.args,
)))),
// DATEADD with 3 args - transform the unit (first arg) using date part mapping
"DATEADD" if f.args.len() >= 1 => {
let mut args = f.args;
args[0] = self.transform_date_part_arg(args[0].clone());
Ok(Expression::Function(Box::new(Function::new(
"DATEADD".to_string(),
args,
))))
}
// DATEDIFF with 3 args - transform the unit (first arg) using date part mapping
// Also convert _POLYGLOT_TO_DATE back to TO_DATE (from cross-dialect normalize)
"DATEDIFF" if f.args.len() >= 1 => {
let mut args = f.args;
args[0] = self.transform_date_part_arg(args[0].clone());
// Convert _POLYGLOT_TO_DATE back to TO_DATE for date args
// (_POLYGLOT_TO_DATE is an internal marker from cross-dialect normalize)
for i in 1..args.len() {
if let Expression::Function(ref func) = args[i] {
if func.name == "_POLYGLOT_TO_DATE" {
let inner_args = func.args.clone();
args[i] = Expression::Function(Box::new(Function::new(
"TO_DATE".to_string(),
inner_args,
)));
}
}
}
Ok(Expression::Function(Box::new(Function::new(
"DATEDIFF".to_string(),
args,
))))
}
// TIMEDIFF -> DATEDIFF
"TIMEDIFF" => Ok(Expression::Function(Box::new(Function::new(
"DATEDIFF".to_string(),
f.args,
)))),
// TIMESTAMPDIFF -> DATEDIFF
"TIMESTAMPDIFF" => Ok(Expression::Function(Box::new(Function::new(
"DATEDIFF".to_string(),
f.args,
)))),
// TIMESTAMPADD -> DATEADD
"TIMESTAMPADD" => Ok(Expression::Function(Box::new(Function::new(
"DATEADD".to_string(),
f.args,
)))),
// TIMEADD -> preserve it
"TIMEADD" => Ok(Expression::Function(Box::new(f))),
// DATE_FROM_PARTS, DATEFROMPARTS -> DATE_FROM_PARTS
"DATEFROMPARTS" => Ok(Expression::Function(Box::new(Function::new(
"DATE_FROM_PARTS".to_string(),
f.args,
)))),
// TIME_FROM_PARTS, TIMEFROMPARTS -> TIME_FROM_PARTS
"TIMEFROMPARTS" => Ok(Expression::Function(Box::new(Function::new(
"TIME_FROM_PARTS".to_string(),
f.args,
)))),
// DAYOFWEEK -> DAYOFWEEK (preserve)
"DAYOFWEEK" => Ok(Expression::Function(Box::new(f))),
// DAYOFMONTH -> DAYOFMONTH (preserve)
"DAYOFMONTH" => Ok(Expression::Function(Box::new(f))),
// DAYOFYEAR -> DAYOFYEAR (preserve)
"DAYOFYEAR" => Ok(Expression::Function(Box::new(f))),
// MONTHNAME -> Monthname AST node (abbreviated=true for Snowflake)
// Target dialects can then convert to their native form
"MONTHNAME" if f.args.len() == 1 => {
let arg = f.args.into_iter().next().unwrap();
Ok(Expression::Monthname(Box::new(
crate::expressions::Monthname {
this: Box::new(arg),
abbreviated: Some(Box::new(Expression::Literal(Box::new(
Literal::String("true".to_string()),
)))),
},
)))
}
// DAYNAME -> Dayname AST node (abbreviated=true for Snowflake)
// Target dialects can then convert to their native form
"DAYNAME" if f.args.len() == 1 => {
let arg = f.args.into_iter().next().unwrap();
Ok(Expression::Dayname(Box::new(crate::expressions::Dayname {
this: Box::new(arg),
abbreviated: Some(Box::new(Expression::Literal(Box::new(Literal::String(
"true".to_string(),
))))),
})))
}
// BOOLAND_AGG/BOOL_AND/LOGICAL_AND -> LogicalAnd AST node
"BOOLAND_AGG" | "BOOL_AND" | "LOGICAL_AND" if !f.args.is_empty() => {
let arg = f.args.into_iter().next().unwrap();
Ok(Expression::LogicalAnd(Box::new(AggFunc {
this: arg,
distinct: false,
filter: None,
order_by: Vec::new(),
name: Some("BOOLAND_AGG".to_string()),
ignore_nulls: None,
having_max: None,
limit: None,
inferred_type: None,
})))
}
// BOOLOR_AGG/BOOL_OR/LOGICAL_OR -> LogicalOr AST node
"BOOLOR_AGG" | "BOOL_OR" | "LOGICAL_OR" if !f.args.is_empty() => {
let arg = f.args.into_iter().next().unwrap();
Ok(Expression::LogicalOr(Box::new(AggFunc {
this: arg,
distinct: false,
filter: None,
order_by: Vec::new(),
name: Some("BOOLOR_AGG".to_string()),
ignore_nulls: None,
having_max: None,
limit: None,
inferred_type: None,
})))
}
// SKEW -> Skewness AST node for proper cross-dialect handling
"SKEW" | "SKEWNESS" if !f.args.is_empty() => {
let arg = f.args.into_iter().next().unwrap();
Ok(Expression::Skewness(Box::new(AggFunc {
this: arg,
distinct: false,
filter: None,
order_by: Vec::new(),
name: Some("SKEW".to_string()),
ignore_nulls: None,
having_max: None,
limit: None,
inferred_type: None,
})))
}
// VAR_SAMP -> VARIANCE (Snowflake uses VARIANCE for sample variance)
"VAR_SAMP" => Ok(Expression::Function(Box::new(Function::new(
"VARIANCE".to_string(),
f.args,
)))),
// VAR_POP -> VARIANCE_POP
"VAR_POP" => Ok(Expression::Function(Box::new(Function::new(
"VARIANCE_POP".to_string(),
f.args,
)))),
// DATE(str) -> TO_DATE(str) (single-arg form)
"DATE" if f.args.len() == 1 => Ok(Expression::Function(Box::new(Function::new(
"TO_DATE".to_string(),
f.args,
)))),
// DATE(str, format) -> TO_DATE(str, normalized_format)
// Python SQLGlot normalizes DATE(...) to TO_DATE(...) for formatted variants.
// But _POLYGLOT_DATE(str, format) stays as DATE() (from BigQuery PARSE_DATE conversion)
"DATE" if f.args.len() >= 2 => {
let mut args = f.args;
args[1] = Self::normalize_format_arg(args[1].clone());
Ok(Expression::Function(Box::new(Function::new(
"TO_DATE".to_string(),
args,
))))
}
// Internal marker from BigQuery PARSE_DATE -> Snowflake conversion
// _POLYGLOT_DATE stays as DATE() (not converted to TO_DATE)
"_POLYGLOT_DATE" if f.args.len() >= 2 => {
let mut args = f.args;
args[1] = Self::normalize_format_arg(args[1].clone());
Ok(Expression::Function(Box::new(Function::new(
"DATE".to_string(),
args,
))))
}
// DESCRIBE/DESC normalization
"DESCRIBE" => Ok(Expression::Function(Box::new(f))),
// MD5 -> MD5 (preserve) but MD5_HEX -> MD5
"MD5_HEX" => Ok(Expression::Function(Box::new(Function::new(
"MD5".to_string(),
f.args,
)))),
// SHA1_HEX -> SHA1
"SHA1_HEX" => Ok(Expression::Function(Box::new(Function::new(
"SHA1".to_string(),
f.args,
)))),
// SHA2_HEX -> SHA2
"SHA2_HEX" => Ok(Expression::Function(Box::new(Function::new(
"SHA2".to_string(),
f.args,
)))),
// EDITDISTANCE -> EDITDISTANCE (preserve Snowflake name)
"LEVENSHTEIN" => Ok(Expression::Function(Box::new(Function::new(
"EDITDISTANCE".to_string(),
f.args,
)))),
// BIT_NOT -> BITNOT
"BIT_NOT" if f.args.len() == 1 => Ok(Expression::Function(Box::new(Function::new(
"BITNOT".to_string(),
f.args,
)))),
// BIT_AND -> BITAND
"BIT_AND" if f.args.len() >= 2 => Ok(Expression::Function(Box::new(Function::new(
"BITAND".to_string(),
f.args,
)))),
// BIT_OR -> BITOR
"BIT_OR" if f.args.len() >= 2 => Ok(Expression::Function(Box::new(Function::new(
"BITOR".to_string(),
f.args,
)))),
// BIT_XOR -> BITXOR
"BIT_XOR" if f.args.len() >= 2 => Ok(Expression::Function(Box::new(Function::new(
"BITXOR".to_string(),
f.args,
)))),
// BIT_SHIFTLEFT -> BITSHIFTLEFT
"BIT_SHIFTLEFT" if f.args.len() >= 2 => Ok(Expression::Function(Box::new(
Function::new("BITSHIFTLEFT".to_string(), f.args),
))),
// BIT_SHIFTRIGHT -> BITSHIFTRIGHT
"BIT_SHIFTRIGHT" if f.args.len() >= 2 => Ok(Expression::Function(Box::new(
Function::new("BITSHIFTRIGHT".to_string(), f.args),
))),
// SYSTIMESTAMP -> CURRENT_TIMESTAMP (preserving parens style)
"SYSTIMESTAMP" => Ok(Expression::Function(Box::new(Function {
name: "CURRENT_TIMESTAMP".to_string(),
args: f.args,
distinct: false,
trailing_comments: Vec::new(),
use_bracket_syntax: false,
no_parens: f.no_parens,
quoted: false,
span: None,
inferred_type: None,
}))),
// LOCALTIMESTAMP -> CURRENT_TIMESTAMP (preserving parens style)
"LOCALTIMESTAMP" => Ok(Expression::Function(Box::new(Function {
name: "CURRENT_TIMESTAMP".to_string(),
args: f.args,
distinct: false,
trailing_comments: Vec::new(),
use_bracket_syntax: false,
no_parens: f.no_parens,
quoted: false,
span: None,
inferred_type: None,
}))),
// SPACE(n) -> REPEAT(' ', n) in Snowflake
"SPACE" if f.args.len() == 1 => {
let arg = f.args.into_iter().next().unwrap();
Ok(Expression::Function(Box::new(Function::new(
"REPEAT".to_string(),
vec![
Expression::Literal(Box::new(Literal::String(" ".to_string()))),
arg,
],
))))
}
// CEILING -> CEIL
"CEILING" => Ok(Expression::Function(Box::new(Function::new(
"CEIL".to_string(),
f.args,
)))),
// LOG without base -> LN
"LOG" if f.args.len() == 1 => Ok(Expression::Function(Box::new(Function::new(
"LN".to_string(),
f.args,
)))),
// REGEXP_SUBSTR_ALL is native to Snowflake
"REGEXP_SUBSTR_ALL" => Ok(Expression::Function(Box::new(f))),
// GET_PATH - transform path argument:
// - Convert colon notation to dot notation (y[0]:z -> y[0].z)
// - Wrap unsafe keys in brackets ($id -> ["$id"])
"GET_PATH" if f.args.len() >= 2 => {
let mut args = f.args;
// Transform the path argument (second argument)
if let Expression::Literal(lit) = &args[1] {
if let crate::expressions::Literal::String(path) = lit.as_ref() {
let transformed = Self::transform_json_path(path);
args[1] = Expression::Literal(Box::new(
crate::expressions::Literal::String(transformed),
));
}
}
Ok(Expression::Function(Box::new(Function::new(
"GET_PATH".to_string(),
args,
))))
}
"GET_PATH" => Ok(Expression::Function(Box::new(f))),
// FLATTEN is native to Snowflake
"FLATTEN" => Ok(Expression::Function(Box::new(f))),
// DATE_TRUNC - transform unit to quoted string
// DATE_TRUNC(yr, x) -> DATE_TRUNC('YEAR', x)
"DATE_TRUNC" if f.args.len() >= 1 => {
let mut args = f.args;
// Transform the unit to canonical form and convert to string literal
let unit_name = match &args[0] {
Expression::Identifier(id) => Some(id.name.as_str()),
Expression::Var(v) => Some(v.this.as_str()),
Expression::Column(col) if col.table.is_none() => Some(col.name.name.as_str()),
_ => None,
};
if let Some(name) = unit_name {
let canonical = Self::map_date_part(name).unwrap_or(name);
args[0] = Expression::Literal(Box::new(crate::expressions::Literal::String(
canonical.to_uppercase(),
)));
}
Ok(Expression::Function(Box::new(Function::new(
"DATE_TRUNC".to_string(),
args,
))))
}
// DATE_PART - transform unit argument
// DATE_PART(yyy, x) -> DATE_PART(YEAR, x)
// Only convert string literals to identifiers when the second arg is a typed literal
// (e.g., TIMESTAMP '...', DATE '...'), indicating the function came from another dialect.
// For native Snowflake DATE_PART('month', CAST(...)), preserve the string as-is.
"DATE_PART" if f.args.len() >= 1 => {
let mut args = f.args;
let from_typed_literal = args.len() >= 2
&& matches!(
&args[1],
Expression::Literal(lit) if matches!(lit.as_ref(),
crate::expressions::Literal::Timestamp(_)
| crate::expressions::Literal::Date(_)
| crate::expressions::Literal::Time(_)
| crate::expressions::Literal::Datetime(_)
)
);
if from_typed_literal {
args[0] = self.transform_date_part_arg(args[0].clone());
} else {
// For non-typed-literal cases, only normalize identifiers/columns
// (don't convert string literals to identifiers)
args[0] = self.transform_date_part_arg_identifiers_only(args[0].clone());
}
Ok(Expression::Function(Box::new(Function::new(
"DATE_PART".to_string(),
args,
))))
}
// OBJECT_CONSTRUCT is native to Snowflake
"OBJECT_CONSTRUCT" => Ok(Expression::Function(Box::new(f))),
// OBJECT_CONSTRUCT_KEEP_NULL is native to Snowflake
"OBJECT_CONSTRUCT_KEEP_NULL" => Ok(Expression::Function(Box::new(f))),
// DESC -> DESCRIBE
"DESC" => Ok(Expression::Function(Box::new(Function::new(
"DESCRIBE".to_string(),
f.args,
)))),
// RLIKE -> REGEXP_LIKE
"RLIKE" if f.args.len() >= 2 => Ok(Expression::Function(Box::new(Function::new(
"REGEXP_LIKE".to_string(),
f.args,
)))),
// TRANSFORM function - handle typed lambda parameters
// For typed lambdas like `a int -> a + 1`, we need to:
// 1. Remove the type annotation from the parameter
// 2. Wrap all references to the parameter in the body with CAST(param AS type)
"TRANSFORM" => {
let transformed_args: Vec<Expression> = f
.args
.into_iter()
.map(|arg| {
if let Expression::Lambda(lambda) = arg {
self.transform_typed_lambda(*lambda)
} else {
arg
}
})
.collect();
Ok(Expression::Function(Box::new(Function::new(
"TRANSFORM".to_string(),
transformed_args,
))))
}
// SEARCH function - convert to Search expression with canonical parameter ordering
"SEARCH" if f.args.len() >= 2 => {
let mut args = f.args.into_iter();
let this = Box::new(args.next().unwrap());
let expression = Box::new(args.next().unwrap());
let mut analyzer: Option<Box<Expression>> = None;
let mut search_mode: Option<Box<Expression>> = None;
// Parse remaining named arguments
for arg in args {
if let Expression::NamedArgument(na) = &arg {
let name_upper = na.name.name.to_uppercase();
match name_upper.as_str() {
"ANALYZER" => analyzer = Some(Box::new(arg)),
"SEARCH_MODE" => search_mode = Some(Box::new(arg)),
_ => {}
}
}
}
Ok(Expression::Search(Box::new(crate::expressions::Search {
this,
expression,
json_scope: None,
analyzer,
analyzer_options: None,
search_mode,
})))
}
// ODBC CONVERT function: CONVERT(value, SQL_TYPE) -> CAST(value AS TYPE)
// This handles the { fn CONVERT(...) } ODBC escape sequence syntax
"CONVERT" if f.args.len() == 2 => {
let value = f.args.get(0).cloned().unwrap();
let type_arg = f.args.get(1).cloned().unwrap();
// Check if second argument is a SQL_ type identifier
if let Expression::Column(col) = &type_arg {
let type_name = col.name.name.to_uppercase();
let data_type = match type_name.as_str() {
"SQL_DOUBLE" => Some(DataType::Double {
precision: None,
scale: None,
}),
"SQL_VARCHAR" => Some(DataType::VarChar {
length: None,
parenthesized_length: false,
}),
"SQL_INTEGER" | "SQL_INT" => Some(DataType::Int {
length: None,
integer_spelling: false,
}),
"SQL_BIGINT" => Some(DataType::BigInt { length: None }),
"SQL_SMALLINT" => Some(DataType::SmallInt { length: None }),
"SQL_FLOAT" => Some(DataType::Float {
precision: None,
scale: None,
real_spelling: false,
}),
"SQL_REAL" => Some(DataType::Float {
precision: None,
scale: None,
real_spelling: true,
}),
"SQL_DECIMAL" => Some(DataType::Decimal {
precision: None,
scale: None,
}),
"SQL_DATE" => Some(DataType::Date),
"SQL_TIME" => Some(DataType::Time {
precision: None,
timezone: false,
}),
"SQL_TIMESTAMP" => Some(DataType::Timestamp {
precision: None,
timezone: false,
}),
_ => None,
};
if let Some(dt) = data_type {
return Ok(Expression::Cast(Box::new(Cast {
this: value,
to: dt,
double_colon_syntax: false,
trailing_comments: vec![],
format: None,
default: None,
inferred_type: None,
})));
}
}
// If not a SQL_ type, keep as regular CONVERT function
Ok(Expression::Function(Box::new(f)))
}
// TO_TIMESTAMP_TZ: single string arg -> CAST(... AS TIMESTAMPTZ), otherwise keep as function
// Per Python sqlglot: _build_datetime converts TO_TIMESTAMP_TZ('string') to CAST('string' AS TIMESTAMPTZ)
"TO_TIMESTAMP_TZ" => {
if f.args.len() == 1 {
if let Expression::Literal(lit) = &f.args[0] {
if let crate::expressions::Literal::String(_) = lit.as_ref() {
return Ok(Expression::Cast(Box::new(Cast {
this: f.args.into_iter().next().unwrap(),
to: DataType::Custom {
name: "TIMESTAMPTZ".to_string(),
},
double_colon_syntax: false,
trailing_comments: vec![],
format: None,
default: None,
inferred_type: None,
})));
}
}
}
Ok(Expression::Function(Box::new(f)))
}
// TO_TIMESTAMP_NTZ: single string arg -> CAST(... AS TIMESTAMPNTZ), otherwise keep as function
"TO_TIMESTAMP_NTZ" => {
if f.args.len() == 1 {
if let Expression::Literal(lit) = &f.args[0] {
if let crate::expressions::Literal::String(_) = lit.as_ref() {
return Ok(Expression::Cast(Box::new(Cast {
this: f.args.into_iter().next().unwrap(),
to: DataType::Custom {
name: "TIMESTAMPNTZ".to_string(),
},
double_colon_syntax: false,
trailing_comments: vec![],
format: None,
default: None,
inferred_type: None,
})));
}
}
}
Ok(Expression::Function(Box::new(f)))
}
// TO_TIMESTAMP_LTZ: single string arg -> CAST(... AS TIMESTAMPLTZ), otherwise keep as function
"TO_TIMESTAMP_LTZ" => {
if f.args.len() == 1 {
if let Expression::Literal(lit) = &f.args[0] {
if let crate::expressions::Literal::String(_) = lit.as_ref() {
return Ok(Expression::Cast(Box::new(Cast {
this: f.args.into_iter().next().unwrap(),
to: DataType::Custom {
name: "TIMESTAMPLTZ".to_string(),
},
double_colon_syntax: false,
trailing_comments: vec![],
format: None,
default: None,
inferred_type: None,
})));
}
}
}
Ok(Expression::Function(Box::new(f)))
}
// UNIFORM -> keep as-is (Snowflake-specific)
"UNIFORM" => Ok(Expression::Function(Box::new(f))),
// REPLACE with 2 args -> add empty string 3rd arg
"REPLACE" if f.args.len() == 2 => {
let mut args = f.args;
args.push(Expression::Literal(Box::new(
crate::expressions::Literal::String(String::new()),
)));
Ok(Expression::Function(Box::new(Function::new(
"REPLACE".to_string(),
args,
))))
}
// ARBITRARY -> ANY_VALUE in Snowflake
"ARBITRARY" => Ok(Expression::Function(Box::new(Function::new(
"ANY_VALUE".to_string(),
f.args,
)))),
// SAFE_DIVIDE(x, y) -> IFF(y <> 0, x / y, NULL)
"SAFE_DIVIDE" if f.args.len() == 2 => {
let mut args = f.args;
let x = args.remove(0);
let y = args.remove(0);
Ok(Expression::IfFunc(Box::new(crate::expressions::IfFunc {
condition: Expression::Neq(Box::new(BinaryOp {
left: y.clone(),
right: Expression::number(0),
left_comments: Vec::new(),
operator_comments: Vec::new(),
trailing_comments: Vec::new(),
inferred_type: None,
})),
true_value: Expression::Div(Box::new(BinaryOp {
left: x,
right: y,
left_comments: Vec::new(),
operator_comments: Vec::new(),
trailing_comments: Vec::new(),
inferred_type: None,
})),
false_value: Some(Expression::Null(crate::expressions::Null)),
original_name: Some("IFF".to_string()),
inferred_type: None,
})))
}
// TIMESTAMP(x) -> CAST(x AS TIMESTAMPTZ) in Snowflake
"TIMESTAMP" if f.args.len() == 1 => {
let arg = f.args.into_iter().next().unwrap();
Ok(Expression::Cast(Box::new(Cast {
this: arg,
to: DataType::Custom {
name: "TIMESTAMPTZ".to_string(),
},
trailing_comments: Vec::new(),
double_colon_syntax: false,
format: None,
default: None,
inferred_type: None,
})))
}
// TIMESTAMP(x, tz) -> CONVERT_TIMEZONE(tz, CAST(x AS TIMESTAMP)) in Snowflake
"TIMESTAMP" if f.args.len() == 2 => {
let mut args = f.args;
let value = args.remove(0);
let tz = args.remove(0);
Ok(Expression::Function(Box::new(Function::new(
"CONVERT_TIMEZONE".to_string(),
vec![
tz,
Expression::Cast(Box::new(Cast {
this: value,
to: DataType::Timestamp {
precision: None,
timezone: false,
},
trailing_comments: Vec::new(),
double_colon_syntax: false,
format: None,
default: None,
inferred_type: None,
})),
],
))))
}
// TIME(h, m, s) -> TIME_FROM_PARTS(h, m, s) in Snowflake
"TIME" if f.args.len() == 3 => Ok(Expression::Function(Box::new(Function::new(
"TIME_FROM_PARTS".to_string(),
f.args,
)))),
// DIV0(x, y) -> IFF(y = 0 AND NOT x IS NULL, 0, x / y)
"DIV0" if f.args.len() == 2 => {
let mut args = f.args;
let x = args.remove(0);
let y = args.remove(0);
// Need parens around complex expressions
let x_expr = Self::maybe_paren(x.clone());
let y_expr = Self::maybe_paren(y.clone());
Ok(Expression::IfFunc(Box::new(crate::expressions::IfFunc {
condition: Expression::And(Box::new(BinaryOp::new(
Expression::Eq(Box::new(BinaryOp::new(
y_expr.clone(),
Expression::number(0),
))),
Expression::Not(Box::new(crate::expressions::UnaryOp {
this: Expression::IsNull(Box::new(crate::expressions::IsNull {
this: x_expr.clone(),
not: false,
postfix_form: false,
})),
inferred_type: None,
})),
))),
true_value: Expression::number(0),
false_value: Some(Expression::Div(Box::new(BinaryOp::new(x_expr, y_expr)))),
original_name: Some("IFF".to_string()),
inferred_type: None,
})))
}
// DIV0NULL(x, y) -> IFF(y = 0 OR y IS NULL, 0, x / y)
"DIV0NULL" if f.args.len() == 2 => {
let mut args = f.args;
let x = args.remove(0);
let y = args.remove(0);
let x_expr = Self::maybe_paren(x.clone());
let y_expr = Self::maybe_paren(y.clone());
Ok(Expression::IfFunc(Box::new(crate::expressions::IfFunc {
condition: Expression::Or(Box::new(BinaryOp::new(
Expression::Eq(Box::new(BinaryOp::new(
y_expr.clone(),
Expression::number(0),
))),
Expression::IsNull(Box::new(crate::expressions::IsNull {
this: y_expr.clone(),
not: false,
postfix_form: false,
})),
))),
true_value: Expression::number(0),
false_value: Some(Expression::Div(Box::new(BinaryOp::new(x_expr, y_expr)))),
original_name: Some("IFF".to_string()),
inferred_type: None,
})))
}
// ZEROIFNULL(x) -> IFF(x IS NULL, 0, x)
"ZEROIFNULL" if f.args.len() == 1 => {
let x = f.args.into_iter().next().unwrap();
Ok(Expression::IfFunc(Box::new(crate::expressions::IfFunc {
condition: Expression::IsNull(Box::new(crate::expressions::IsNull {
this: x.clone(),
not: false,
postfix_form: false,
})),
true_value: Expression::number(0),
false_value: Some(x),
original_name: Some("IFF".to_string()),
inferred_type: None,
})))
}
// NULLIFZERO(x) -> IFF(x = 0, NULL, x)
"NULLIFZERO" if f.args.len() == 1 => {
let x = f.args.into_iter().next().unwrap();
Ok(Expression::IfFunc(Box::new(crate::expressions::IfFunc {
condition: Expression::Eq(Box::new(BinaryOp::new(
x.clone(),
Expression::number(0),
))),
true_value: Expression::Null(crate::expressions::Null),
false_value: Some(x),
original_name: Some("IFF".to_string()),
inferred_type: None,
})))
}
// TRY_TO_TIME('string') -> TRY_CAST('string' AS TIME) when single string arg
"TRY_TO_TIME" => {
if f.args.len() == 1 {
if let Expression::Literal(lit) = &f.args[0] {
if let crate::expressions::Literal::String(_) = lit.as_ref() {
return Ok(Expression::TryCast(Box::new(Cast {
this: f.args.into_iter().next().unwrap(),
to: crate::expressions::DataType::Time {
precision: None,
timezone: false,
},
double_colon_syntax: false,
trailing_comments: Vec::new(),
format: None,
default: None,
inferred_type: None,
})));
}
}
}
// Normalize format string (2nd arg) if present
let mut args = f.args;
if args.len() >= 2 {
args[1] = Self::normalize_format_arg(args[1].clone());
}
Ok(Expression::Function(Box::new(Function::new(
"TRY_TO_TIME".to_string(),
args,
))))
}
// TRY_TO_TIMESTAMP('string') -> TRY_CAST('string' AS TIMESTAMP) when single string arg
// Convert if the string is NOT a pure numeric/epoch value
"TRY_TO_TIMESTAMP" => {
if f.args.len() == 1 {
if let Expression::Literal(lit) = &f.args[0] {
if let crate::expressions::Literal::String(s) = lit.as_ref() {
if !Self::looks_like_epoch(s) {
return Ok(Expression::TryCast(Box::new(Cast {
this: f.args.into_iter().next().unwrap(),
to: DataType::Timestamp {
precision: None,
timezone: false,
},
double_colon_syntax: false,
trailing_comments: Vec::new(),
format: None,
default: None,
inferred_type: None,
})));
}
}
}
}
// Normalize format string (2nd arg) if present
let mut args = f.args;
if args.len() >= 2 {
args[1] = Self::normalize_format_arg(args[1].clone());
}
Ok(Expression::Function(Box::new(Function::new(
"TRY_TO_TIMESTAMP".to_string(),
args,
))))
}
// TRY_TO_DATE('string') -> TRY_CAST('string' AS DATE) when single string arg
"TRY_TO_DATE" => {
if f.args.len() == 1 {
if let Expression::Literal(lit) = &f.args[0] {
if let crate::expressions::Literal::String(s) = lit.as_ref() {
// Only convert if the string looks like a date
if s.contains('-') && s.len() >= 8 && s.len() <= 12 {
return Ok(Expression::TryCast(Box::new(Cast {
this: f.args.into_iter().next().unwrap(),
to: crate::expressions::DataType::Date,
double_colon_syntax: false,
trailing_comments: Vec::new(),
format: None,
default: None,
inferred_type: None,
})));
}
}
}
}
// Normalize format string (2nd arg) if present
let mut args = f.args;
if args.len() >= 2 {
args[1] = Self::normalize_format_arg(args[1].clone());
}
Ok(Expression::Function(Box::new(Function::new(
"TRY_TO_DATE".to_string(),
args,
))))
}
// TRY_TO_DOUBLE -> keep as TRY_TO_DOUBLE in Snowflake (native function)
"TRY_TO_DOUBLE" => Ok(Expression::Function(Box::new(f))),
// REGEXP_REPLACE with 2 args -> add empty string replacement
"REGEXP_REPLACE" if f.args.len() == 2 => {
let mut args = f.args;
args.push(Expression::Literal(Box::new(
crate::expressions::Literal::String(String::new()),
)));
Ok(Expression::Function(Box::new(Function::new(
"REGEXP_REPLACE".to_string(),
args,
))))
}
// LAST_DAY(x, MONTH) -> LAST_DAY(x) in Snowflake (strip MONTH default)
"LAST_DAY" if f.args.len() == 2 => {
let mut args = f.args;
let date = args.remove(0);
let unit = args.remove(0);
let unit_str = match &unit {
Expression::Column(c) => c.name.name.to_uppercase(),
Expression::Identifier(i) => i.name.to_uppercase(),
_ => String::new(),
};
if unit_str == "MONTH" {
Ok(Expression::Function(Box::new(Function::new(
"LAST_DAY".to_string(),
vec![date],
))))
} else {
Ok(Expression::Function(Box::new(Function::new(
"LAST_DAY".to_string(),
vec![date, unit],
))))
}
}
// EXTRACT('field', expr) function-call syntax -> DATE_PART('field', expr)
"EXTRACT" if f.args.len() == 2 => Ok(Expression::Function(Box::new(Function::new(
"DATE_PART".to_string(),
f.args,
)))),
// ENDS_WITH/ENDSWITH -> EndsWith AST node
"ENDS_WITH" | "ENDSWITH" if f.args.len() == 2 => {
let mut args = f.args;
let this = args.remove(0);
let expr = args.remove(0);
Ok(Expression::EndsWith(Box::new(
crate::expressions::BinaryFunc {
original_name: None,
this,
expression: expr,
inferred_type: None,
},
)))
}
// Pass through everything else
_ => Ok(Expression::Function(Box::new(f))),
}
}
/// Check if a string looks like a datetime (contains date separators, not just digits)
fn looks_like_datetime(s: &str) -> bool {
// A datetime string typically contains dashes, colons, or spaces
// A numeric/epoch string is just digits (possibly with a dot)
s.contains('-') || s.contains(':') || s.contains(' ') || s.contains('/')
}
/// Check if a string looks like an epoch number (only digits, possibly with a dot)
fn looks_like_epoch(s: &str) -> bool {
!s.is_empty() && s.chars().all(|c| c.is_ascii_digit() || c == '.')
}
/// Wrap an expression in parentheses if it's a complex expression (binary op, etc.)
fn maybe_paren(expr: Expression) -> Expression {
match &expr {
Expression::Sub(_) | Expression::Add(_) | Expression::Mul(_) | Expression::Div(_) => {
Expression::Paren(Box::new(crate::expressions::Paren {
this: expr,
trailing_comments: Vec::new(),
}))
}
_ => expr,
}
}
/// Normalize Snowflake date/time format strings to canonical lowercase form.
/// YYYY -> yyyy, MM -> mm, DD -> DD (stays), HH24 -> hh24, HH12 -> hh12,
/// MI -> mi, SS -> ss, FF -> ff, AM/PM -> pm, quoted "T" -> T
fn normalize_snowflake_format(format: &str) -> String {
let mut result = String::new();
let chars: Vec<char> = format.chars().collect();
let mut i = 0;
while i < chars.len() {
// Handle quoted strings like "T" -> T
if chars[i] == '"' {
i += 1;
while i < chars.len() && chars[i] != '"' {
result.push(chars[i]);
i += 1;
}
if i < chars.len() {
i += 1; // skip closing quote
}
continue;
}
let remaining = &format[i..];
let remaining_upper = remaining.to_uppercase();
// Multi-char patterns (check longest first)
if remaining_upper.starts_with("YYYY") {
result.push_str("yyyy");
i += 4;
} else if remaining_upper.starts_with("YY") {
result.push_str("yy");
i += 2;
} else if remaining_upper.starts_with("MMMM") {
result.push_str("mmmm");
i += 4;
} else if remaining_upper.starts_with("MON") {
result.push_str("mon");
i += 3;
} else if remaining_upper.starts_with("MM") {
result.push_str("mm");
i += 2;
} else if remaining_upper.starts_with("DD") {
result.push_str("DD");
i += 2;
} else if remaining_upper.starts_with("DY") {
result.push_str("dy");
i += 2;
} else if remaining_upper.starts_with("HH24") {
result.push_str("hh24");
i += 4;
} else if remaining_upper.starts_with("HH12") {
result.push_str("hh12");
i += 4;
} else if remaining_upper.starts_with("HH") {
result.push_str("hh");
i += 2;
} else if remaining_upper.starts_with("MISS") {
// MISS = MI + SS
result.push_str("miss");
i += 4;
} else if remaining_upper.starts_with("MI") {
result.push_str("mi");
i += 2;
} else if remaining_upper.starts_with("SS") {
result.push_str("ss");
i += 2;
} else if remaining_upper.starts_with("FF") {
// FF followed by a digit (FF1-FF9) keeps the digit
let ff_len = 2;
let digit = if i + ff_len < chars.len() && chars[i + ff_len].is_ascii_digit() {
let d = chars[i + ff_len];
Some(d)
} else {
None
};
if let Some(d) = digit {
result.push_str("ff");
result.push(d);
i += 3;
} else {
// Plain FF -> ff9
result.push_str("ff9");
i += 2;
}
} else if remaining_upper.starts_with("AM") || remaining_upper.starts_with("PM") {
result.push_str("pm");
i += 2;
} else if remaining_upper.starts_with("TZH") {
result.push_str("tzh");
i += 3;
} else if remaining_upper.starts_with("TZM") {
result.push_str("tzm");
i += 3;
} else {
// Keep separators and other characters as-is
result.push(chars[i]);
i += 1;
}
}
result
}
/// Normalize format string argument if it's a string literal
fn normalize_format_arg(expr: Expression) -> Expression {
if let Expression::Literal(lit) = &expr {
if let crate::expressions::Literal::String(s) = lit.as_ref() {
let normalized = Self::normalize_snowflake_format(s);
Expression::Literal(Box::new(crate::expressions::Literal::String(normalized)))
} else {
expr.clone()
}
} else {
expr
}
}
/// Transform a lambda with typed parameters for Snowflake
/// For `a int -> a + a + 1`, transforms to `a -> CAST(a AS INT) + CAST(a AS INT) + 1`
fn transform_typed_lambda(&self, lambda: crate::expressions::LambdaExpr) -> Expression {
use crate::expressions::{DataType, LambdaExpr};
use std::collections::HashMap;
// Build mapping of parameter names to their types
let mut param_types: HashMap<String, DataType> = HashMap::new();
for (i, param) in lambda.parameters.iter().enumerate() {
if let Some(Some(dt)) = lambda.parameter_types.get(i) {
param_types.insert(param.name.to_uppercase(), dt.clone());
}
}
// If no typed parameters, return lambda unchanged
if param_types.is_empty() {
return Expression::Lambda(Box::new(lambda));
}
// Transform the body by replacing parameter references with CAST expressions
let transformed_body = self.replace_lambda_params_with_cast(lambda.body, ¶m_types);
// Return new lambda without type annotations (they're now embedded in CAST)
Expression::Lambda(Box::new(LambdaExpr {
parameters: lambda.parameters,
body: transformed_body,
colon: lambda.colon,
parameter_types: Vec::new(), // Clear type annotations
}))
}
/// Recursively replace column/identifier references to typed lambda parameters with CAST expressions
fn replace_lambda_params_with_cast(
&self,
expr: Expression,
param_types: &std::collections::HashMap<String, crate::expressions::DataType>,
) -> Expression {
use crate::expressions::{BinaryOp, Cast, Paren};
match expr {
// Column reference - check if it matches a typed parameter
Expression::Column(col) if col.table.is_none() => {
let name_upper = col.name.name.to_uppercase();
if let Some(dt) = param_types.get(&name_upper) {
// Wrap in CAST
Expression::Cast(Box::new(Cast {
this: Expression::Column(col),
to: dt.clone(),
double_colon_syntax: false,
trailing_comments: Vec::new(),
format: None,
default: None,
inferred_type: None,
}))
} else {
Expression::Column(col)
}
}
// Identifier reference - check if it matches a typed parameter
Expression::Identifier(id) => {
let name_upper = id.name.to_uppercase();
if let Some(dt) = param_types.get(&name_upper) {
// Wrap in CAST
Expression::Cast(Box::new(Cast {
this: Expression::Identifier(id),
to: dt.clone(),
double_colon_syntax: false,
trailing_comments: Vec::new(),
format: None,
default: None,
inferred_type: None,
}))
} else {
Expression::Identifier(id)
}
}
// Binary operations - recursively transform both sides
Expression::Add(op) => Expression::Add(Box::new(BinaryOp::new(
self.replace_lambda_params_with_cast(op.left, param_types),
self.replace_lambda_params_with_cast(op.right, param_types),
))),
Expression::Sub(op) => Expression::Sub(Box::new(BinaryOp::new(
self.replace_lambda_params_with_cast(op.left, param_types),
self.replace_lambda_params_with_cast(op.right, param_types),
))),
Expression::Mul(op) => Expression::Mul(Box::new(BinaryOp::new(
self.replace_lambda_params_with_cast(op.left, param_types),
self.replace_lambda_params_with_cast(op.right, param_types),
))),
Expression::Div(op) => Expression::Div(Box::new(BinaryOp::new(
self.replace_lambda_params_with_cast(op.left, param_types),
self.replace_lambda_params_with_cast(op.right, param_types),
))),
Expression::Mod(op) => Expression::Mod(Box::new(BinaryOp::new(
self.replace_lambda_params_with_cast(op.left, param_types),
self.replace_lambda_params_with_cast(op.right, param_types),
))),
// Parenthesized expression
Expression::Paren(p) => Expression::Paren(Box::new(Paren {
this: self.replace_lambda_params_with_cast(p.this, param_types),
trailing_comments: p.trailing_comments,
})),
// Function calls - transform arguments
Expression::Function(mut f) => {
f.args = f
.args
.into_iter()
.map(|arg| self.replace_lambda_params_with_cast(arg, param_types))
.collect();
Expression::Function(f)
}
// Comparison operators
Expression::Eq(op) => Expression::Eq(Box::new(BinaryOp::new(
self.replace_lambda_params_with_cast(op.left, param_types),
self.replace_lambda_params_with_cast(op.right, param_types),
))),
Expression::Neq(op) => Expression::Neq(Box::new(BinaryOp::new(
self.replace_lambda_params_with_cast(op.left, param_types),
self.replace_lambda_params_with_cast(op.right, param_types),
))),
Expression::Lt(op) => Expression::Lt(Box::new(BinaryOp::new(
self.replace_lambda_params_with_cast(op.left, param_types),
self.replace_lambda_params_with_cast(op.right, param_types),
))),
Expression::Lte(op) => Expression::Lte(Box::new(BinaryOp::new(
self.replace_lambda_params_with_cast(op.left, param_types),
self.replace_lambda_params_with_cast(op.right, param_types),
))),
Expression::Gt(op) => Expression::Gt(Box::new(BinaryOp::new(
self.replace_lambda_params_with_cast(op.left, param_types),
self.replace_lambda_params_with_cast(op.right, param_types),
))),
Expression::Gte(op) => Expression::Gte(Box::new(BinaryOp::new(
self.replace_lambda_params_with_cast(op.left, param_types),
self.replace_lambda_params_with_cast(op.right, param_types),
))),
// And/Or
Expression::And(op) => Expression::And(Box::new(BinaryOp::new(
self.replace_lambda_params_with_cast(op.left, param_types),
self.replace_lambda_params_with_cast(op.right, param_types),
))),
Expression::Or(op) => Expression::Or(Box::new(BinaryOp::new(
self.replace_lambda_params_with_cast(op.left, param_types),
self.replace_lambda_params_with_cast(op.right, param_types),
))),
// Other expressions - return unchanged
other => other,
}
}
fn transform_aggregate_function(
&self,
f: Box<crate::expressions::AggregateFunction>,
) -> Result<Expression> {
let name_upper = f.name.to_uppercase();
match name_upper.as_str() {
// GROUP_CONCAT -> LISTAGG
"GROUP_CONCAT" if !f.args.is_empty() => Ok(Expression::Function(Box::new(
Function::new("LISTAGG".to_string(), f.args),
))),
// STRING_AGG -> LISTAGG
"STRING_AGG" if !f.args.is_empty() => Ok(Expression::Function(Box::new(
Function::new("LISTAGG".to_string(), f.args),
))),
// APPROX_DISTINCT -> APPROX_COUNT_DISTINCT
"APPROX_DISTINCT" if !f.args.is_empty() => Ok(Expression::Function(Box::new(
Function::new("APPROX_COUNT_DISTINCT".to_string(), f.args),
))),
// BIT_AND -> BITAND_AGG
"BIT_AND" if !f.args.is_empty() => Ok(Expression::Function(Box::new(Function::new(
"BITAND_AGG".to_string(),
f.args,
)))),
// BIT_OR -> BITOR_AGG
"BIT_OR" if !f.args.is_empty() => Ok(Expression::Function(Box::new(Function::new(
"BITOR_AGG".to_string(),
f.args,
)))),
// BIT_XOR -> BITXOR_AGG
"BIT_XOR" if !f.args.is_empty() => Ok(Expression::Function(Box::new(Function::new(
"BITXOR_AGG".to_string(),
f.args,
)))),
// BOOL_AND/BOOLAND_AGG/LOGICAL_AND -> LogicalAnd AST node
"BOOL_AND" | "LOGICAL_AND" | "BOOLAND_AGG" if !f.args.is_empty() => {
let arg = f.args.into_iter().next().unwrap();
Ok(Expression::LogicalAnd(Box::new(AggFunc {
this: arg,
distinct: f.distinct,
filter: f.filter,
order_by: Vec::new(),
name: Some("BOOLAND_AGG".to_string()),
ignore_nulls: None,
having_max: None,
limit: None,
inferred_type: None,
})))
}
// BOOL_OR/BOOLOR_AGG/LOGICAL_OR -> LogicalOr AST node
"BOOL_OR" | "LOGICAL_OR" | "BOOLOR_AGG" if !f.args.is_empty() => {
let arg = f.args.into_iter().next().unwrap();
Ok(Expression::LogicalOr(Box::new(AggFunc {
this: arg,
distinct: f.distinct,
filter: f.filter,
order_by: Vec::new(),
name: Some("BOOLOR_AGG".to_string()),
ignore_nulls: None,
having_max: None,
limit: None,
inferred_type: None,
})))
}
// APPROX_TOP_K - add default k=1 if only one argument
"APPROX_TOP_K" if f.args.len() == 1 => {
let mut args = f.args;
args.push(Expression::number(1));
Ok(Expression::AggregateFunction(Box::new(
crate::expressions::AggregateFunction {
name: "APPROX_TOP_K".to_string(),
args,
distinct: f.distinct,
filter: f.filter,
order_by: Vec::new(),
limit: None,
ignore_nulls: None,
inferred_type: None,
},
)))
}
// SKEW/SKEWNESS -> Skewness AST node
"SKEW" | "SKEWNESS" if !f.args.is_empty() => {
let arg = f.args.into_iter().next().unwrap();
Ok(Expression::Skewness(Box::new(AggFunc {
this: arg,
distinct: f.distinct,
filter: f.filter,
order_by: Vec::new(),
name: Some("SKEW".to_string()),
ignore_nulls: None,
having_max: None,
limit: None,
inferred_type: None,
})))
}
// Pass through everything else
_ => Ok(Expression::AggregateFunction(f)),
}
}
}
/// Convert strftime format specifiers to Snowflake format specifiers
fn strftime_to_snowflake_format(fmt: &str) -> String {
let mut result = String::new();
let chars: Vec<char> = fmt.chars().collect();
let mut i = 0;
while i < chars.len() {
if chars[i] == '%' && i + 1 < chars.len() {
match chars[i + 1] {
'Y' => {
result.push_str("yyyy");
i += 2;
}
'y' => {
result.push_str("yy");
i += 2;
}
'm' => {
result.push_str("mm");
i += 2;
}
'd' => {
result.push_str("DD");
i += 2;
}
'H' => {
result.push_str("hh24");
i += 2;
}
'M' => {
result.push_str("mmmm");
i += 2;
} // %M = full month name
'i' => {
result.push_str("mi");
i += 2;
}
'S' | 's' => {
result.push_str("ss");
i += 2;
}
'f' => {
result.push_str("ff");
i += 2;
}
'w' => {
result.push_str("dy");
i += 2;
} // day of week number
'a' => {
result.push_str("DY");
i += 2;
} // abbreviated day name
'b' => {
result.push_str("mon");
i += 2;
} // abbreviated month name
'T' => {
result.push_str("hh24:mi:ss");
i += 2;
} // time shorthand
_ => {
result.push(chars[i]);
result.push(chars[i + 1]);
i += 2;
}
}
} else {
result.push(chars[i]);
i += 1;
}
}
result
}
#[cfg(test)]
mod tests {
use super::*;
use crate::dialects::Dialect;
fn transpile_to_snowflake(sql: &str) -> String {
let dialect = Dialect::get(DialectType::Generic);
let result = dialect
.transpile(sql, DialectType::Snowflake)
.expect("Transpile failed");
result[0].clone()
}
#[test]
fn test_ifnull_to_coalesce() {
let result = transpile_to_snowflake("SELECT IFNULL(a, b)");
assert!(
result.contains("COALESCE"),
"Expected COALESCE, got: {}",
result
);
}
#[test]
fn test_basic_select() {
let result = transpile_to_snowflake("SELECT a, b FROM users WHERE id = 1");
assert!(result.contains("SELECT"));
assert!(result.contains("FROM users"));
}
#[test]
fn test_group_concat_to_listagg() {
let result = transpile_to_snowflake("SELECT GROUP_CONCAT(name)");
assert!(
result.contains("LISTAGG"),
"Expected LISTAGG, got: {}",
result
);
}
#[test]
fn test_string_agg_to_listagg() {
let result = transpile_to_snowflake("SELECT STRING_AGG(name)");
assert!(
result.contains("LISTAGG"),
"Expected LISTAGG, got: {}",
result
);
}
#[test]
fn test_array_to_array_construct() {
let result = transpile_to_snowflake("SELECT ARRAY(1, 2, 3)");
// ARRAY(1, 2, 3) from Generic -> Snowflake uses [] bracket notation
assert!(
result.contains("[1, 2, 3]"),
"Expected [1, 2, 3], got: {}",
result
);
}
#[test]
fn test_double_quote_identifiers() {
// Snowflake uses double quotes for identifiers
let dialect = SnowflakeDialect;
let config = dialect.generator_config();
assert_eq!(config.identifier_quote, '"');
}
}