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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
# pylint: disable=invalid-name, redefined-outer-name, too-many-lines


import logging

import pytest
import sqlglot
from pytest_mock import MockerFixture
from sqlglot import Dialects, exp, parse_one

from superset.exceptions import QueryClauseValidationException, SupersetParseError
from superset.jinja_context import JinjaTemplateProcessor
from superset.sql.parse import (
    _check_script_length,
    BaseSQLStatement,
    CTASMethod,
    extract_tables_from_statement,
    has_aggregate,
    JinjaSQLResult,
    KQLTokenType,
    KustoKQLStatement,
    LimitMethod,
    Partition,
    process_jinja_sql,
    remove_quotes,
    RLSMethod,
    sanitize_clause,
    split_kql,
    SQLGLOT_DIALECTS,
    SQLScript,
    SQLStatement,
    Table,
    tokenize_kql,
    transpile_to_dialect,
)
from tests.integration_tests.conftest import with_feature_flags


def test_table() -> None:
    """
    Test the `Table` class and its string conversion.

    Special characters in the table, schema, or catalog name should be escaped correctly.
    """  # noqa: E501
    assert str(Table("tbname")) == "tbname"
    assert str(Table("tbname", "schemaname")) == "schemaname.tbname"
    assert (
        str(Table("tbname", "schemaname", "catalogname"))
        == "catalogname.schemaname.tbname"
    )
    assert (
        str(Table("table.name", "schema/name", "catalog\nname"))
        == "catalog%0Aname.schema%2Fname.table%2Ename"
    )


def test_table_qualify() -> None:
    """
    Test the `Table.qualify` method.

    The qualify method should add schema and/or catalog if not already set,
    but should not override existing values.
    """
    # Table with no schema or catalog
    table = Table("tbname")

    # Add schema only
    qualified = table.qualify(schema="schemaname")
    assert qualified.table == "tbname"
    assert qualified.schema == "schemaname"
    assert qualified.catalog is None
    assert str(qualified) == "schemaname.tbname"

    # Add catalog only
    qualified = table.qualify(catalog="catalogname")
    assert qualified.table == "tbname"
    assert qualified.schema is None
    assert qualified.catalog == "catalogname"
    assert str(qualified) == "catalogname.tbname"

    # Add both schema and catalog
    qualified = table.qualify(schema="schemaname", catalog="catalogname")
    assert qualified.table == "tbname"
    assert qualified.schema == "schemaname"
    assert qualified.catalog == "catalogname"
    assert str(qualified) == "catalogname.schemaname.tbname"

    # Table with existing schema - should not override
    table_with_schema = Table("tbname", "existingschema")
    qualified = table_with_schema.qualify(schema="newschema")
    assert qualified.schema == "existingschema"
    assert str(qualified) == "existingschema.tbname"

    # Table with existing catalog - should not override
    table_with_catalog = Table("tbname", catalog="existingcatalog")
    qualified = table_with_catalog.qualify(catalog="newcatalog")
    assert qualified.catalog == "existingcatalog"
    assert str(qualified) == "existingcatalog.tbname"

    # Table with existing schema and catalog - should not override
    fully_qualified = Table("tbname", "existingschema", "existingcatalog")
    qualified = fully_qualified.qualify(schema="newschema", catalog="newcatalog")
    assert qualified.schema == "existingschema"
    assert qualified.catalog == "existingcatalog"
    assert str(qualified) == "existingcatalog.existingschema.tbname"

    # Table with schema but no catalog - should add catalog only
    table_with_schema_only = Table("tbname", "existingschema")
    qualified = table_with_schema_only.qualify(
        schema="newschema", catalog="catalogname"
    )
    assert qualified.schema == "existingschema"
    assert qualified.catalog == "catalogname"
    assert str(qualified) == "catalogname.existingschema.tbname"

    # Table with catalog but no schema - should add schema only
    table_with_catalog_only = Table("tbname", catalog="existingcatalog")
    qualified = table_with_catalog_only.qualify(
        schema="schemaname", catalog="newcatalog"
    )
    assert qualified.schema == "schemaname"
    assert qualified.catalog == "existingcatalog"
    assert str(qualified) == "existingcatalog.schemaname.tbname"

    # Calling qualify with no arguments should return equivalent table
    qualified = table.qualify()
    assert qualified.table == table.table
    assert qualified.schema == table.schema
    assert qualified.catalog == table.catalog


def test_partition() -> None:
    """
    Test the `Partition` class and its string conversion.
    """
    # Test partitioned table with partition columns
    partition = Partition(is_partitioned_table=True, partition_column=("col1", "col2"))
    assert partition.is_partitioned_table is True
    assert partition.partition_column == ("col1", "col2")
    assert (
        str(partition)
        == "Partition(is_partitioned_table=True, partition_column=[col1, col2])"
    )

    # Test non-partitioned table
    partition_none = Partition(is_partitioned_table=False, partition_column=None)
    assert partition_none.is_partitioned_table is False
    assert partition_none.partition_column is None
    assert (
        str(partition_none)
        == "Partition(is_partitioned_table=False, partition_column=[None])"
    )

    # Test equality
    partition1 = Partition(is_partitioned_table=True, partition_column=("col1",))
    partition2 = Partition(is_partitioned_table=True, partition_column=("col1",))
    partition3 = Partition(is_partitioned_table=True, partition_column=("col2",))
    assert partition1 == partition2
    assert partition1 != partition3

    # A frozen dataclass with a tuple field must be hashable (a list field would
    # raise TypeError: unhashable type at hash time).
    assert hash(partition1) == hash(partition2)
    assert len({partition1, partition2, partition3}) == 2


def extract_tables_from_sql(sql: str, engine: str = "postgresql") -> set[Table]:
    """
    Helper function to extract tables from SQL.
    """
    dialect = SQLGLOT_DIALECTS.get(engine)
    return {
        table
        for statement in SQLScript(sql, engine).statements
        for table in extract_tables_from_statement(statement._parsed, dialect)
    }


def test_extract_tables_from_sql() -> None:
    """
    Test that referenced tables are parsed correctly from the SQL.
    """
    assert extract_tables_from_sql("SELECT * FROM tbname") == {Table("tbname")}
    assert extract_tables_from_sql("SELECT * FROM tbname foo") == {Table("tbname")}
    assert extract_tables_from_sql("SELECT * FROM tbname AS foo") == {Table("tbname")}

    # underscore
    assert extract_tables_from_sql("SELECT * FROM tb_name") == {Table("tb_name")}

    # quotes
    assert extract_tables_from_sql('SELECT * FROM "tbname"') == {Table("tbname")}

    # unicode
    assert extract_tables_from_sql('SELECT * FROM "tb_name" WHERE city = "Lübeck"') == {
        Table("tb_name")
    }

    # columns
    assert extract_tables_from_sql("SELECT field1, field2 FROM tb_name") == {
        Table("tb_name")
    }
    assert extract_tables_from_sql("SELECT t1.f1, t2.f2 FROM t1, t2") == {
        Table("t1"),
        Table("t2"),
    }

    # named table
    assert extract_tables_from_sql(
        "SELECT a.date, a.field FROM left_table a LIMIT 10"
    ) == {Table("left_table")}

    assert extract_tables_from_sql(
        "SELECT FROM (SELECT FROM forbidden_table) AS forbidden_table;"
    ) == {Table("forbidden_table")}

    assert extract_tables_from_sql(
        "select * from (select * from forbidden_table) forbidden_table"
    ) == {Table("forbidden_table")}


def test_extract_tables_subselect() -> None:
    """
    Test that tables inside subselects are parsed correctly.
    """
    assert extract_tables_from_sql(
        """
SELECT sub.*
FROM (
    SELECT *
        FROM s1.t1
        WHERE day_of_week = 'Friday'
    ) sub, s2.t2
WHERE sub.resolution = 'NONE'
"""
    ) == {Table("t1", "s1"), Table("t2", "s2")}

    assert extract_tables_from_sql(
        """
SELECT sub.*
FROM (
    SELECT *
    FROM s1.t1
    WHERE day_of_week = 'Friday'
) sub
WHERE sub.resolution = 'NONE'
"""
    ) == {Table("t1", "s1")}

    assert extract_tables_from_sql(
        """
SELECT * FROM t1
WHERE s11 > ANY (
    SELECT COUNT(*) /* no hint */ FROM t2
    WHERE NOT EXISTS (
        SELECT * FROM t3
        WHERE ROW(5*t2.s1,77)=(
            SELECT 50,11*s1 FROM t4
        )
    )
)
"""
    ) == {Table("t1"), Table("t2"), Table("t3"), Table("t4")}


def test_extract_tables_select_in_expression() -> None:
    """
    Test that parser works with `SELECT`s used as expressions.
    """
    assert extract_tables_from_sql("SELECT f1, (SELECT count(1) FROM t2) FROM t1") == {
        Table("t1"),
        Table("t2"),
    }
    assert extract_tables_from_sql(
        "SELECT f1, (SELECT count(1) FROM t2) as f2 FROM t1"
    ) == {
        Table("t1"),
        Table("t2"),
    }


def test_extract_tables_parenthesis() -> None:
    """
    Test that parenthesis are parsed correctly.
    """
    assert extract_tables_from_sql("SELECT f1, (x + y) AS f2 FROM t1") == {Table("t1")}


def test_extract_tables_with_schema() -> None:
    """
    Test that schemas are parsed correctly.
    """
    assert extract_tables_from_sql("SELECT * FROM schemaname.tbname") == {
        Table("tbname", "schemaname")
    }
    assert extract_tables_from_sql('SELECT * FROM "schemaname"."tbname"') == {
        Table("tbname", "schemaname")
    }
    assert extract_tables_from_sql('SELECT * FROM "schemaname"."tbname" foo') == {
        Table("tbname", "schemaname")
    }
    assert extract_tables_from_sql('SELECT * FROM "schemaname"."tbname" AS foo') == {
        Table("tbname", "schemaname")
    }


def test_extract_tables_union() -> None:
    """
    Test that `UNION` queries work as expected.
    """
    assert extract_tables_from_sql("SELECT * FROM t1 UNION SELECT * FROM t2") == {
        Table("t1"),
        Table("t2"),
    }
    assert extract_tables_from_sql("SELECT * FROM t1 UNION ALL SELECT * FROM t2") == {
        Table("t1"),
        Table("t2"),
    }
    assert extract_tables_from_sql(
        "SELECT * FROM t1 INTERSECT ALL SELECT * FROM t2"
    ) == {
        Table("t1"),
        Table("t2"),
    }


def test_extract_tables_select_from_values() -> None:
    """
    Test that selecting from values returns no tables.
    """
    assert extract_tables_from_sql("SELECT * FROM VALUES (13, 42)") == set()


def test_extract_tables_select_array() -> None:
    """
    Test that queries selecting arrays work as expected.
    """
    assert extract_tables_from_sql(
        """
SELECT ARRAY[1, 2, 3] AS my_array
FROM t1 LIMIT 10
"""
    ) == {Table("t1")}


def test_extract_tables_select_if() -> None:
    """
    Test that queries with an `IF` work as expected.
    """
    assert extract_tables_from_sql(
        """
SELECT IF(CARDINALITY(my_array) >= 3, my_array[3], NULL)
FROM t1 LIMIT 10
"""
    ) == {Table("t1")}


def test_extract_tables_with_catalog() -> None:
    """
    Test that catalogs are parsed correctly.
    """
    assert extract_tables_from_sql("SELECT * FROM catalogname.schemaname.tbname") == {
        Table("tbname", "schemaname", "catalogname")
    }


def test_extract_tables_illdefined() -> None:
    """
    Test that ill-defined tables return an empty set.
    """
    with pytest.raises(SupersetParseError) as excinfo:
        extract_tables_from_sql("SELECT * FROM schemaname.")
    assert str(excinfo.value) == "Error parsing near '.' at line 1:25"

    with pytest.raises(SupersetParseError) as excinfo:
        extract_tables_from_sql("SELECT * FROM catalogname.schemaname.")
    assert str(excinfo.value) == "Error parsing near '.' at line 1:37"

    with pytest.raises(SupersetParseError) as excinfo:
        extract_tables_from_sql("SELECT * FROM catalogname..")
    assert str(excinfo.value) == "Error parsing near '.' at line 1:27"

    with pytest.raises(SupersetParseError) as excinfo:
        extract_tables_from_sql('SELECT * FROM "tbname')
    assert str(excinfo.value) == "Unable to parse script"

    # odd edge case that works
    assert extract_tables_from_sql("SELECT * FROM catalogname..tbname") == {
        Table(table="tbname", schema=None, catalog="catalogname")
    }


def test_extract_tables_show_tables_from() -> None:
    """
    Test `SHOW TABLES FROM`.

    No individual table target is extractable, so the statement must be
    flagged as unparseable for authorization purposes instead of passing
    strict scoping with an empty table set.
    """
    assert (
        extract_tables_from_sql("SHOW TABLES FROM s1 like '%order%'", "mysql") == set()
    )
    assert SQLScript(
        "SHOW TABLES FROM s1 like '%order%'", "mysql"
    ).has_unparseable_statement


def test_extract_tables_show_create_table() -> None:
    """
    Test `SHOW CREATE TABLE`.

    The target table must enter table-level authorization.
    """
    assert extract_tables_from_sql("SHOW CREATE TABLE s1.t1", "mysql") == {
        Table("t1", "s1")
    }
    assert not SQLScript("SHOW CREATE TABLE s1.t1", "mysql").has_unparseable_statement


def test_format_show_tables() -> None:
    """
    Test format when `ast.sql()` raises an exception.
    """
    assert (
        SQLScript("SHOW TABLES FROM s1 like '%order%'", "mysql").format()
        == "SHOW TABLES FROM s1 LIKE '%order%'"
    )


def test_format_no_dialect() -> None:
    """
    Test format with an engine that has no corresponding dialect.
    """
    assert (
        SQLScript("SELECT col FROM t WHERE col NOT IN (1, 2)", "dremio").format()
        == """
SELECT
  col
FROM t
WHERE
  NOT col IN (1, 2)
        """.strip()
    )


def test_format_oracle_group_by_keeps_explicit_expressions() -> None:
    """
    Test that formatting Oracle SQL doesn't rewrite ``GROUP BY`` to ordinals.

    Oracle doesn't support positional grouping (``GROUP BY 1, 2``) and fails
    with ``ORA-00979: not a GROUP BY expression``. sqlglot < 27.21.0 rewrote
    ``GROUP BY`` expressions that matched aliased projections into ordinals
    when generating Oracle SQL, breaking chart queries.

    Regression test for https://github.com/apache/superset/issues/35414,
    fixed by upgrading sqlglot.
    """
    sql = (
        "SELECT TRUNC(CAST(order_date AS DATE), 'MONTH') AS __timestamp, "
        'region AS region, SUM(sales) AS "SUM(sales)" '
        "FROM orders "
        "GROUP BY TRUNC(CAST(order_date AS DATE), 'MONTH'), region "
        'ORDER BY "SUM(sales)" DESC'
    )
    formatted = SQLStatement(sql, engine="oracle").format()

    # pretty-formatting puts each `GROUP BY` item on its own line
    group_by_clause = formatted.split("GROUP BY")[1].split("ORDER BY")[0]
    group_by_items = [
        line.strip().rstrip(",") for line in group_by_clause.strip().splitlines()
    ]
    assert group_by_items == [
        "TRUNC(CAST(order_date AS DATE), 'MONTH')",
        "region",
    ]
    # no item should have been replaced by a positional reference
    assert not any(item.isdigit() for item in group_by_items)


def test_format_oracle_group_by_keeps_explicit_expressions_subquery() -> None:
    """
    Test that formatting an Oracle chart query doesn't rewrite ``GROUP BY``
    to ordinals when the aggregated column comes from a virtual dataset
    subquery.

    This mirrors the query shape SQLAlchemy generates for a bar chart with a
    dimension and a ``COUNT(*)`` metric on a virtual dataset, which is the
    reproduction reported in
    https://github.com/apache/superset/issues/28327 (``ORA-00979: not a
    GROUP BY expression``). Fixed by the same sqlglot upgrade that resolved
    https://github.com/apache/superset/issues/35414.
    """
    sql = (
        "SELECT bar AS bar, COUNT(*) AS count "
        "FROM (SELECT 'foo' AS bar FROM dual) AS virtual_table "
        "GROUP BY bar"
    )
    formatted = SQLStatement(sql, engine="oracle").format()

    group_by_clause = formatted.split("GROUP BY")[1]
    group_by_items = [
        line.strip().rstrip(",") for line in group_by_clause.strip().splitlines()
    ]
    assert group_by_items == ["bar"]
    # no item should have been replaced by a positional reference
    assert not any(item.isdigit() for item in group_by_items)


def test_format_hana_preserves_quoted_identifier_casing() -> None:
    """
    Regression test for https://github.com/apache/superset/issues/39328.

    HANA is mapped to the Postgres sqlglot dialect (there's no dedicated HANA
    dialect upstream). HANA calculation-view invocations address the view as
    a quoted, case-sensitive identifier followed by a PLACEHOLDER parameter
    list, e.g. ``"zbw.10_001/INVENTORY"('PLACEHOLDER' = (...))`` -- sqlglot's
    parser treats that shape as a function call, so Postgres's inherited
    function-name normalization (``NORMALIZE_FUNCTIONS = "upper"``) re-cased
    the quoted identifier to ``"ZBW.10_001/INVENTORY"``. HANA resolves
    calculation-view names case-sensitively, so the re-cased identifier no
    longer exists and SQL Lab fails with ``invalid table name`` even though
    the user's original query was valid.
    """
    sql = (
        'SELECT * FROM _sys_bic."zbw.10_001/INVENTORY"\n'
        "(\n"
        "  'PLACEHOLDER' = ('$$IP_DATE_TO$$', ''),\n"
        "  'PLACEHOLDER' = ('$$IP_DATE_FROM$$', '')\n"
        ")"
    )
    formatted = SQLStatement(sql, engine="hana").format()

    assert '"zbw.10_001/INVENTORY"' in formatted
    assert "$$IP_DATE_TO$$" in formatted
    assert "$$IP_DATE_FROM$$" in formatted


def test_format_hana_custom_function_call_untouched() -> None:
    """
    The HANA dialect disables function-name normalization entirely (see
    ``test_format_hana_preserves_quoted_identifier_casing``), which only
    affects functions sqlglot doesn't recognize (parsed as
    ``exp.Anonymous`` -- built-ins like ``COUNT`` have their own dedicated
    AST node and always generate with a fixed canonical casing regardless).
    An unrecognized, mixed-case function call must round-trip with its
    original casing intact rather than being forced to uppercase.
    """
    formatted = SQLStatement("SELECT MyCustomFunc(col) FROM t", engine="hana").format()

    assert "MyCustomFunc(col)" in formatted


def test_split_no_dialect() -> None:
    """
    Test the statement split when the engine has no corresponding dialect.
    """
    sql = "SELECT col FROM t WHERE col NOT IN (1, 2); SELECT * FROM t; SELECT foo"
    statements = SQLScript(sql, "dremio").statements
    assert len(statements) == 3
    assert statements[0].format() == "SELECT\n  col\nFROM t\nWHERE\n  NOT col IN (1, 2)"
    assert statements[1].format() == "SELECT\n  *\nFROM t"
    assert statements[2].format() == "SELECT\n  foo"


def test_extract_tables_show_columns_from() -> None:
    """
    Test `SHOW COLUMNS FROM`.
    """
    assert extract_tables_from_sql("SHOW COLUMNS FROM t1") == {Table("t1")}


def test_extract_tables_where_subquery() -> None:
    """
    Test that tables in a `WHERE` subquery are parsed correctly.
    """
    assert extract_tables_from_sql(
        """
SELECT name
FROM t1
WHERE regionkey = (SELECT max(regionkey) FROM t2)
"""
    ) == {Table("t1"), Table("t2")}

    assert extract_tables_from_sql(
        """
SELECT name
FROM t1
WHERE regionkey IN (SELECT regionkey FROM t2)
"""
    ) == {Table("t1"), Table("t2")}

    assert extract_tables_from_sql(
        """
SELECT name
FROM t1
WHERE EXISTS (SELECT 1 FROM t2 WHERE t1.regionkey = t2.regionkey);
"""
    ) == {Table("t1"), Table("t2")}


def test_extract_tables_describe() -> None:
    """
    Test `DESCRIBE`.
    """
    assert extract_tables_from_sql("DESCRIBE t1") == {Table("t1")}


def test_extract_tables_show_partitions() -> None:
    """
    Test `SHOW PARTITIONS`.
    """
    assert extract_tables_from_sql(
        """
SHOW PARTITIONS FROM orders
WHERE ds >= '2013-01-01' ORDER BY ds DESC
"""
    ) == {Table("orders")}


def test_extract_tables_join() -> None:
    """
    Test joins.
    """
    assert extract_tables_from_sql(
        "SELECT t1.*, t2.* FROM t1 JOIN t2 ON t1.a = t2.a;"
    ) == {
        Table("t1"),
        Table("t2"),
    }

    assert extract_tables_from_sql(
        """
SELECT a.date, b.name
FROM left_table a
JOIN (
    SELECT
        CAST((b.year) as VARCHAR) date,
        name
    FROM right_table
) b
ON a.date = b.date
"""
    ) == {Table("left_table"), Table("right_table")}

    assert extract_tables_from_sql(
        """
SELECT a.date, b.name
FROM left_table a
LEFT INNER JOIN (
    SELECT
        CAST((b.year) as VARCHAR) date,
        name
    FROM right_table
) b
ON a.date = b.date
"""
    ) == {Table("left_table"), Table("right_table")}

    assert extract_tables_from_sql(
        """
SELECT a.date, b.name
FROM left_table a
RIGHT OUTER JOIN (
    SELECT
        CAST((b.year) as VARCHAR) date,
        name
    FROM right_table
) b
ON a.date = b.date
"""
    ) == {Table("left_table"), Table("right_table")}

    assert extract_tables_from_sql(
        """
SELECT a.date, b.name
FROM left_table a
FULL OUTER JOIN (
    SELECT
        CAST((b.year) as VARCHAR) date,
        name
        FROM right_table
) b
ON a.date = b.date
"""
    ) == {Table("left_table"), Table("right_table")}


def test_extract_tables_semi_join() -> None:
    """
    Test `LEFT SEMI JOIN`.
    """
    assert extract_tables_from_sql(
        """
SELECT a.date, b.name
FROM left_table a
LEFT SEMI JOIN (
    SELECT
        CAST((b.year) as VARCHAR) date,
        name
    FROM right_table
) b
ON a.data = b.date
"""
    ) == {Table("left_table"), Table("right_table")}


def test_extract_tables_combinations() -> None:
    """
    Test a complex case with nested queries.
    """
    assert extract_tables_from_sql(
        """
SELECT * FROM t1
WHERE s11 > ANY (
    SELECT * FROM t1 UNION ALL SELECT * FROM (
        SELECT t6.*, t3.* FROM t6 JOIN t3 ON t6.a = t3.a
    ) tmp_join
    WHERE NOT EXISTS (
        SELECT * FROM t3
        WHERE ROW(5*t3.s1,77)=(
            SELECT 50,11*s1 FROM t4
        )
    )
)
"""
    ) == {Table("t1"), Table("t3"), Table("t4"), Table("t6")}

    assert extract_tables_from_sql(
        """
SELECT * FROM (
    SELECT * FROM (
        SELECT * FROM (
            SELECT * FROM EmployeeS
        ) AS S1
    ) AS S2
) AS S3
"""
    ) == {Table("EmployeeS")}


def test_extract_tables_with() -> None:
    """
    Test `WITH`.
    """
    assert extract_tables_from_sql(
        """
WITH
    x AS (SELECT a FROM t1),
    y AS (SELECT a AS b FROM t2),
    z AS (SELECT b AS c FROM t3)
SELECT c FROM z
"""
    ) == {Table("t1"), Table("t2"), Table("t3")}

    assert extract_tables_from_sql(
        """
WITH
    x AS (SELECT a FROM t1),
    y AS (SELECT a AS b FROM x),
    z AS (SELECT b AS c FROM y)
SELECT c FROM z
"""
    ) == {Table("t1")}


def test_extract_tables_reusing_aliases() -> None:
    """Test that the parser follows aliases.

    A non-recursive ``WITH`` item sees only items declared before it, so a forward
    reference resolves to the table of that name -- a real read that must be extracted.
    """
    # `q1` first: the `q2` in its body, and `q2`'s `src`, are both tables.
    assert extract_tables_from_sql(
        """
with q1 as ( select key from q2 where key = '5'),
q2 as ( select key from src where key = '5')
select * from (select key from q1) a
"""
    ) == {Table("q2"), Table("src")}

    # `src` first: its `q2` is a table; `q2`'s `src` and the outer `src` are the CTE.
    assert extract_tables_from_sql(
        """
with src as ( select key from q2 where key = '5'),
q2 as ( select key from src where key = '5')
select * from (select key from src) a
"""
    ) == {Table("q2")}


def test_extract_tables_cte_name_shared_with_table() -> None:
    """Test that a CTE's name does not hide reads of the table it is named after.

    Only a reference resolving to the CTE may be excluded; dropping any other costs it
    both its row filter and its access check.
    """
    # A qualified reference -- in the CTE body or elsewhere -- is the table.
    assert extract_tables_from_sql(
        "WITH orders AS (SELECT * FROM public.orders) SELECT * FROM orders"
    ) == {Table("orders", "public")}
    assert extract_tables_from_sql(
        "WITH orders AS (SELECT 1 AS d) "
        "SELECT * FROM (SELECT * FROM public.orders) AS z"
    ) == {Table("orders", "public")}

    # A non-recursive CTE cannot see itself, so its own name in its body is the table.
    assert extract_tables_from_sql(
        "WITH orders AS (SELECT * FROM orders) SELECT * FROM orders"
    ) == {Table("orders")}

    # A catalog disqualifies like a schema; `cat..orders` is checked only when pivoted.
    assert extract_tables_from_sql(
        "WITH orders AS (SELECT 1 AS amt, 'a' AS mth) "
        "SELECT * FROM cat..orders PIVOT(SUM(amt) FOR mth IN ('a'))",
        engine="snowflake",
    ) == {Table("orders", None, "cat")}


def test_extract_tables_cte_reference_not_table() -> None:
    """Test the counterpart: a reference that resolves to a CTE is not a table.

    A recursive item's reference to itself is the shape a bare-name compare gets wrong.
    """
    assert (
        extract_tables_from_sql(
            "WITH RECURSIVE t AS ("
            "SELECT 1 AS n UNION ALL SELECT n + 1 FROM t WHERE n < 5"
            ") SELECT * FROM t"
        )
        == set()
    )


def test_extract_tables_pivoted_cte_reference_is_not_a_table() -> None:
    """Test that pivoting a CTE reference does not make it a table read.

    Pivoting yields a new relation, so sqlglot keeps the reference as an ``exp.Table``
    -- the one shape where a CTE reference reaches ``is_cte()`` unqualified.
    """
    assert extract_tables_from_sql(
        "WITH c AS (SELECT a, b FROM other_table) "
        "SELECT * FROM c PIVOT(SUM(b) FOR a IN ('p'))",
        engine="snowflake",
    ) == {Table("other_table")}
    # Also when the pivot sits inside a derived table.
    assert extract_tables_from_sql(
        "WITH c AS (SELECT a, b FROM other_table) "
        "SELECT * FROM (SELECT * FROM c PIVOT(SUM(b) FOR a IN ('p'))) AS z",
        engine="snowflake",
    ) == {Table("other_table")}


def test_extract_tables_aliased_cte_does_not_hide_table() -> None:
    """Test that aliasing a CTE reference does not erase a table of the same name.

    ``Scope.sources`` is keyed by ``alias_or_name`` and would file the table under the
    CTE's alias; ``cte_sources`` is keyed by CTE name only.
    """
    assert extract_tables_from_sql(
        "WITH c AS (SELECT 1 AS n) SELECT s2.* FROM c AS other_table, other_table AS s2"
    ) == {Table("other_table")}
    assert extract_tables_from_sql(
        "WITH c AS (SELECT 1 AS n) "
        "SELECT s2.* FROM c AS other_table LEFT JOIN other_table AS s2 ON TRUE"
    ) == {Table("other_table")}


def test_extract_tables_cte_reference_over_reported() -> None:
    """Test the two shapes that over-report a CTE reference as a table.

    A spurious access check, not a missing one. Pinned so a change either way is meant.
    """
    # PostgreSQL resolves `foo` to the CTE; this reports the table.
    assert extract_tables_from_sql("WITH Foo AS (SELECT 1 AS d) SELECT * FROM foo") == {
        Table("foo")
    }
    # Legal under RECURSIVE: `q2` is the CTE declared below, not a table.
    assert extract_tables_from_sql(
        "WITH RECURSIVE q1 AS (SELECT key FROM q2), q2 AS (SELECT 1 AS key) "
        "SELECT * FROM q1"
    ) == {Table("q2")}


def test_extract_tables_multistatement() -> None:
    """
    Test that the parser works with multiple statements.
    """
    assert extract_tables_from_sql("SELECT * FROM t1; SELECT * FROM t2") == {
        Table("t1"),
        Table("t2"),
    }
    assert extract_tables_from_sql("SELECT * FROM t1; SELECT * FROM t2;") == {
        Table("t1"),
        Table("t2"),
    }
    assert extract_tables_from_sql(
        "ADD JAR file:///hive.jar; SELECT * FROM t1;",
        engine="hive",
    ) == {Table("t1")}


def test_extract_tables_complex() -> None:
    """
    Test a few complex queries.
    """
    assert extract_tables_from_sql(
        """
SELECT sum(m_examples) AS "sum__m_example"
FROM (
    SELECT
        COUNT(DISTINCT id_userid) AS m_examples,
        some_more_info
    FROM my_b_table b
    JOIN my_t_table t ON b.ds=t.ds
    JOIN my_l_table l ON b.uid=l.uid
    WHERE
        b.rid IN (
            SELECT other_col
            FROM inner_table
        )
        AND l.bla IN ('x', 'y')
    GROUP BY 2
    ORDER BY 2 ASC
) AS "meh"
ORDER BY "sum__m_example" DESC
LIMIT 10;
"""
    ) == {
        Table("my_l_table"),
        Table("my_b_table"),
        Table("my_t_table"),
        Table("inner_table"),
    }

    assert extract_tables_from_sql(
        """
SELECT *
FROM table_a AS a, table_b AS b, table_c as c
WHERE a.id = b.id and b.id = c.id
"""
    ) == {Table("table_a"), Table("table_b"), Table("table_c")}

    assert extract_tables_from_sql(
        """
SELECT somecol AS somecol
FROM (
    WITH bla AS (
        SELECT col_a
        FROM a
        WHERE
            1=1
            AND column_of_choice NOT IN (
                SELECT interesting_col
                FROM b
            )
    ),
    rb AS (
        SELECT yet_another_column
        FROM (
            SELECT a
            FROM c
            GROUP BY the_other_col
        ) not_table
        LEFT JOIN bla foo
        ON foo.prop = not_table.bad_col0
        WHERE 1=1
        GROUP BY
            not_table.bad_col1 ,
            not_table.bad_col2 ,
        ORDER BY not_table.bad_col_3 DESC ,
            not_table.bad_col4 ,
            not_table.bad_col5
    )
    SELECT random_col
    FROM d
    WHERE 1=1
    UNION ALL SELECT even_more_cols
    FROM e
    WHERE 1=1
    UNION ALL SELECT lets_go_deeper
    FROM f
    WHERE 1=1
    GROUP BY last_col
    LIMIT 50000
)
"""
    ) == {Table("a"), Table("b"), Table("c"), Table("d"), Table("e"), Table("f")}


def test_extract_tables_mixed_from_clause() -> None:
    """
    Test that the parser handles a `FROM` clause with table and subselect.
    """
    assert extract_tables_from_sql(
        """
SELECT *
FROM table_a AS a, (select * from table_b) AS b, table_c as c
WHERE a.id = b.id and b.id = c.id
"""
    ) == {Table("table_a"), Table("table_b"), Table("table_c")}


def test_extract_tables_nested_select() -> None:
    """
    Test that the parser handles selects inside functions.
    """
    assert extract_tables_from_sql(
        """
select (extractvalue(1,concat(0x7e,(select GROUP_CONCAT(TABLE_NAME)
from INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA like "%bi%"),0x7e)));
""",
        "mysql",
    ) == {Table("COLUMNS", "INFORMATION_SCHEMA")}

    assert extract_tables_from_sql(
        """
select (extractvalue(1,concat(0x7e,(select GROUP_CONCAT(COLUMN_NAME)
from INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME="bi_achievement_daily"),0x7e)));
""",
        "mysql",
    ) == {Table("COLUMNS", "INFORMATION_SCHEMA")}


def test_extract_tables_complex_cte_with_prefix() -> None:
    """
    Test that the parser handles CTEs with prefixes.
    """
    assert extract_tables_from_sql(
        """
WITH CTE__test (SalesPersonID, SalesOrderID, SalesYear)
AS (
    SELECT SalesPersonID, SalesOrderID, YEAR(OrderDate) AS SalesYear
    FROM SalesOrderHeader
    WHERE SalesPersonID IS NOT NULL
)
SELECT SalesPersonID, COUNT(SalesOrderID) AS TotalSales, SalesYear
FROM CTE__test
GROUP BY SalesYear, SalesPersonID
ORDER BY SalesPersonID, SalesYear;
"""
    ) == {Table("SalesOrderHeader")}


def test_extract_tables_qualified_reference_matching_cte_name() -> None:
    """
    Test that a schema/catalog-qualified reference is resolved as a physical
    table even when its final name component matches a CTE defined in scope.

    A CTE name is always a bare identifier, so ``public.orders`` cannot be the
    CTE ``orders`` and must be reported as the physical table it names.
    """
    # schema-qualified reference shadowed by a same-named bare CTE
    assert extract_tables_from_sql(
        "WITH orders AS (SELECT 1) SELECT * FROM public.orders"
    ) == {Table("orders", "public")}

    # the CTE itself still references its own physical source
    assert extract_tables_from_sql(
        "WITH orders AS (SELECT * FROM staging.orders) SELECT * FROM public.orders"
    ) == {Table("orders", "staging"), Table("orders", "public")}

    # catalog-qualified reference shadowed by a same-named bare CTE
    assert extract_tables_from_sql(
        "WITH orders AS (SELECT 1) SELECT * FROM cat.public.orders"
    ) == {Table("orders", "public", "cat")}


def test_extract_tables_bare_cte_still_excluded() -> None:
    """
    Test that a genuine bare CTE reference is still not reported as a table.
    """
    assert extract_tables_from_sql(
        "WITH foo AS (SELECT * FROM target_table) SELECT * FROM foo"
    ) == {Table("target_table")}


def test_extract_tables_unreferenced_cte_does_not_shadow_table() -> None:
    """
    Test that a CTE that is defined but not used by the outer query does not
    change extraction of a physical table sharing its name.
    """
    assert extract_tables_from_sql(
        "WITH orders AS (SELECT 1) SELECT * FROM orders_summary"
    ) == {Table("orders_summary")}


def test_extract_tables_identifier_list_with_keyword_as_alias() -> None:
    """
    Test that aliases that are keywords are parsed correctly.
    """
    assert extract_tables_from_sql(
        """
WITH
    f AS (SELECT * FROM foo),
    match AS (SELECT * FROM f)
SELECT * FROM match
"""
    ) == {Table("foo")}


def test_sqlscript() -> None:
    """
    Test the `SQLScript` class.
    """
    script = SQLScript("SELECT 1; SELECT 2;", "sqlite")

    assert len(script.statements) == 2
    assert script.format() == "SELECT\n  1;\nSELECT\n  2"
    assert script.statements[0].format() == "SELECT\n  1"

    script = SQLScript("SET a=1; SET a=2; SELECT 3;", "sqlite")
    assert script.get_settings() == {"a": "2"}

    query = SQLScript(
        """set querytrace;
Events | take 100""",
        "kustokql",
    )
    assert query.get_settings() == {"querytrace": True}


def test_sqlscript_format_preserves_optimizer_hint_block() -> None:
    """
    Regression for #38189: an inline `--` comment trailing a query with a
    `/*+ SET_VAR(...) */` optimizer hint must not get repositioned inside
    the hint block during `format()` -- that would corrupt the hint syntax
    (StarRocks and other engines using the `/*+ ... */` convention reject
    a nested `/* */` inside it). `format()` is what Superset's execution
    path actually sends to the engine (see `executor.py`/`celery_task.py`).
    """
    sql = """SELECT /*+ SET_VAR(query_timeout = 3000) */ col1, col2
FROM my_table
LIMIT 100

-- increase timeout for large scans"""
    statement = SQLScript(sql, "starrocks").statements[0]
    formatted = statement.format()

    hint = "/*+ SET_VAR(query_timeout = 3000) */"
    assert hint in formatted
    assert "SET_VAR(query_timeout /*" not in formatted
    # the trailing comment must survive, and land outside (after) the hint
    # block rather than being dropped or relocated into it
    hint_end = formatted.index(hint) + len(hint)
    assert "increase timeout for large scans" in formatted[hint_end:]


@pytest.mark.xfail(
    reason=(
        "#38189 is not fully fixed: a `;`-terminated statement still hits "
        "the comment-relocation branch and corrupts the hint block. Only "
        "the no-semicolon form from the original repro was fixed."
    ),
    strict=True,
)
def test_sqlscript_format_preserves_optimizer_hint_block_with_semicolon() -> None:
    """
    Same as `test_sqlscript_format_preserves_optimizer_hint_block`, but with
    a terminating `;` on the statement -- this still reproduces #38189: the
    trailing `--` comment gets injected inside the `/*+ SET_VAR(...) */`
    hint block, corrupting it for StarRocks/MySQL-style engines.
    """
    sql = """SELECT /*+ SET_VAR(query_timeout = 3000) */ col1, col2
FROM my_table
LIMIT 100;

-- increase timeout for large scans"""
    statement = SQLScript(sql, "starrocks").statements[0]
    formatted = statement.format()

    hint = "/*+ SET_VAR(query_timeout = 3000) */"
    assert hint in formatted
    assert "SET_VAR(query_timeout /*" not in formatted
    hint_end = formatted.index(hint) + len(hint)
    assert "increase timeout for large scans" in formatted[hint_end:]


@pytest.mark.parametrize(
    "sql, engine, expected",
    [
        (
            " SELECT foo FROM tbl ; ",
            "postgresql",
            ["SELECT\n  foo\nFROM tbl"],
        ),
        (
            "SELECT foo FROM tbl1; SELECT bar FROM tbl2;",
            "postgresql",
            ["SELECT\n  foo\nFROM tbl1", "SELECT\n  bar\nFROM tbl2"],
        ),
        (
            "let foo = 1; tbl | where bar == foo",
            "kustokql",
            ["let foo = 1", "tbl | where bar == foo"],
        ),
        (
            "SELECT 1; -- extraneous comment",
            "postgresql",
            ["SELECT\n  1 /* extraneous comment */"],
        ),
        (
            "SHOW TABLES FROM s1 like '%order%';",
            "mysql",
            ["SHOW TABLES FROM s1 LIKE '%order%'"],
        ),
        (
            "SELECT 1; SELECT 2; SELECT 3;",
            "unknown-engine",
            [
                "SELECT\n  1",
                "SELECT\n  2",
                "SELECT\n  3",
            ],
        ),
    ],
)
def test_sqlscript_split(sql: str, engine: str, expected: list[str]) -> None:
    """
    Test the `SQLScript` class with a script that has a single statement.
    """
    script = SQLScript(sql, engine)
    assert [statement.format() for statement in script.statements] == expected


def test_sqlstatement() -> None:
    """
    Test the `SQLStatement` class.
    """
    statement = SQLStatement(
        "SELECT * FROM table1 UNION ALL SELECT * FROM table2",
        "sqlite",
    )

    assert (
        statement.format()
        == "SELECT\n  *\nFROM table1\nUNION ALL\nSELECT\n  *\nFROM table2"
    )
    assert str(statement) == statement.format()

    assert statement.tables == {
        Table(table="table1", schema=None, catalog=None),
        Table(table="table2", schema=None, catalog=None),
    }

    assert statement.parse_predicate("a > 1") == exp.GT(
        this=exp.Column(this=exp.Identifier(this="a", quoted=False)),
        expression=exp.Literal(this="1", is_string=False),
    )

    statement = SQLStatement("SET a=1", "sqlite")
    assert statement.get_settings() == {"a": "1"}

    with pytest.raises(
        ValueError,
        match="Either statement or ast must be provided",
    ):
        SQLStatement()


def test_kustokqlstatement() -> None:
    """
    Test the `KustoKQLStatement` class.
    """
    statement = KustoKQLStatement("foo | take 100", "kustokql")

    assert statement.format() == "foo | take 100"
    assert str(statement) == statement.format()

    # doesn't support table extraction
    assert statement.tables == set()

    # optimize is a no-op
    assert statement.optimize().format() == "foo | take 100"

    # predicate parsing is also no-op
    assert statement.parse_predicate("a > 1") == "a > 1"

    with pytest.raises(SupersetParseError, match="Invalid engine: invalid-engine"):
        KustoKQLStatement("foo | take 100", "invalid-engine")

    with pytest.raises(
        SupersetParseError,
        match="KustoKQLStatement should have exactly one statement",
    ):
        KustoKQLStatement("foo | take 1; bar | take 2", "kustokql")


def test_kustokqlstatement_split_script() -> None:
    """
    Test the `KustoKQLStatement` split method.
    """
    statements = KustoKQLStatement.split_script(
        """
let totalPagesPerDay = PageViews
| summarize by Page, Day = startofday(Timestamp)
| summarize count() by Day;
let materializedScope = PageViews
| summarize by Page, Day = startofday(Timestamp);
let cachedResult = materialize(materializedScope);
cachedResult
| project Page, Day1 = Day
| join kind = inner
(
    cachedResult
    | project Page, Day2 = Day
)
on Page
| where Day2 > Day1
| summarize count() by Day1, Day2
| join kind = inner
    totalPagesPerDay
on $left.Day1 == $right.Day
| project Day1, Day2, Percentage = count_*100.0/count_1
        """,
        "kustokql",
    )
    assert len(statements) == 4


def test_kustokqlstatement_with_program() -> None:
    """
    Test the `KustoKQLStatement` split method when the KQL has a program.
    """
    statements = KustoKQLStatement.split_script(
        """
print program = ```
  public class Program {
    public static void Main() {
      System.Console.WriteLine("Hello!");
    }
  }```
        """,
        "kustokql",
    )
    assert len(statements) == 1


def test_kustokqlstatement_with_set() -> None:
    """
    Test the `KustoKQLStatement` split method when the KQL has a set command.
    """
    statements = KustoKQLStatement.split_script(
        """
set querytrace;
Events | take 100
        """,
        "kustokql",
    )
    assert len(statements) == 2
    assert statements[0].format() == "set querytrace"
    assert statements[1].format() == "Events | take 100"


@pytest.mark.parametrize(
    "kql,statements",
    [
        ('print banner=strcat("Hello", ", ", "World!")', 1),
        (r"print 'O\'Malley\'s'", 1),
        (r"print 'O\'Mal;ley\'s'", 1),
        ("print ```foo;\nbar;\nbaz;```\n", 1),
    ],
)
def test_kustokql_statement_split_special(kql: str, statements: int) -> None:
    assert len(KustoKQLStatement.split_script(kql, "kustokql")) == statements


@pytest.mark.parametrize(
    "kql, expected",
    [
        (";Table | take 5", ["Table | take 5"]),
        (";Table | take 5;", ["Table | take 5"]),
        (
            """
let totalPagesPerDay = PageViews
| summarize by Page, Day = startofday(Timestamp)
| summarize count() by Day;
let materializedScope = PageViews
| summarize by Page, Day = startofday(Timestamp);
let cachedResult = materialize(materializedScope);
cachedResult
| project Page, Day1 = Day
| join kind = inner
(
    cachedResult
    | project Page, Day2 = Day
)
on Page
| where Day2 > Day1
| summarize count() by Day1, Day2
| join kind = inner
    totalPagesPerDay
on $left.Day1 == $right.Day
| project Day1, Day2, Percentage = count_*100.0/count_1
            """,
            [
                """
let totalPagesPerDay = PageViews
| summarize by Page, Day = startofday(Timestamp)
| summarize count() by Day""",
                """
let materializedScope = PageViews
| summarize by Page, Day = startofday(Timestamp)""",
                """
let cachedResult = materialize(materializedScope)""",
                """
cachedResult
| project Page, Day1 = Day
| join kind = inner
(
    cachedResult
    | project Page, Day2 = Day
)
on Page
| where Day2 > Day1
| summarize count() by Day1, Day2
| join kind = inner
    totalPagesPerDay
on $left.Day1 == $right.Day
| project Day1, Day2, Percentage = count_*100.0/count_1
            """,
            ],
        ),
    ],
)
def test_split_kql(kql: str, expected: list[str]) -> None:
    """
    Test the `split_kql` function.
    """
    assert split_kql(kql) == expected


@pytest.mark.parametrize(
    ("engine", "sql", "expected"),
    [
        ("sqlite", "SELECT 1", False),
        ("sqlite", "INSERT INTO foo VALUES (1)", True),
        ("sqlite", "UPDATE foo SET bar = 2 WHERE id = 1", True),
        ("sqlite", "DELETE FROM foo WHERE id = 1", True),
        ("sqlite", "CREATE TABLE foo (id INT, bar TEXT)", True),
        ("sqlite", "DROP TABLE foo", True),
        ("sqlite", "EXPLAIN SELECT * FROM foo", False),
        ("sqlite", "PRAGMA table_info(foo)", False),
        ("postgresql", "SELECT 1", False),
        ("postgresql", "INSERT INTO foo (id, bar) VALUES (1, 'test')", True),
        ("postgresql", "UPDATE foo SET bar = 'new' WHERE id = 1", True),
        ("postgresql", "DELETE FROM foo WHERE id = 1", True),
        ("postgresql", "CREATE TABLE foo (id SERIAL PRIMARY KEY, bar TEXT)", True),
        ("postgresql", "DROP TABLE foo", True),
        ("postgresql", "EXPLAIN ANALYZE SELECT * FROM foo", False),
        ("postgresql", "EXPLAIN ANALYZE DELETE FROM foo", True),
        # SHOW reads server configuration; it mutates nothing, so it is NOT
        # classified as mutating (that would be wrong for the commit/limit/
        # "only SELECT" consumers of has_mutation()). Gating disclosure reads
        # belongs in DISALLOWED_SQL_FUNCTIONS, not the mutation check.
        ("postgresql", "SHOW search_path", False),
        # SET search_path parses as exp.Set (a structured node), not
        # exp.Command, so the SET-in-mutating-commands rule does NOT
        # catch it. Pure GUC reads/writes stay non-mutating.
        ("postgresql", "SET search_path TO public", False),
        (
            "postgres",
            """
            with source as (
                select 1 as one
            )
            select * from source
            """,
            False,
        ),
        ("trino", "SELECT 1", False),
        ("trino", "INSERT INTO foo VALUES (1, 'bar')", True),
        ("trino", "UPDATE foo SET bar = 'baz' WHERE id = 1", True),
        ("trino", "DELETE FROM foo WHERE id = 1", True),
        ("trino", "CREATE TABLE foo (id INT, bar VARCHAR)", True),
        ("trino", "DROP TABLE foo", True),
        ("trino", "EXPLAIN SELECT * FROM foo", False),
        ("trino", "SHOW SCHEMAS", False),
        ("trino", "SET SESSION optimization_level = '3'", False),
        ("kustokql", "tbl | limit 100", False),
        ("kustokql", "let foo = 1; tbl | where bar == foo", False),
        ("kustokql", ".show tables", False),
        ("kustokql", "print 1", False),
        ("kustokql", "set querytrace; Events | take 100", False),
        ("kustokql", ".drop table foo", True),
        ("kustokql", ".set-or-append table foo <| bar", True),
        ("base", "SHOW LOCKS test EXTENDED", False),
        ("base", "SET hivevar:desc='Legislators'", False),
        ("base", "UPDATE t1 SET col1 = NULL", True),
        ("base", "EXPLAIN SELECT 1", False),
        ("base", "SELECT 1", False),
        ("base", "WITH bla AS (SELECT 1) SELECT * FROM bla", False),
        ("base", "SHOW CATALOGS", False),
        ("base", "SHOW TABLES", False),
        ("hive", "UPDATE t1 SET col1 = NULL", True),
        ("hive", "INSERT OVERWRITE TABLE tabB SELECT a.Age FROM TableA", True),
        ("hive", "SHOW LOCKS test EXTENDED", False),
        ("hive", "SET hivevar:desc='Legislators'", False),
        ("hive", "EXPLAIN SELECT 1", False),
        ("hive", "SELECT 1", False),
        ("hive", "WITH bla AS (SELECT 1) SELECT * FROM bla", False),
        ("presto", "SET hivevar:desc='Legislators'", False),
        ("presto", "UPDATE t1 SET col1 = NULL", True),
        ("presto", "INSERT OVERWRITE TABLE tabB SELECT a.Age FROM TableA", True),
        ("presto", "SHOW LOCKS test EXTENDED", False),
        ("presto", "EXPLAIN SELECT 1", False),
        ("presto", "SELECT 1", False),
        ("presto", "WITH bla AS (SELECT 1) SELECT * FROM bla", False),
    ],
)
def test_has_mutation(engine: str, sql: str, expected: bool) -> None:
    """
    Test the `has_mutation` method.
    """
    assert SQLScript(sql, engine).has_mutation() == expected


@pytest.mark.parametrize(
    "engine, sql, expected",
    [
        # Plain SELECT parses to a proper AST node.
        ("postgresql", "SELECT * FROM foo", False),
        # CALL parses to ``exp.Command`` on Postgres.
        ("postgresql", "CALL my_proc(1);", True),
        # A script that mixes a parseable statement with an unparseable one
        # is still flagged so strict scoping can refuse the whole script.
        ("postgresql", "SELECT 1; CALL my_proc();", True),
        # Non-sqlglot engines (e.g. Kusto KQL) do not produce a parseable
        # AST and cannot have their tables enumerated, so they must be
        # flagged as unparseable to fail closed under strict scoping.
        ("kustokql", "print 1", True),
    ],
)
def test_has_unparseable_statement(engine: str, sql: str, expected: bool) -> None:
    """
    Test the `has_unparseable_statement` property used by strict scoping to
    refuse statements that sqlglot couldn't fully model.
    """
    assert SQLScript(sql, engine).has_unparseable_statement is expected


@pytest.mark.parametrize(
    "sql",
    [
        "SELECT last(my_value_column, my_time_column) FROM my_table",
        "SELECT first(my_value_column, my_time_column) FROM my_table",
        "SELECT time_bucket('1 hour', my_time_column) AS bucket FROM my_table",
    ],
)
def test_postgres_parses_timescaledb_hyperfunctions(sql: str) -> None:
    """
    Regression for #32028: TimescaleDB extends Postgres with hyperfunctions
    (``last``, ``first``, ``time_bucket``, etc.) that take more arguments
    than vanilla Postgres equivalents. SQL Lab tolerates them (it routes
    raw SQL straight to the engine), but the dashboard chart path runs the
    SQL through ``SQLScript`` for inspection. A strict per-function arity
    check in sqlglot was rejecting these queries with ``The number of
    provided arguments (2) is greater than the maximum number of supported
    arguments (1)``, which broke dashboards built on TimescaleDB datasets.

    These tests pin that the parse path tolerates Postgres-dialect SQL
    using TimescaleDB hyperfunction signatures. If a future sqlglot
    upgrade reintroduces the strict arity check, this fails immediately.
    """
    SQLScript(sql, "postgresql")  # Must not raise.


@pytest.mark.parametrize(
    "engine",
    ["oracle", "postgresql", "trino", "presto", "hive", "base"],
)
def test_with_clause_containing_union_is_not_mutating(engine: str) -> None:
    """
    Regression for #25659: a SELECT with a WITH clause whose CTEs contain
    UNION (or UNION ALL) must not be classified as mutating, on any dialect.

    The original bug surfaced on Oracle, where saving a virtual dataset built
    from such a query failed with "Only `SELECT` statements are allowed". The
    parser was misclassifying the WITH+UNION construct as DML.

    Multiple dialects are exercised because the bug arose from sqlglot's
    per-dialect AST shape — Oracle's representation of the same query may
    differ from Postgres/Trino, and a fix that only touches one dialect
    leaves the others exposed to the same regression.
    """
    sql = """
    WITH set1 AS (SELECT 1 AS n UNION SELECT 2),
         set2 AS (SELECT * FROM set1)
    SELECT * FROM set2
    """
    assert not SQLScript(sql, engine).has_mutation(), (
        f"WITH+UNION misclassified as mutating on {engine!r}; "
        "this would block the query from being saved as a virtual dataset."
    )


def test_with_clause_containing_union_all_is_not_mutating_oracle() -> None:
    """
    Companion to test_with_clause_containing_union_is_not_mutating: the
    original bug report (#25659) used the exact Oracle-flavored shape below
    (``SYSDATE FROM DUAL`` is the Oracle no-op for "now"). Pinning the
    verbatim repro guards against a future dialect-specific regression that
    a generic ``SELECT 1`` test might miss.
    """
    sql = """
    WITH SET1 AS (SELECT SYSDATE FROM DUAL UNION ALL SELECT SYSDATE FROM DUAL),
         SET2 AS (SELECT * FROM SET1)
    SELECT * FROM SET2
    """
    assert not SQLScript(sql, "oracle").has_mutation()


@pytest.mark.parametrize("engine", ["clickhouse", "clickhousedb"])
def test_clickhouse_parametric_aggregate_parses_and_is_read_only(engine: str) -> None:
    """
    Regression for #37285: ClickHouse parametric aggregate functions use a
    double pair of parentheses — ``groupConcat(', ')(part_name)`` — where the
    first list holds the aggregate's parameters and the second its arguments.

    Older sqlglot versions choked on the second parenthesized list, so SQL
    Lab either mangled the query sent to the database or, with DDL/DML
    disallowed, refused to run it because it "could not be parsed to confirm
    it is a read-only query". The sqlglot bump to >=30 fixed the parsing;
    pinning the reporter's verbatim query guards against a future
    dialect-specific regression. Both ClickHouse engine specs are exercised
    since each resolves the sqlglot dialect independently.
    """
    sql = """
    select
      groupConcat(', ')(part_name) as concatenated
    from system.parts
    """
    script = SQLScript(sql, engine)  # Must not raise.
    assert not script.has_mutation(), (
        f"Parametric aggregate misclassified as mutating on {engine!r}; "
        "this would block the query on connections without DDL/DML allowed."
    )


def test_get_settings() -> None:
    """
    Test `get_settings` in some edge cases.
    """
    sql = """
set
-- this is a tricky comment
search_path -- another one
= bar;
SELECT * FROM some_table;
    """
    assert SQLScript(sql, "postgresql").get_settings() == {"search_path": "bar"}


@pytest.mark.parametrize(
    "app",
    [{"SQLGLOT_DIALECTS_EXTENSIONS": {"custom": Dialects.MYSQL}}],
    indirect=True,
)
def test_custom_dialect(app: None) -> None:
    """
    Test that custom dialects are loaded correctly.
    """
    assert SQLGLOT_DIALECTS.get("custom") == Dialects.MYSQL


@pytest.mark.parametrize(
    "engine",
    [
        "ascend",
        "awsathena",
        "base",
        "bigquery",
        "clickhouse",
        "clickhousedb",
        "cockroachdb",
        "couchbase",
        "crate",
        "databend",
        "databricks",
        "db2",
        "denodo",
        "dremio",
        "drill",
        "druid",
        "duckdb",
        "dynamodb",
        "elasticsearch",
        "exa",
        "firebird",
        "firebolt",
        "gsheets",
        "hana",
        "hive",
        "ibmi",
        "impala",
        "kustokql",
        "kustosql",
        "kylin",
        "mariadb",
        "motherduck",
        "mssql",
        "mysql",
        "netezza",
        "oceanbase",
        "ocient",
        "odelasticsearch",
        "oracle",
        "pinot",
        "postgresql",
        "presto",
        "pydoris",
        "redshift",
        "risingwave",
        "shillelagh",
        "snowflake",
        "solr",
        "sqlite",
        "starrocks",
        "superset",
        "teradatasql",
        "trino",
        "vertica",
    ],
)
@pytest.mark.parametrize(
    "sql, expected",
    [
        ("SELECT 1", False),
        ("with source as ( select 1 as one ) select * from source", False),
        ("ALTER TABLE foo ADD COLUMN bar INT", True),
        # COMMENT ON parses as a typed exp.Comment node across dialects; it
        # writes to the catalog (pg_description on Postgres) so it is gated.
        ("COMMENT ON TABLE t IS 'note'", True),
    ],
)
def test_is_mutating(sql: str, engine: str, expected: bool) -> None:
    """
    Global tests for `is_mutating`, covering all supported engines.
    """
    assert SQLStatement(sql, engine).is_mutating() == expected


@pytest.mark.parametrize(
    "sql, engine",
    [
        # Opaque `exp.Command` fallbacks must fail closed on every dialect,
        # not only PostgreSQL.
        ("CALL evil_proc()", "mysql"),
        ("LOAD '/tmp/x.so'", "postgres"),
        ("EXEC dbo.evil_proc", "mssql"),
        # The EXPLAIN ANALYZE unwrap must handle the parenthesized
        # option-list, whitespace, alternate-spelling, and leading-comment
        # forms: PostgreSQL executes the inner DML for all of them.
        ("EXPLAIN (ANALYZE) UPDATE t SET x = 1", "postgresql"),
        ("EXPLAIN (ANALYZE, BUFFERS) DELETE FROM t", "postgresql"),
        ("EXPLAIN ANALYZE\nUPDATE t SET x = 1", "postgresql"),
        ("EXPLAIN ANALYSE UPDATE t SET x = 1", "postgresql"),
        ("EXPLAIN /* c */ (ANALYZE) UPDATE t SET x = 1", "postgresql"),
        # A bare COMMIT persists every prior write on the connection even
        # when the execution layer skips its own commit call.
        ("COMMIT", "postgresql"),
        ("COMMIT", "mysql"),
        # Further EXPLAIN ANALYZE edge forms: a leading line comment before
        # the option, a VERBOSE qualifier, an empty option list, and an
        # inner statement that cannot be parsed all fail closed as mutating.
        ("EXPLAIN --c\nANALYZE UPDATE t SET x = 1", "postgresql"),
        ("EXPLAIN ANALYZE VERBOSE UPDATE t SET x = 1", "postgresql"),
        ("EXPLAIN (ANALYZE)", "postgresql"),
        ("EXPLAIN ANALYZE )))", "postgresql"),
    ],
)
def test_is_mutating_fails_closed_on_gate_blind_spots(sql: str, engine: str) -> None:
    """
    `is_mutating` must fail closed on statements that slip past node-type
    matching: non-PostgreSQL command fallbacks, normalized `EXPLAIN ANALYZE`
    variants, and structured `COMMIT`.
    """
    assert SQLStatement(sql, engine).is_mutating()


@pytest.mark.parametrize(
    "sql, expected",
    [
        (
            """
DO $$
BEGIN
  INSERT INTO public.users (name, real_name)
    VALUES ('SQLLab bypass DML', 'SQLLab bypass DML');
END;
$$;
            """,
            True,
        ),
        (
            """
DO $$
BEGIN
    IF (SELECT COUNT(*) FROM orders WHERE status = 'pending') > 100 THEN
        RAISE NOTICE 'High pending order volume detected';
    END IF;
END;
$$;
            """,
            True,
        ),
    ],
)
def test_is_mutating_anonymous_block(sql: str, expected: bool) -> None:
    """
    Test for `is_mutating` with a Postgres anonymous block.

    Since we can't parse the PL/pgSQL inside the block we always assume it is mutating.
    """
    assert SQLStatement(sql, "postgresql").is_mutating() == expected


@pytest.mark.parametrize(
    "sql, expected",
    [
        # PostgreSQL large-object writers: each mutates server state. The bare
        # SELECT wrapper is irrelevant because the function call itself is the
        # side effect.
        ("SELECT lo_from_bytea(0, decode('deadbeef', 'hex'))", True),
        ("SELECT lo_export(12345, '/tmp/payload.bin')", True),
        ("SELECT lo_import('/etc/passwd')", True),
        ("SELECT lo_put(12345, 0, decode('00', 'hex'))", True),
        ("SELECT lo_create(0)", True),
        # lo_creat is the legacy large-object creator (distinct from lo_create).
        ("SELECT lo_creat(-1)", True),
        ("SELECT lowrite(12345, decode('00', 'hex'))", True),
        # lo_truncate/lo_truncate64 shrink an existing large object: a write.
        ("SELECT lo_truncate(12345, 0)", True),
        ("SELECT lo_truncate64(12345, 0)", True),
        # lo_unlink deletes a large object outright.
        ("SELECT lo_unlink(12345)", True),
        # PostgreSQL sequence mutators. setval()/nextval() look like reads but
        # advance sequence state for every subsequent caller.
        ("SELECT setval('public.my_seq', 1000)", True),
        ("SELECT SETVAL('public.my_seq', 1)", True),
        ("SELECT nextval('public.my_seq')", True),
        # currval() only reads the session's last value, so it is not mutating.
        ("SELECT currval('public.my_seq')", False),
        # Read-side large-object functions are intentionally NOT classified
        # as mutating here. They are still blocked via the function denylist
        # (see DISALLOWED_SQL_FUNCTIONS) but they do not write state.
        ("SELECT lo_get(12345)", False),
        ("SELECT loread(12345, 1024)", False),
        # Case-insensitive matching: the AST stores the raw casing for
        # anonymous functions, the check uppercases both sides.
        ("SELECT LO_EXPORT(12345, '/tmp/x')", True),
        # `SELECT INTO new_table FROM existing` creates a new relation; treat
        # as mutating even though sqlglot parses it as exp.Select.
        ("SELECT * INTO new_table FROM existing_table", True),
        ("SELECT col INTO TEMP new_table FROM existing_table", True),
        # A built-in function whose first string argument happens to match a
        # mutating name must NOT be flagged. sqlglot parses these into dedicated
        # nodes (e.g. exp.Upper) whose `.name` is the argument text, not the
        # function name, so the walk is restricted to exp.Anonymous to avoid a
        # false positive on this read-only query.
        ("SELECT upper('lo_export')", False),
        ("SELECT length('setval')", False),
        # Plain SELECT must remain non-mutating.
        ("SELECT 1", False),
        ("SELECT * FROM users WHERE id = 1", False),
    ],
)
def test_is_mutating_postgres_function_and_select_into(
    sql: str, expected: bool
) -> None:
    """
    `is_mutating` must catch mutating function calls (PostgreSQL large-object
    writers) and `SELECT ... INTO new_table` even though the wrapping AST
    node is a plain `exp.Select`.
    """
    assert SQLStatement(sql, "postgresql").is_mutating() == expected


@pytest.mark.parametrize(
    "engine, sql",
    [
        # `SELECT ... INTO new_table` is CTAS only in Postgres/Redshift/T-SQL.
        # In Oracle PL/SQL and MySQL the same syntax assigns into a variable
        # and is a read, so it must NOT be classified as mutating.
        ("oracle", "SELECT col INTO v FROM existing_table"),
        ("mysql", "SELECT col INTO @v FROM existing_table"),
    ],
)
def test_is_mutating_select_into_variable_is_read(engine: str, sql: str) -> None:
    """
    `SELECT ... INTO target` is only CTAS (mutating) for dialects where the
    syntax creates a table. On Oracle/MySQL it assigns into a variable and is
    a read, so `is_mutating` must return False there.
    """
    assert SQLStatement(sql, engine).is_mutating() is False


@pytest.mark.parametrize(
    "engine, sql",
    [
        # `SELECT ... INTO new_table` is CTAS on Redshift and T-SQL just as it
        # is on Postgres, so each dialect in _SELECT_INTO_CTAS_DIALECTS must
        # classify the statement as mutating.
        ("redshift", "SELECT * INTO new_table FROM existing_table"),
        ("redshift", "SELECT col INTO new_table FROM existing_table"),
        ("mssql", "SELECT * INTO new_table FROM existing_table"),
        ("mssql", "SELECT col INTO new_table FROM existing_table"),
    ],
)
def test_is_mutating_select_into_ctas_dialects(engine: str, sql: str) -> None:
    """
    `SELECT ... INTO new_table` creates a table on the CTAS dialects beyond
    Postgres (Redshift, T-SQL), so `is_mutating` must return True there.
    """
    assert SQLStatement(sql, engine).is_mutating() is True


@pytest.mark.parametrize(
    "engine, sql",
    [
        # The mutating-function names are PostgreSQL built-ins. On other engines
        # a same-named read-only function or UDF must NOT be flagged as
        # mutating, otherwise read-only queries get wrongly blocked.
        ("mysql", "SELECT setval(my_col)"),
        ("mysql", "SELECT lo_export(id, path) FROM t"),
        ("base", "SELECT setval(my_col)"),
        ("trino", "SELECT lowrite(x)"),
    ],
)
def test_is_mutating_function_names_scoped_to_postgres(engine: str, sql: str) -> None:
    """
    `_MUTATING_FUNCTION_NAMES` is PostgreSQL-specific, so the function-name walk
    only runs for the Postgres dialect; same-named functions on other engines
    must stay non-mutating.
    """
    assert SQLStatement(sql, engine).is_mutating() is False


@pytest.mark.parametrize(
    "sql, expected",
    [
        # PostgreSQL constructs that sqlglot parses as opaque exp.Command.
        # Each can wrap a DML body or change effective server state.
        ("PREPARE u AS UPDATE t SET x = 1", True),
        ("PREPARE i AS INSERT INTO t VALUES (1)", True),
        ("EXECUTE my_plan", True),
        ("CALL my_writing_procedure()", True),
        ("COPY t FROM '/tmp/data.csv'", True),
        ("GRANT SELECT ON t TO public", True),
        ("REVOKE SELECT ON t FROM public", True),
        ("SET ROLE other_role", True),
        ("REFRESH MATERIALIZED VIEW mv", True),
        ("REINDEX TABLE t", True),
        ("VACUUM t", True),
        # SHOW commands are reads (they mutate nothing), so they are NOT
        # classified as mutating. Gating information-disclosure reads such as
        # SHOW server_version belongs in DISALLOWED_SQL_FUNCTIONS (which already
        # blocks pg_read_file, version(), etc.), not in the mutation check.
        ("SHOW search_path", False),
        ("SHOW all", False),
        ("SHOW server_version", False),
        # RESET reverts a prior SET (e.g. RESET ROLE backs out SET ROLE).
        ("RESET ROLE", True),
        # DDL head-tokens that sqlglot falls back to exp.Command for when the
        # body uses syntax it does not model. One representative per
        # head-token branch (CREATE/ALTER/DROP); they all hit the same
        # set-lookup so additional CREATE PUBLICATION/SUBSCRIPTION/etc.
        # cases would not add coverage.
        (
            "CREATE FUNCTION x() RETURNS int AS '/tmp/x.so', 'i' LANGUAGE C",
            True,
        ),
        ("CREATE EXTENSION pg_trgm", True),  # non-FUNCTION DDL via Command
        ("ALTER SYSTEM SET wal_level = 'logical'", True),
        ("DROP EXTENSION pg_trgm", True),
        # LOAD dlopens a shared library on the PG host. Same RCE primitive
        # as `CREATE FUNCTION ... LANGUAGE C` if the library path is
        # attacker-controlled (e.g. via a prior COPY-to-program foothold).
        ("LOAD '/tmp/x.so'", True),
        # Case-insensitive: sqlglot preserves source case on Command.name,
        # so the set lookup must normalise. Regression for the original
        # bug where a lowercase head-token bypassed the gate.
        ("create extension pg_trgm", True),
        ("load '/tmp/x.so'", True),
        # Pre-existing positive controls
        ("DO $$ BEGIN UPDATE t SET x = 1; END $$", True),
        ("EXPLAIN ANALYZE UPDATE t SET x = 1", True),
    ],
)
def test_is_mutating_postgres_command_constructs(sql: str, expected: bool) -> None:
    """
    Several PostgreSQL constructs are represented by sqlglot as opaque
    `exp.Command` nodes (no structured AST). `is_mutating` recognises them
    by command name so they cannot slip past the read-only gate.
    """
    assert SQLStatement(sql, "postgresql").is_mutating() == expected


@pytest.mark.parametrize(
    "sql, engine, functions, expected",
    [
        # MySQL `@@<name>` syntax parses as exp.SessionParameter, which is
        # not a subclass of exp.Func. The walker must include it so the
        # denylist entry for `version` still catches `SELECT @@version`.
        ("SELECT @@version", "mysql", {"version"}, True),
        ("SELECT @@global.version", "mysql", {"version"}, True),
        ("SELECT @@hostname", "mysql", {"hostname"}, True),
        ("SELECT @@datadir", "mysql", {"datadir"}, True),
        # Negative control: a session parameter not in the denylist must
        # not match.
        ("SELECT @@autocommit", "mysql", {"version", "hostname"}, False),
        # A plain SELECT does not introduce session-parameter names.
        ("SELECT 1", "mysql", {"version"}, False),
        # The pre-existing exp.Func walk still works for normal calls.
        ("SELECT version()", "mysql", {"version"}, True),
        # PostgreSQL large-object functions are exp.Anonymous calls. The
        # walk includes them; the denylist entry catches them.
        ("SELECT lo_export(12345, '/tmp/x')", "postgresql", {"lo_export"}, True),
        (
            "SELECT lo_from_bytea(0, decode('00','hex'))",
            "postgresql",
            {"lo_from_bytea"},
            True,
        ),
        ("SELECT loread(12345, 1024)", "postgresql", {"loread"}, True),
    ],
)
def test_check_functions_present_session_parameter(
    sql: str, engine: str, functions: set[str], expected: bool
) -> None:
    """
    `check_functions_present` must visit `exp.SessionParameter` so that
    denylist entries for names like `version` or `hostname` also match
    `SELECT @@version` / `SELECT @@hostname` in MySQL.
    """
    assert SQLScript(sql, engine).check_functions_present(functions) == expected


@pytest.mark.parametrize(
    "sql, expected",
    [
        ("SELECT 1", False),
        ("INSERT INTO t VALUES (1)", False),
        ("UPDATE t SET x = 1", False),
        ("DELETE FROM t", False),
        ("MERGE INTO t USING s ON t.id = s.id WHEN MATCHED THEN DELETE", False),
        ("CREATE TABLE t (id INT)", False),
        ("DROP TABLE t", True),
        ("DROP TABLE IF EXISTS t", True),
        ("DROP VIEW v", True),
        ("TRUNCATE TABLE t", True),
        ("ALTER TABLE t ADD COLUMN x INT", True),
        ("ALTER TABLE t DROP COLUMN x", True),
    ],
)
def test_is_destructive(sql: str, expected: bool) -> None:
    """
    Test that ``is_destructive`` detects DROP, TRUNCATE, and ALTER
    but not SELECT, INSERT, UPDATE, DELETE, MERGE, or CREATE.
    """
    assert SQLStatement(sql, "postgresql").is_destructive() == expected


@pytest.mark.parametrize(
    "sql, expected",
    [
        ("SELECT 1; INSERT INTO t VALUES (1)", False),
        ("SELECT 1; DROP TABLE t", True),
        ("SELECT 1; TRUNCATE TABLE t", True),
        ("CREATE TABLE t (id INT); ALTER TABLE t ADD COLUMN x INT", True),
    ],
)
def test_has_destructive(sql: str, expected: bool) -> None:
    """
    Test that ``has_destructive`` on SQLScript detects destructive DDL
    across multiple statements.
    """
    assert SQLScript(sql, "postgresql").has_destructive() == expected


@pytest.mark.parametrize(
    "sql, expected",
    [
        ("SELECT 1 UNION SELECT 2", True),
        ("SELECT 1 UNION ALL SELECT 2", True),
        ("SELECT 1 INTERSECT SELECT 2", True),
        ("SELECT 1 EXCEPT SELECT 2", True),
        ("SELECT 1", False),
        ("WITH cte AS (SELECT 1) SELECT * FROM cte", False),
        ("SELECT * FROM (SELECT 1 UNION SELECT 2) AS sub", False),
    ],
)
def test_is_set_operation(sql: str, expected: bool) -> None:
    """
    Test that ``is_set_operation`` detects top-level UNION/INTERSECT/EXCEPT
    but not nested set operations inside a sub-query.
    """
    assert SQLStatement(sql, "postgresql").is_set_operation() == expected


@pytest.mark.parametrize(
    "kql, expected",
    [
        (".drop table T", True),
        (".alter table T (col:string)", True),
        (".show tables", False),
        ("T | count", False),
    ],
)
def test_kusto_is_destructive(kql: str, expected: bool) -> None:
    """
    Test ``is_destructive`` on KustoKQLStatement.
    """
    from superset.sql.parse import KustoKQLStatement

    assert KustoKQLStatement(kql, "kustokql").is_destructive() == expected


def test_optimize() -> None:
    """
    Test that the `optimize` method works as expected.

    The SQL optimization only works with engines that have a corresponding dialect.
    """
    sql = """
SELECT anon_1.a, anon_1.b
FROM (SELECT some_table.a AS a, some_table.b AS b, some_table.c AS c
FROM some_table) AS anon_1
WHERE anon_1.a > 1 AND anon_1.b = 2
    """

    optimized = """
SELECT
  anon_1.a,
  anon_1.b
FROM (
  SELECT
    some_table.a AS a,
    some_table.b AS b,
    some_table.c AS c
  FROM some_table
  WHERE
    some_table.a > 1 AND some_table.b = 2
) AS anon_1
WHERE
  TRUE AND TRUE
    """.strip()

    not_optimized = """
SELECT
  anon_1.a,
  anon_1.b
FROM (
  SELECT
    some_table.a AS a,
    some_table.b AS b,
    some_table.c AS c
  FROM some_table
) AS anon_1
WHERE
  anon_1.a > 1 AND anon_1.b = 2
    """.strip()

    assert SQLStatement(sql, "sqlite").optimize().format() == optimized
    assert SQLStatement(sql, "crate").optimize().format() == not_optimized

    # also works for scripts
    assert SQLScript(sql, "sqlite").optimize().format() == optimized


def test_firebolt() -> None:
    """
    Test that Firebolt 3rd party dialect is registered correctly.

    We need a custom dialect for Firebolt because it parses `NOT col IN (1, 2)` as
    `(NOT col) IN (1, 2)` instead of `NOT (col IN (1, 2))`, which will fail when `col`
    is not a boolean.

    Note that `NOT col = 1` works as expected in Firebolt, parsing as `NOT (col = 1)`.
    """
    sql = "SELECT col NOT IN (1, 2) FROM tbl"
    assert (
        SQLStatement(sql, "firebolt").format()
        == """
SELECT
  NOT (
    col IN (1, 2)
  )
FROM tbl
    """.strip()
    )

    sql = "SELECT NOT col = 1 FROM tbl"
    assert (
        SQLStatement(sql, "firebolt").format()
        == """
SELECT
  NOT col = 1
FROM tbl
    """.strip()
    )


def test_firebolt_old() -> None:
    """
    Test the dialect for the old Firebolt syntax.
    """
    from superset.sql.dialects import FireboltOld
    from superset.sql.parse import SQLGLOT_DIALECTS

    SQLGLOT_DIALECTS["firebolt"] = FireboltOld

    sql = "SELECT * FROM t1 UNNEST(col1 AS foo)"
    assert (
        SQLStatement(sql, "firebolt").format()
        == """
SELECT
  *
FROM t1 UNNEST(col1 AS foo)
        """.strip()
    )


def test_firebolt_old_escape_string() -> None:
    """
    Test the dialect for the old Firebolt syntax.
    """
    from superset.sql.dialects import FireboltOld
    from superset.sql.parse import SQLGLOT_DIALECTS

    SQLGLOT_DIALECTS["firebolt"] = FireboltOld

    # both '' and \' are valid escape sequences
    sql = r"SELECT 'foo''bar', 'foo\'bar'"

    # but they normalize to ''
    assert (
        SQLStatement(sql, "firebolt").format()
        == """
SELECT
  'foo''bar',
  'foo''bar'
        """.strip()
    )


@pytest.mark.parametrize(
    "sql, engine, expected",
    [
        ("SELECT * FROM users LIMIT 10", "postgresql", 10),
        (
            """
WITH cte_example AS (
  SELECT * FROM my_table
  LIMIT 100
)
SELECT * FROM cte_example
LIMIT 10;
        """,
            "postgresql",
            10,
        ),
        ("SELECT * FROM users ORDER BY id DESC LIMIT 25", "postgresql", 25),
        ("SELECT * FROM users", "postgresql", None),
        ("SELECT TOP 5 name FROM employees", "teradatasql", 5),
        ("SELECT TOP (42) * FROM table_name", "teradatasql", 42),
        ("select * from table", "postgresql", None),
        ("select * from mytable limit 10", "postgresql", 10),
        (
            "select * from (select * from my_subquery limit 10) where col=1 limit 20",
            "postgresql",
            20,
        ),
        ("select * from (select * from my_subquery limit 10);", "postgresql", None),
        (
            "select * from (select * from my_subquery limit 10) where col=1 limit 20;",
            "postgresql",
            20,
        ),
        ("select * from mytable limit 20, 10", "postgresql", 10),
        ("select * from mytable limit 10 offset 20", "postgresql", 10),
        (
            """
SELECT id, value, i
FROM (SELECT * FROM my_table LIMIT 10),
LATERAL generate_series(1, value) AS i;
        """,
            "postgresql",
            None,
        ),
        # not really valid SQL, but let's roll with it
        ("SELECT * FROM my_table LIMIT invalid", "postgresql", None),
    ],
)
def test_get_limit_value(sql: str, engine: str, expected: str) -> None:
    assert SQLStatement(sql, engine).get_limit_value() == expected


@pytest.mark.parametrize(
    "kql, expected",
    [
        ("StormEvents | take 10", 10),
        ("StormEvents | limit 20", 20),
        ("StormEvents | where State == 'FL' | summarize count()", None),
        ("StormEvents | where name has 'limit 10'", None),
        ("AnotherTable | take 5", 5),
        ("datatable(x:int) [1, 2, 3] | take 100", 100),
        (
            """
    Table1 | where msg contains 'abc;xyz'
           | limit 5
    """,
            5,
        ),
        ("table | take five", None),
    ],
)
def test_get_kql_limit_value(kql: str, expected: str) -> None:
    assert KustoKQLStatement(kql, "kustokql").get_limit_value() == expected


@pytest.mark.parametrize(
    "sql, engine, limit, method, expected",
    [
        (
            "SELECT * FROM t",
            "postgresql",
            10,
            LimitMethod.FORCE_LIMIT,
            "SELECT\n  *\nFROM t\nLIMIT 10",
        ),
        (
            "SELECT * FROM t LIMIT 1000",
            "postgresql",
            10,
            LimitMethod.FORCE_LIMIT,
            "SELECT\n  *\nFROM t\nLIMIT 10",
        ),
        (
            "SELECT * FROM t",
            "mssql",
            10,
            LimitMethod.FORCE_LIMIT,
            "SELECT\nTOP 10\n  *\nFROM t",
        ),
        (
            "SELECT * FROM t",
            "teradatasql",
            10,
            LimitMethod.FORCE_LIMIT,
            "SELECT\nTOP 10\n  *\nFROM t",
        ),
        (
            "SELECT * FROM t",
            "oracle",
            10,
            LimitMethod.FORCE_LIMIT,
            "SELECT\n  *\nFROM t\nFETCH FIRST 10 ROWS ONLY",
        ),
        (
            "SELECT * FROM t",
            "db2",
            10,
            LimitMethod.WRAP_SQL,
            "SELECT\n  *\nFROM (\n  SELECT\n    *\n  FROM t\n)\nLIMIT 10",
        ),
        (
            "SEL TOP 1000 * FROM My_table",
            "teradatasql",
            100,
            LimitMethod.FORCE_LIMIT,
            "SELECT\nTOP 100\n  *\nFROM My_table",
        ),
        (
            "SEL TOP 1000 * FROM My_table;",
            "teradatasql",
            100,
            LimitMethod.FORCE_LIMIT,
            "SELECT\nTOP 100\n  *\nFROM My_table",
        ),
        (
            "SEL TOP 1000 * FROM My_table;",
            "teradatasql",
            1000,
            LimitMethod.FORCE_LIMIT,
            "SELECT\nTOP 1000\n  *\nFROM My_table",
        ),
        (
            "SELECT TOP 1000 * FROM My_table;",
            "teradatasql",
            100,
            LimitMethod.FORCE_LIMIT,
            "SELECT\nTOP 100\n  *\nFROM My_table",
        ),
        (
            "SELECT TOP 1000 * FROM My_table;",
            "teradatasql",
            10000,
            LimitMethod.FORCE_LIMIT,
            "SELECT\nTOP 10000\n  *\nFROM My_table",
        ),
        (
            "SELECT TOP 1000 * FROM My_table",
            "mssql",
            100,
            LimitMethod.FORCE_LIMIT,
            "SELECT\nTOP 100\n  *\nFROM My_table",
        ),
        (
            "SELECT TOP 1000 * FROM My_table;",
            "mssql",
            100,
            LimitMethod.FORCE_LIMIT,
            "SELECT\nTOP 100\n  *\nFROM My_table",
        ),
        (
            "SELECT TOP 1000 * FROM My_table;",
            "mssql",
            10000,
            LimitMethod.FORCE_LIMIT,
            "SELECT\nTOP 10000\n  *\nFROM My_table",
        ),
        (
            "SELECT TOP 1000 * FROM My_table;",
            "mssql",
            1000,
            LimitMethod.FORCE_LIMIT,
            "SELECT\nTOP 1000\n  *\nFROM My_table",
        ),
        (
            """
with abc as (select * from test union select * from test1)
select TOP 100 * from currency
            """,
            "mssql",
            1000,
            LimitMethod.FORCE_LIMIT,
            """
WITH abc AS (
  SELECT
    *
  FROM test
  UNION
  SELECT
    *
  FROM test1
)
SELECT
TOP 1000
  *
FROM currency
            """.strip(),
        ),
        (
            "SELECT DISTINCT x from tbl",
            "mssql",
            100,
            LimitMethod.FORCE_LIMIT,
            "SELECT DISTINCT\nTOP 100\n  x\nFROM tbl",
        ),
        (
            "SELECT 1 as cnt",
            "mssql",
            10,
            LimitMethod.FORCE_LIMIT,
            "SELECT\nTOP 10\n  1 AS cnt",
        ),
        (
            "select TOP 1000 * from abc where id=1",
            "mssql",
            10,
            LimitMethod.FORCE_LIMIT,
            "SELECT\nTOP 10\n  *\nFROM abc\nWHERE\n  id = 1",
        ),
        (
            "SELECT * FROM birth_names -- SOME COMMENT",
            "postgresql",
            1000,
            LimitMethod.FORCE_LIMIT,
            "SELECT\n  *\nFROM birth_names /* SOME COMMENT */\nLIMIT 1000",
        ),
        (
            "SELECT * FROM birth_names -- SOME COMMENT WITH LIMIT 555",
            "postgresql",
            1000,
            LimitMethod.FORCE_LIMIT,
            """
SELECT
  *
FROM birth_names /* SOME COMMENT WITH LIMIT 555 */
LIMIT 1000
            """.strip(),
        ),
        (
            "SELECT * FROM birth_names LIMIT 555",
            "postgresql",
            1000,
            LimitMethod.FORCE_LIMIT,
            "SELECT\n  *\nFROM birth_names\nLIMIT 1000",
        ),
        (
            "SELECT * FROM birth_names LIMIT 555",
            "postgresql",
            1000,
            LimitMethod.FETCH_MANY,
            "SELECT\n  *\nFROM birth_names\nLIMIT 555",
        ),
    ],
)
def test_set_limit_value(
    sql: str,
    engine: str,
    limit: int,
    method: LimitMethod,
    expected: str,
) -> None:
    statement = SQLStatement(sql, engine)
    statement.set_limit_value(limit, method)
    assert statement.format() == expected


@pytest.mark.parametrize(
    "method",
    [LimitMethod.FORCE_LIMIT, LimitMethod.WRAP_SQL],
)
@pytest.mark.parametrize(
    "engine",
    [
        # Engines whose sqlglot dialect parses `SHOW` into a real `exp.Show`
        # node (as opposed to falling back to an opaque `exp.Command`, which
        # doesn't expose a `limit` arg and so was never affected by this bug).
        "starrocks",
        "mysql",
        "snowflake",
    ],
)
@pytest.mark.parametrize(
    "sql",
    [
        "SHOW TABLES",
        "SHOW DATABASES",
        "SHOW CREATE TABLE test.will_test1",
    ],
)
def test_set_limit_value_leaves_show_statements_unchanged(
    sql: str, engine: str, method: LimitMethod
) -> None:
    """
    Regression for #36939: no limit method may touch ``SHOW`` statements.

    ``SHOW`` statements have no `LIMIT` clause in sqlglot's expression tree,
    so forcing one via ``args["limit"]`` doesn't reject cleanly, it produces
    a malformed statement with two ``LIMIT`` keywords (one from a stray
    rendering of the bare ``Limit`` expression, one from the forced value).
    StarRocks (and presumably other engines) reject that outright: "Getting
    syntax error ... Unexpected input 'LIMIT'". The statement should be
    left untouched instead, matching how ``SELECT`` statements without a
    scannable row source aren't force-limited either.

    ``WRAP_SQL`` is wrong on a ``SHOW`` for the same reason but fails more
    quietly, rewriting it as ``SELECT * FROM (SHOW DATABASES)``, so both
    methods are covered here.

    Covers multiple engines, not just StarRocks: the fix guards on the AST
    node category (``exp.Query``), not the dialect, so any engine whose
    sqlglot dialect parses ``SHOW`` into a real ``Show`` node (e.g. MySQL,
    Snowflake) is equally exposed and must be equally protected.
    """
    statement = SQLStatement(sql, engine)
    original = statement.format()
    statement.set_limit_value(1000, method)
    assert statement.format() == original
    assert "LIMIT" not in statement.format()


@pytest.mark.parametrize(
    "method",
    [LimitMethod.FORCE_LIMIT, LimitMethod.WRAP_SQL],
)
@pytest.mark.parametrize(
    "sql",
    [
        "DESCRIBE test.will_test1",
        "USE test",
        "SET time_zone = 'UTC'",
        "GRANT SELECT ON t1 TO u1",
    ],
)
def test_set_limit_value_leaves_non_query_statements_unchanged(
    sql: str, method: LimitMethod
) -> None:
    """
    ``SHOW`` is not the only statement with nowhere to put a `LIMIT`.

    `apply_limit()` only skips *mutating* statements, so every read-only
    non-query statement reaches ``set_limit_value``. These happen to survive
    a forced limit today only because their sqlglot generators ignore an
    unexpected ``limit`` arg -- a silent dependency on generator internals.
    Guarding on ``exp.Query`` makes leaving them alone explicit, so a future
    sqlglot that starts rendering `limit` for one of these node types can't
    reintroduce the ``SHOW`` bug under a different keyword.
    """
    statement = SQLStatement(sql, "starrocks")
    original = statement.format()
    statement.set_limit_value(1000, method)
    assert statement.format() == original
    assert "LIMIT" not in statement.format()


@pytest.mark.parametrize(
    "sql",
    [
        # `UNION` parses as `exp.Union` and a parenthesized query as
        # `exp.Subquery` -- neither is an `exp.Select`, so narrowing the guard
        # to `is_select()` would silently stop limiting them.
        "SELECT 1 UNION SELECT 2",
        "(SELECT 1)",
        "WITH t AS (SELECT 1) SELECT * FROM t",
    ],
)
def test_set_limit_value_limits_non_select_query_expressions(sql: str) -> None:
    """
    Query expressions that aren't `SELECT` must still be limited.
    """
    statement = SQLStatement(sql, "starrocks")
    statement.set_limit_value(1000, LimitMethod.FORCE_LIMIT)
    assert "LIMIT 1000" in statement.format()


@pytest.mark.parametrize(
    "kql, limit, expected",
    [
        ("StormEvents | take 10", 100, "StormEvents | take 100"),
        ("StormEvents | limit 20", 10, "StormEvents | limit 10"),
        (
            "StormEvents | where State == 'FL' | summarize count()",
            10,
            "StormEvents | where State == 'FL' | summarize count() | take 10",
        ),
        (
            "StormEvents | where name has 'limit 10'",
            10,
            "StormEvents | where name has 'limit 10' | take 10",
        ),
        ("AnotherTable | take 5", 50, "AnotherTable | take 50"),
        (
            "datatable(x:int) [1, 2, 3] | take 100",
            10,
            "datatable(x:int) [1, 2, 3] | take 10",
        ),
        (
            """
    Table1 | where msg contains 'abc;xyz'
           | limit 5
    """,
            10,
            """Table1 | where msg contains 'abc;xyz'
           | limit 10""",
        ),
    ],
)
def test_set_kql_limit_value(kql: str, limit: int, expected: str) -> None:
    """
    Test the `set_limit_value` method for KustoKQLStatement.
    """
    statement = KustoKQLStatement(kql, "kustokql")
    statement.set_limit_value(limit)
    assert statement.format() == expected


@pytest.mark.parametrize("method", [LimitMethod.WRAP_SQL, LimitMethod.FETCH_MANY])
def test_set_kql_limit_value_invalid_method(method: LimitMethod) -> None:
    """
    Test that setting a limit value with an invalid method raises an error.
    """
    statement = KustoKQLStatement("foo", "kustokql")

    with pytest.raises(
        SupersetParseError,
        match="Kusto KQL only supports the FORCE_LIMIT method.",
    ):
        statement.set_limit_value(10, method)


@pytest.mark.parametrize(
    "sql, engine, expected",
    [
        ("SELECT 1", "postgresql", False),
        ("SELECT 1 AS cnt", "postgresql", False),
        (
            """
SELECT 'INR' AS cur
UNION
SELECT 'USD' AS cur
UNION
SELECT 'EUR' AS cur
            """,
            "postgresql",
            False,
        ),
        ("WITH cte AS (SELECT 1) SELECT * FROM cte", "postgresql", True),
        (
            """
WITH
    x AS (SELECT a FROM t1),
    y AS (SELECT a AS b FROM t2),
    z AS (SELECT b AS c FROM t3)
SELECT c FROM z
            """,
            "postgresql",
            True,
        ),
        (
            """
WITH
    x AS (SELECT a FROM t1),
    y AS (SELECT a AS b FROM x),
    z AS (SELECT b AS c FROM y)
SELECT c FROM z
            """,
            "postgresql",
            True,
        ),
        (
            """
WITH CTE__test (SalesPersonID, SalesOrderID, SalesYear)
AS (
    SELECT SalesPersonID, SalesOrderID, YEAR(OrderDate) AS SalesYear
    FROM SalesOrderHeader
    WHERE SalesPersonID IS NOT NULL
)
SELECT SalesPersonID, COUNT(SalesOrderID) AS TotalSales, SalesYear
FROM CTE__test
GROUP BY SalesYear, SalesPersonID
ORDER BY SalesPersonID, SalesYear;
            """,
            "postgresql",
            True,
        ),
    ],
)
def test_has_cte(sql: str, engine: str, expected: bool) -> None:
    """
    Test that the parser detects CTEs correctly.
    """
    assert SQLStatement(sql, engine).has_cte() == expected


@pytest.mark.parametrize(
    "sql, engine, expected",
    [
        (
            "SELECT 1",
            "postgresql",
            "WITH __cte AS (\n  SELECT\n    1\n)",
        ),
        (
            """
WITH currency AS (SELECT 'INR' AS cur),
     currency_2 AS (SELECT 'USD' AS cur)
SELECT * FROM currency
UNION ALL
SELECT * FROM currency_2
            """,
            "postgresql",
            """
WITH currency AS (
  SELECT
    'INR' AS cur
), currency_2 AS (
  SELECT
    'USD' AS cur
), __cte AS (
  SELECT
    *
  FROM currency
  UNION ALL
  SELECT
    *
  FROM currency_2
)
            """.strip(),
        ),
    ],
)
def test_as_cte(sql: str, engine: str, expected: str) -> None:
    """
    Test that we can covert select to CTE.
    """
    assert SQLStatement(sql, engine).as_cte().format() == expected


def test_as_cte_called_twice() -> None:
    """
    Test that calling as_cte() multiple times on the same instance works.

    Regression test for a bug where as_cte() sets self._parsed.args["with_"] = None
    after extracting CTEs, but has_cte() only checked if the key existed, not if
    the value was truthy. This caused an AttributeError on subsequent as_cte() calls.
    """
    sql = "WITH cte AS (SELECT 1) SELECT * FROM cte"
    stmt = SQLStatement(sql, "postgresql")

    assert stmt.has_cte() is True
    stmt.as_cte()
    assert stmt.has_cte() is False
    stmt.as_cte()


@pytest.mark.parametrize(
    ("sql", "removed"),
    [
        ("SELECT value FROM source ORDER BY value", True),
        ("SELECT TOP 1 value FROM source ORDER BY value", False),
        ("SELECT value FROM source ORDER BY value OFFSET 0 ROWS", False),
        ("SELECT value FROM source ORDER BY value FOR JSON AUTO", False),
    ],
)
def test_remove_unbounded_top_level_order_by(sql: str, removed: bool) -> None:
    statement = SQLStatement(sql, "mssql")

    assert statement.remove_unbounded_top_level_order_by() is removed
    assert ("ORDER BY" not in statement.format()) is removed


@pytest.mark.parametrize(
    "sql, rules, expected",
    [
        (
            "SELECT t.foo FROM some_table AS t",
            {Table("some_table", "schema1", "catalog1"): "id = 42"},
            """
SELECT
  t.foo
FROM (
  SELECT
    *
  FROM some_table
  WHERE
    id = 42
) AS t
            """.strip(),
        ),
        (
            "SELECT t.foo FROM some_table AS t",
            {},
            """
SELECT
  t.foo
FROM some_table AS t
            """.strip(),
        ),
        (
            "SELECT t.foo FROM some_table AS t WHERE bar = 'baz'",
            {Table("some_table", "schema1", "catalog1"): "id = 42"},
            """
SELECT
  t.foo
FROM (
  SELECT
    *
  FROM some_table
  WHERE
    id = 42
) AS t
WHERE
  bar = 'baz'
            """.strip(),
        ),
        (
            "SELECT t.foo FROM schema1.some_table AS t",
            {Table("some_table", "schema1", "catalog1"): "id = 42"},
            """
SELECT
  t.foo
FROM (
  SELECT
    *
  FROM schema1.some_table
  WHERE
    id = 42
) AS t
            """.strip(),
        ),
        (
            "SELECT t.foo FROM schema1.some_table AS t",
            {Table("some_table", "schema2"): "id = 42"},
            "SELECT\n  t.foo\nFROM schema1.some_table AS t",
        ),
        (
            "SELECT t.foo FROM catalog1.schema1.some_table AS t",
            {Table("some_table", "schema1", "catalog1"): "id = 42"},
            """
SELECT
  t.foo
FROM (
  SELECT
    *
  FROM catalog1.schema1.some_table
  WHERE
    id = 42
) AS t
            """.strip(),
        ),
        (
            "SELECT t.foo FROM catalog1.schema1.some_table AS t",
            {Table("some_table", "schema1", "catalog2"): "id = 42"},
            "SELECT\n  t.foo\nFROM catalog1.schema1.some_table AS t",
        ),
        (
            "SELECT * FROM some_table WHERE 1=1",
            {Table("some_table", "schema1", "catalog1"): "id = 42"},
            """
SELECT
  *
FROM (
  SELECT
    *
  FROM some_table
  WHERE
    id = 42
) AS "some_table"
WHERE
  1 = 1
            """.strip(),
        ),
        (
            "SELECT * FROM table WHERE 1=1",
            {Table("table", "schema1", "catalog1"): "id = 42"},
            """
SELECT
  *
FROM (
  SELECT
    *
  FROM table
  WHERE
    id = 42
) AS "table"
WHERE
  1 = 1
            """.strip(),
        ),
        (
            'SELECT * FROM "table" WHERE 1=1',
            {Table("table", "schema1", "catalog1"): "id = 42"},
            """
SELECT
  *
FROM (
  SELECT
    *
  FROM "table"
  WHERE
    id = 42
) AS "table"
WHERE
  1 = 1
            """.strip(),
        ),
        (
            "SELECT * FROM table WHERE 1=1",
            {Table("other_table", "schema1", "catalog1"): "id = 42"},
            """
SELECT
  *
FROM table
WHERE
  1 = 1
            """.strip(),
        ),
        (
            "SELECT * FROM other_table WHERE 1=1",
            {Table("table", "schema1", "catalog1"): "id = 42"},
            """
SELECT
  *
FROM other_table
WHERE
  1 = 1
            """.strip(),
        ),
        (
            "SELECT * FROM table JOIN other_table ON table.id = other_table.id",
            {Table("other_table", "schema1", "catalog1"): "id = 42"},
            """
SELECT
  *
FROM table
JOIN (
  SELECT
    *
  FROM other_table
  WHERE
    id = 42
) AS "other_table"
  ON table.id = other_table.id
            """.strip(),
        ),
        (
            'SELECT * FROM "table" JOIN other_table ON "table".id = other_table.id',
            {Table("table", "schema1", "catalog1"): "id = 42"},
            """
SELECT
  *
FROM (
  SELECT
    *
  FROM "table"
  WHERE
    id = 42
) AS "table"
JOIN other_table
  ON "table".id = other_table.id
            """.strip(),
        ),
        (
            "SELECT * FROM (SELECT * FROM some_table)",
            {Table("some_table", "schema1", "catalog1"): "id = 42"},
            """
SELECT
  *
FROM (
  SELECT
    *
  FROM (
    SELECT
      *
    FROM some_table
    WHERE
      id = 42
  ) AS "some_table"
)
            """.strip(),
        ),
        (
            "SELECT * FROM table UNION ALL SELECT * FROM other_table",
            {Table("table", "schema1", "catalog1"): "id = 42"},
            """
SELECT
  *
FROM (
  SELECT
    *
  FROM table
  WHERE
    id = 42
) AS "table"
UNION ALL
SELECT
  *
FROM other_table
            """.strip(),
        ),
        (
            "SELECT * FROM table UNION ALL SELECT * FROM other_table",
            {Table("other_table", "schema1", "catalog1"): "id = 42"},
            """
SELECT
  *
FROM table
UNION ALL
SELECT
  *
FROM (
  SELECT
    *
  FROM other_table
  WHERE
    id = 42
) AS "other_table"
            """.strip(),
        ),
        (
            "SELECT a.*, b.* FROM tbl_a AS a INNER JOIN tbl_b AS b ON a.col = b.col",
            {Table("tbl_a", "schema1", "catalog1"): "id = 42"},
            """
SELECT
  a.*,
  b.*
FROM (
  SELECT
    *
  FROM tbl_a
  WHERE
    id = 42
) AS a
INNER JOIN tbl_b AS b
  ON a.col = b.col
            """.strip(),
        ),
        (
            "SELECT a.*, b.* FROM tbl_a a INNER JOIN tbl_b b ON a.col = b.col",
            {Table("tbl_a", "schema1", "catalog1"): "id = 42"},
            """
SELECT
  a.*,
  b.*
FROM (
  SELECT
    *
  FROM tbl_a
  WHERE
    id = 42
) AS a
INNER JOIN tbl_b AS b
  ON a.col = b.col
            """.strip(),
        ),
        (
            "SELECT * FROM public.flights LIMIT 100",
            {Table("flights", "public", "catalog1"): "\"AIRLINE\" like 'A%'"},
            """
SELECT
  *
FROM (
  SELECT
    *
  FROM public.flights
  WHERE
    "AIRLINE" LIKE 'A%'
) AS "flights"
LIMIT 100
        """.strip(),
        ),
        (
            'SELECT * FROM tbl_a AS "x AND 1 = 0 OR 1 = 1"',
            {Table("tbl_a", "schema1", "catalog1"): "id = 42"},
            """
SELECT
  *
FROM (
  SELECT
    *
  FROM tbl_a
  WHERE
    id = 42
) AS "x AND 1 = 0 OR 1 = 1"
            """.strip(),
        ),
        (
            "SELECT c1 FROM tbl_a AS x (c1, c2)",
            {Table("tbl_a", "schema1", "catalog1"): "id = 42"},
            """
SELECT
  c1
FROM (
  SELECT
    *
  FROM tbl_a
  WHERE
    id = 42
) AS x(c1, c2)
            """.strip(),
        ),
        # A CTE sharing the rule's table name is not a read of it: only the real read
        # inside the CTE body is wrapped; the CTE reference keeps its own projection.
        (
            "WITH some_table AS (SELECT id FROM some_table) SELECT * FROM some_table",
            {Table("some_table", "schema1", "catalog1"): "id = 42"},
            """
WITH some_table AS (
  SELECT
    id
  FROM (
    SELECT
      *
    FROM some_table
    WHERE
      id = 42
  ) AS "some_table"
)
SELECT
  *
FROM some_table
            """.strip(),
        ),
        # A correlated ``LATERAL`` reaches the outer read through two scopes: wrapped
        # once, not twice. The lateral's own read is a distinct node, wrapped in place.
        (
            "SELECT * FROM some_table, LATERAL ("
            "SELECT * FROM other_table WHERE other_table.x = some_table.x) t",
            {
                Table("some_table", "schema1", "catalog1"): "id = 42",
                Table("other_table", "schema1", "catalog1"): "id = 7",
            },
            """
SELECT
  *
FROM (
  SELECT
    *
  FROM some_table
  WHERE
    id = 42
) AS "some_table", LATERAL (
  SELECT
    *
  FROM (
    SELECT
      *
    FROM other_table
    WHERE
      id = 7
  ) AS "other_table"
  WHERE
    other_table.x = some_table.x
) AS t
            """.strip(),
        ),
        # A read in a DML statement's subquery is filtered in place, not refused: the
        # ``UPDATE`` target is not a source, so only the ``SELECT`` read of ``t`` wraps.
        (
            "UPDATE dst SET x = 1 WHERE id IN (SELECT id FROM t)",
            {Table("t", "schema1", "catalog1"): "id = 42"},
            """
UPDATE dst SET x = 1
WHERE
  id IN (
    SELECT
      id
    FROM (
      SELECT
        *
      FROM t
      WHERE
        id = 42
    ) AS "t"
  )
            """.strip(),
        ),
    ],
)
def test_rls_subquery_transformer(
    sql: str,
    rules: dict[Table, str],
    expected: str,
) -> None:
    """
    Test `RLSAsSubqueryTransformer`.
    """
    statement = SQLStatement(sql)
    statement.apply_rls(
        "catalog1",
        "schema1",
        {k: [parse_one(v)] for k, v in rules.items()},
        RLSMethod.AS_SUBQUERY,
    )
    assert statement.format() == expected


@pytest.mark.parametrize(
    "sql, read_counts",
    [
        ("SELECT * FROM t", {"t": 1}),
        ("SELECT * FROM t JOIN u ON t.id = u.id", {"t": 1, "u": 1}),
        ("SELECT * FROM t, u", {"t": 1, "u": 1}),
        ("SELECT * FROM t WHERE id IN (SELECT id FROM u)", {"t": 1, "u": 1}),
        # A self-join reads the table through two distinct nodes; both are wrapped.
        ("SELECT * FROM t AS a JOIN t AS b ON a.id = b.id", {"t": 2}),
        # The CTE body's read of ``t`` and the outer read of ``t`` are both wrapped;
        # the CTE reference ``c`` is not a read and carries no rule.
        (
            "WITH c AS (SELECT id FROM t) SELECT * FROM c JOIN t AS t2 ON c.id = t2.id",
            {"t": 2},
        ),
        ("SELECT * FROM (SELECT * FROM t) AS x", {"t": 1}),
        # Pins the deepest-first ordering. The parenthesised join head ``t`` carries the
        # join to ``u`` in its own args, so ``u`` must be wrapped before ``t``; wrapping
        # ``t`` first would copy ``u`` into ``t``'s subquery and drop ``u``'s filter.
        # Flipping the sort to ``reverse=False`` makes this case fail.
        ("SELECT * FROM (t JOIN u ON t.id = u.id)", {"t": 1, "u": 1}),
        # A correlated ``LATERAL`` reaches the outer read through two scopes; it is
        # wrapped once, and the lateral's own read is wrapped once.
        (
            "SELECT * FROM some_table, LATERAL ("
            "SELECT * FROM other_table WHERE other_table.x = some_table.x) t",
            {"some_table": 1, "other_table": 1},
        ),
    ],
)
def test_rls_subquery_filters_every_authorized_read(
    sql: str,
    read_counts: dict[str, int],
) -> None:
    """The set the rewrite filters equals the set authorization enforces.

    Each read gets a table-specific sentinel predicate; its count in the output must
    equal that table's real-read node count, catching a dropped read or a double-wrap.
    """
    authorized = {t.table for t in extract_tables_from_statement(parse_one(sql), None)}
    assert authorized == set(read_counts)

    statement = SQLStatement(sql)
    statement.apply_rls(
        "catalog1",
        "schema1",
        {
            Table(table, "schema1", "catalog1"): [parse_one(f"rls_{table} = 1")]
            for table in read_counts
        },
        RLSMethod.AS_SUBQUERY,
    )
    output = statement.format()
    for table, count in read_counts.items():
        assert output.count(f"rls_{table} = 1") == count


def test_rls_invalid_method(mocker: MockerFixture) -> None:
    """
    Test that an invalid RLS method raises an error.
    """
    statement = SQLStatement("SELECT 1", "postgresql")
    predicates = mocker.MagicMock()

    with pytest.raises(ValueError, match="Invalid RLS method: invalid"):
        statement.apply_rls("catalog1", "schema1", predicates, "invalid")  # type: ignore


@pytest.mark.parametrize(
    "sql, rules, expected",
    [
        (
            "SELECT t.foo FROM some_table AS t",
            {Table("some_table", "schema1", "catalog1"): "id = 42"},
            """
SELECT
  t.foo
FROM some_table AS t
WHERE
  t.id = 42
            """.strip(),
        ),
        (
            "SELECT t.foo FROM schema2.some_table AS t",
            {Table("some_table", "schema1", "catalog1"): "id = 42"},
            """
SELECT
  t.foo
FROM schema2.some_table AS t
            """.strip(),
        ),
        (
            "SELECT t.foo FROM catalog2.schema1.some_table AS t",
            {Table("some_table", "schema1", "catalog1"): "id = 42"},
            """
SELECT
  t.foo
FROM catalog2.schema1.some_table AS t
            """.strip(),
        ),
        (
            "SELECT t.foo FROM some_table AS t WHERE bar = 'baz'",
            {Table("some_table", "schema1", "catalog1"): "id = 42"},
            """
SELECT
  t.foo
FROM some_table AS t
WHERE
  t.id = 42 AND (
    bar = 'baz'
  )
            """.strip(),
        ),
        (
            "SELECT t.foo FROM some_table AS t WHERE bar = 'baz' OR foo = 'qux'",
            {Table("some_table", "schema1", "catalog1"): "id = 42"},
            """
SELECT
  t.foo
FROM some_table AS t
WHERE
  t.id = 42 AND (
    bar = 'baz' OR foo = 'qux'
  )
            """.strip(),
        ),
        (
            "SELECT * FROM some_table WHERE 1=1",
            {Table("some_table", "schema1", "catalog1"): "id = 42"},
            """
SELECT
  *
FROM some_table
WHERE
  some_table.id = 42 AND (
    1 = 1
  )
            """.strip(),
        ),
        (
            "SELECT * FROM some_table WHERE TRUE OR FALSE",
            {Table("some_table", "schema1", "catalog1"): "id = 42"},
            """
SELECT
  *
FROM some_table
WHERE
  some_table.id = 42 AND (
    TRUE OR FALSE
  )
            """.strip(),
        ),
        (
            "SELECT * FROM table WHERE 1=1",
            {Table("table", "schema1", "catalog1"): "id = 42"},
            """
SELECT
  *
FROM table
WHERE
  table.id = 42 AND (
    1 = 1
  )
            """.strip(),
        ),
        (
            'SELECT * FROM "table" WHERE 1=1',
            {Table("table", "schema1", "catalog1"): "id = 42"},
            """
SELECT
  *
FROM "table"
WHERE
  "table".id = 42 AND (
    1 = 1
  )
            """.strip(),
        ),
        (
            "SELECT * FROM table WHERE 1=1",
            {Table("other_table", "schema1", "catalog1"): "id = 42"},
            """
SELECT
  *
FROM table
WHERE
  1 = 1
            """.strip(),
        ),
        (
            "SELECT * FROM other_table WHERE 1=1",
            {Table("table", "schema1", "catalog1"): "id = 42"},
            """
SELECT
  *
FROM other_table
WHERE
  1 = 1
            """.strip(),
        ),
        (
            "SELECT * FROM table",
            {Table("table", "schema1", "catalog1"): "id = 42"},
            """
SELECT
  *
FROM table
WHERE
  table.id = 42
            """.strip(),
        ),
        (
            "SELECT * FROM some_table",
            {Table("some_table", "schema1", "catalog1"): "id = 42"},
            """
SELECT
  *
FROM some_table
WHERE
  some_table.id = 42
            """.strip(),
        ),
        (
            "SELECT * FROM table ORDER BY id",
            {Table("table", "schema1", "catalog1"): "id = 42"},
            """
SELECT
  *
FROM table
WHERE
  table.id = 42
ORDER BY
  id
            """.strip(),
        ),
        (
            "SELECT * FROM table WHERE 1=1 AND table.id=42",
            {Table("table", "schema1", "catalog1"): "id = 42"},
            """
SELECT
  *
FROM table
WHERE
  table.id = 42 AND (
    1 = 1 AND table.id = 42
  )
            """.strip(),
        ),
        (
            """
SELECT * FROM table
JOIN other_table
ON table.id = other_table.id
AND other_table.id=42
            """,
            {Table("other_table", "schema1", "catalog1"): "id = 42"},
            """
SELECT
  *
FROM table
JOIN other_table
  ON other_table.id = 42 AND (
    table.id = other_table.id AND other_table.id = 42
  )
            """.strip(),
        ),
        (
            "SELECT * FROM table WHERE 1=1 AND id=42",
            {Table("table", "schema1", "catalog1"): "id = 42"},
            """
SELECT
  *
FROM table
WHERE
  table.id = 42 AND (
    1 = 1 AND id = 42
  )
            """.strip(),
        ),
        (
            "SELECT * FROM table JOIN other_table ON table.id = other_table.id",
            {Table("other_table", "schema1", "catalog1"): "id = 42"},
            """
SELECT
  *
FROM table
JOIN other_table
  ON other_table.id = 42 AND (
    table.id = other_table.id
  )
            """.strip(),
        ),
        (
            "SELECT * FROM table JOIN other_table",
            {Table("other_table", "schema1", "catalog1"): "id = 42"},
            """
SELECT
  *
FROM table
JOIN other_table
  ON other_table.id = 42
            """.strip(),
        ),
        (
            """
SELECT *
FROM table
JOIN other_table
ON table.id = other_table.id
WHERE 1=1
            """,
            {Table("other_table", "schema1", "catalog1"): "id = 42"},
            """
SELECT
  *
FROM table
JOIN other_table
  ON other_table.id = 42 AND (
    table.id = other_table.id
  )
WHERE
  1 = 1
            """.strip(),
        ),
        (
            "SELECT * FROM (SELECT * FROM other_table)",
            {Table("other_table", "schema1", "catalog1"): "id = 42"},
            """
SELECT
  *
FROM (
  SELECT
    *
  FROM other_table
  WHERE
    other_table.id = 42
)
            """.strip(),
        ),
        (
            "SELECT * FROM table UNION ALL SELECT * FROM other_table",
            {Table("table", "schema1", "catalog1"): "id = 42"},
            """
SELECT
  *
FROM table
WHERE
  table.id = 42
UNION ALL
SELECT
  *
FROM other_table
            """.strip(),
        ),
        (
            "SELECT * FROM table UNION ALL SELECT * FROM other_table",
            {Table("other_table", "schema1", "catalog1"): "id = 42"},
            """
SELECT
  *
FROM table
UNION ALL
SELECT
  *
FROM other_table
WHERE
  other_table.id = 42
            """.strip(),
        ),
        (
            "INSERT INTO some_table (col1, col2) VALUES (1, 2)",
            {Table("some_table", "schema1", "catalog1"): "id = 42"},
            """
INSERT INTO some_table (
  col1,
  col2
)
VALUES
  (1, 2)
            """.strip(),
        ),
        (
            'SELECT * FROM tbl_a AS "x AND 1 = 0 OR 1 = 1"',
            {Table("tbl_a", "schema1", "catalog1"): "id = 42"},
            """
SELECT
  *
FROM tbl_a AS "x AND 1 = 0 OR 1 = 1"
WHERE
  "x AND 1 = 0 OR 1 = 1".id = 42
            """.strip(),
        ),
        (
            'SELECT * FROM tbl_a AS "a.b"',
            {Table("tbl_a", "schema1", "catalog1"): "id = 42"},
            """
SELECT
  *
FROM tbl_a AS "a.b"
WHERE
  "a.b".id = 42
            """.strip(),
        ),
        # A column-list alias has no name (``this`` is ``None``); qualify with the table
        # so the predicate does not resolve outward into an enclosing scope.
        (
            "SELECT * FROM tbl_a AS (c1, c2)",
            {Table("tbl_a", "schema1", "catalog1"): "id = 42"},
            """
SELECT
  *
FROM tbl_a AS _t0(c1, c2)
WHERE
  tbl_a.id = 42
            """.strip(),
        ),
        # A table heading a parenthesised join is a read, but its parent is the wrapping
        # ``Subquery``, not a ``From``/``Join``, so the predicate method leaves it --
        # fail-closed (the subquery method filters it). Pinned to catch a shape change.
        (
            "SELECT * FROM (some_table JOIN other_table "
            "ON some_table.id = other_table.id)",
            {Table("some_table", "schema1", "catalog1"): "id = 42"},
            """
SELECT
  *
FROM (
  some_table
    JOIN other_table
      ON some_table.id = other_table.id
)
            """.strip(),
        ),
    ],
)
def test_rls_predicate_transformer(
    sql: str,
    rules: dict[Table, str],
    expected: str,
) -> None:
    """
    Test `RLSPredicateTransformer`.
    """
    statement = SQLStatement(sql)
    statement.apply_rls(
        "catalog1",
        "schema1",
        {k: [parse_one(v)] for k, v in rules.items()},
        RLSMethod.AS_PREDICATE,
    )
    assert statement.format() == expected


@pytest.mark.parametrize(
    "sql, table, expected",
    [
        (
            "SELECT * FROM some_table",
            Table("some_table"),
            """
CREATE TABLE "some_table" AS
SELECT
  *
FROM some_table
            """.strip(),
        ),
        (
            "SELECT * FROM some_table",
            Table("some_table", "schema1", "catalog1"),
            """
CREATE TABLE "catalog1"."schema1"."some_table" AS
SELECT
  *
FROM some_table
            """.strip(),
        ),
    ],
)
def test_as_create_table(sql: str, table: Table, expected: str) -> None:
    """
    Test the `as_create_table` method.
    """
    statement = SQLStatement(sql)
    create_table = statement.as_create_table(table, CTASMethod.TABLE)
    assert create_table.format() == expected


@pytest.mark.parametrize(
    "sql, engine, expected",
    [
        ("SELECT * FROM table", "postgresql", True),
        (
            """
-- comment
SELECT * FROM table
-- comment 2
            """,
            "mysql",
            True,
        ),
        (
            """
-- comment
SET @value = 42;
SELECT @value as foo;
-- comment 2
            """,
            "mysql",
            True,
        ),
        (
            """
-- comment
EXPLAIN SELECT * FROM table
-- comment 2
            """,
            "mysql",
            False,
        ),
        (
            """
SELECT * FROM table;
INSERT INTO TABLE (foo) VALUES (42);
            """,
            "mysql",
            False,
        ),
    ],
)
def test_is_valid_ctas(sql: str, engine: str, expected: bool) -> None:
    """
    Test the `is_valid_ctas` method.
    """
    assert SQLScript(sql, engine).is_valid_ctas() == expected


@pytest.mark.parametrize(
    "sql, engine, expected",
    [
        ("SELECT * FROM table", "postgresql", True),
        (
            """
-- comment
SELECT * FROM table
-- comment 2
            """,
            "mysql",
            True,
        ),
        (
            """
-- comment
SET @value = 42;
SELECT @value as foo;
-- comment 2
            """,
            "mysql",
            False,
        ),
        (
            """
-- comment
SELECT value as foo;
-- comment 2
            """,
            "mysql",
            True,
        ),
        (
            """
SELECT * FROM table;
INSERT INTO TABLE (foo) VALUES (42);
            """,
            "mysql",
            False,
        ),
    ],
)
def test_is_valid_cvas(sql: str, engine: str, expected: bool) -> None:
    """
    Test the `is_valid_cvas` method.
    """
    assert SQLScript(sql, engine).is_valid_cvas() == expected


@pytest.mark.parametrize(
    "sql, expected, engine",
    [
        ("col = 1", "col = 1", "base"),
        # Comment-free clauses are returned verbatim (no semantic round-trip).
        ("1=\t\n1", "1=\t\n1", "base"),
        ("(col = 1)", "(col = 1)", "base"),  # Compact format without newlines
        (
            "(col1 = 1) AND (col2 = 2)",
            "(col1 = 1) AND (col2 = 2)",
            "base",
        ),  # Compact format
        (
            "col = 'abc' -- comment",
            "col = 'abc' /* comment */",
            "base",
        ),  # Line comments converted to block comments
        (
            "TRUE /* precise_count_distinct=true */",
            "TRUE /* precise_count_distinct=true */",
            "base",
        ),  # Block comments preserved
        (
            "col > 1 /* hint=value */",
            "col > 1 /* hint=value */",
            "base",
        ),  # Block comments preserved
        ("col = 'col1 = 1) AND (col2 = 2'", "col = 'col1 = 1) AND (col2 = 2'", "base"),
        ("col = 'select 1; select 2'", "col = 'select 1; select 2'", "base"),
        # Trailing statement terminators are stripped so the clause stays valid
        # once embedded inside a larger fragment (e.g. ``WHERE (...)``).
        ("col = 1;", "col = 1", "base"),
        ("col = 1 ; ", "col = 1", "base"),
        ("col = 'abc -- comment'", "col = 'abc -- comment'", "base"),
        ("col1 = 1) AND (col2 = 2)", QueryClauseValidationException, "base"),
        ("(col1 = 1) AND (col2 = 2", QueryClauseValidationException, "base"),
        ("col1 = 1) AND (col2 = 2", QueryClauseValidationException, "base"),
        ("(col1 = 1)) AND ((col2 = 2)", QueryClauseValidationException, "base"),
        ("TRUE; SELECT 1", QueryClauseValidationException, "base"),
        # Regression test for https://github.com/apache/superset/issues/39223:
        # dialects with `MULTI_ARG_DISTINCT=False` (Postgres, Presto, Trino,
        # DuckDB) must not rewrite user-defined multi-argument DISTINCT
        # aggregates into row-expression null guards. Dremio is included
        # below as a defensive regression guard even though its generator
        # does not currently set `MULTI_ARG_DISTINCT=False`.
        (
            "DISTINCT_AVG(DISTINCT report_id, time_to_accept / 86400)",
            "DISTINCT_AVG(DISTINCT report_id, time_to_accept / 86400)",
            "postgresql",
        ),
        (
            "DISTINCT_SUM(DISTINCT report_id, total_bounty_reward_amount)",
            "DISTINCT_SUM(DISTINCT report_id, total_bounty_reward_amount)",
            "postgresql",
        ),
        (
            "DISTINCT_AVG(DISTINCT k, v)",
            "DISTINCT_AVG(DISTINCT k, v)",
            "presto",
        ),
        (
            "DISTINCT_AVG(DISTINCT k, v)",
            "DISTINCT_AVG(DISTINCT k, v)",
            "trino",
        ),
        (
            "DISTINCT_AVG(DISTINCT k, v)",
            "DISTINCT_AVG(DISTINCT k, v)",
            "duckdb",
        ),
        (
            "DISTINCT_AVG(DISTINCT k, v)",
            "DISTINCT_AVG(DISTINCT k, v)",
            "dremio",
        ),
        # Single-argument DISTINCT must still round-trip cleanly.
        (
            "COUNT(DISTINCT x)",
            "COUNT(DISTINCT x)",
            "postgresql",
        ),
    ],
)
def test_sanitize_clause(sql: str, expected: str | Exception, engine: str) -> None:
    """
    Test the `sanitize_clause` function.
    """
    if isinstance(expected, str):
        assert sanitize_clause(sql, engine) == expected
    else:
        with pytest.raises(expected):
            sanitize_clause(sql, engine)


@pytest.mark.parametrize(
    "engine",
    ["postgresql", "redshift", "cockroachdb", "netezza", "hana", "base", "mysql"],
)
def test_sanitize_clause_preserves_aggregation_semantics(engine: str) -> None:
    """
    Regression test for https://github.com/apache/superset/issues/36113.

    `sanitize_clause` must not silently rewrite a user-authored expression. The
    Postgres SQLGlot dialect (which several engines borrow) rewrites
    ``ROUND(AVG(x), n)`` to ``ROUND(CAST(AVG(x) AS DECIMAL), n)`` at generation
    time. On engines whose unqualified ``DECIMAL`` defaults to scale 0 (e.g.
    Redshift, Netezza) the injected cast rounds the aggregate to an integer
    *before* the explicit ``ROUND``, producing wrong results.

    The clause must be returned unchanged regardless of the engine dialect.
    """
    clause = "ROUND(AVG(col), 4)"
    sanitized = sanitize_clause(clause, engine)
    assert "CAST" not in sanitized.upper(), (
        f"sanitize_clause injected a cast for engine {engine!r}: {sanitized!r}"
    )
    assert sanitized == clause


@pytest.mark.parametrize(
    "engine",
    ["postgresql", "redshift", "cockroachdb", "netezza", "hana", "base", "mysql"],
)
def test_sanitize_clause_preserves_aggregation_semantics_with_comment(
    engine: str,
) -> None:
    """
    Regression test for https://github.com/apache/superset/issues/36113.

    A clause that contains a comment takes the re-rendering branch of
    ``sanitize_clause``. That branch must normalize comments using the *base*
    dialect rather than the engine dialect, so it must not re-apply the Postgres
    ``ROUND(AVG(x), n)`` -> ``ROUND(CAST(AVG(x) AS DECIMAL), n)`` rewrite that
    truncates results on engines where ``DECIMAL`` defaults to scale 0.
    """
    clause = "ROUND(AVG(col), 4) /* precise_count_distinct=true */"
    sanitized = sanitize_clause(clause, engine)
    assert "CAST" not in sanitized.upper(), (
        f"sanitize_clause injected a cast for engine {engine!r}: {sanitized!r}"
    )
    # The comment-handling branch must preserve the user-authored expression and
    # comment payload, not just avoid the cast (otherwise dropping the comment or
    # rewriting the clause entirely would still pass the assertion above).
    assert "ROUND(AVG(col), 4)" in sanitized, (
        f"sanitize_clause rewrote the clause for engine {engine!r}: {sanitized!r}"
    )
    assert "precise_count_distinct=true" in sanitized, (
        f"sanitize_clause dropped the comment for engine {engine!r}: {sanitized!r}"
    )


@pytest.mark.parametrize(
    "engine",
    [
        "postgresql",
        "presto",
        "trino",
        "duckdb",
        "dremio",
    ],
)
def test_sqlstatement_format_preserves_multi_arg_distinct(engine: str) -> None:
    """
    Regression guard for https://github.com/apache/superset/issues/39223:
    ``SQLStatement.format()`` must not rewrite user-defined multi-argument
    DISTINCT aggregates into row-expression null guards. This is the SQL Lab /
    executor path; the metric-expression path is covered by
    ``test_sanitize_clause``.
    """
    sql = "SELECT DISTINCT_AVG(DISTINCT a, b) FROM t"
    formatted = SQLScript(sql, engine).format()
    assert "DISTINCT_AVG(DISTINCT a, b)" in formatted
    assert "CASE WHEN" not in formatted


@with_feature_flags(ENABLE_TEMPLATE_PROCESSING=True)
@pytest.mark.parametrize(
    "engine",
    [
        "hive",
        "presto",
        "trino",
    ],
)
@pytest.mark.parametrize(
    "macro, expected",
    [
        (
            "latest_partition('foo.bar')",
            {Table(table="bar", schema="foo")},
        ),
        (
            "latest_partition(' foo.bar ')",  # Non-atypical user error which works
            {Table(table="bar", schema="foo")},
        ),
        (
            "latest_partition('foo.%s'|format('bar'))",
            {Table(table="bar", schema="foo")},
        ),
        (
            "latest_sub_partition('foo.bar', baz='qux')",
            {Table(table="bar", schema="foo")},
        ),
        (
            "latest_partitions('foo.bar')",
            {Table(table="bar", schema="foo")},
        ),
        (
            "first_latest_partition('foo.bar')",
            {Table(table="bar", schema="foo")},
        ),
    ],
)
def test_extract_tables_from_jinja_sql(
    mocker: MockerFixture,
    engine: str,
    macro: str,
    expected: set[Table],
) -> None:
    assert (
        process_jinja_sql(
            sql=f"'{{{{ {engine}.{macro} }}}}'",
            database=mocker.MagicMock(backend=engine),
        ).tables
        == expected
    )


@pytest.mark.parametrize(
    "engine",
    [
        "hive",
        "presto",
        "trino",
    ],
)
@pytest.mark.parametrize(
    "macro",
    [
        "latest_partition('foo.%s'|format(str('bar')))",
        "latest_partition('foo.{}'.format('bar'))",
        "latest_partitions('foo.{}'.format('bar'))",
        # A partition macro with the wrong number of arguments cannot be
        # resolved to a single table, so it must also fail closed.
        "latest_partition('foo.bar', 'extra')",
    ],
)
def test_extract_tables_from_jinja_sql_fails_closed(
    mocker: MockerFixture,
    engine: str,
    macro: str,
) -> None:
    """
    A partition macro whose table reference cannot be evaluated statically
    must fail closed, as the macro would otherwise execute against a table
    that never entered the authorization check.
    """
    with pytest.raises(SupersetParseError):
        process_jinja_sql(
            sql=f"'{{{{ {engine}.{macro} }}}}'",
            database=mocker.MagicMock(backend=engine),
        )


@with_feature_flags(ENABLE_TEMPLATE_PROCESSING=False)
def test_extract_tables_from_jinja_sql_disabled(mocker: MockerFixture) -> None:
    """
    Test the function when the feature flag is disabled.
    """
    database = mocker.MagicMock()
    database.db_engine_spec.engine = "mssql"

    assert process_jinja_sql(
        sql="SELECT 1 FROM t",
        database=database,
    ).tables == {Table("t")}


def test_extract_tables_from_jinja_sql_invalid_function(mocker: MockerFixture) -> None:
    """
    Test the function with an invalid function.
    """
    database = mocker.MagicMock(backend="postgresql")

    processor = JinjaTemplateProcessor(database)
    processor.env.globals["my_table"] = lambda: "t"
    mocker.patch(
        "superset.jinja_context.get_template_processor",
        return_value=processor,
    )

    assert process_jinja_sql(
        sql="SELECT * FROM {{ my_table() }}",
        database=database,
    ).tables == {Table("t")}


def test_process_jinja_sql_result_object_structure(mocker: MockerFixture) -> None:
    """
    Test that process_jinja_sql returns a proper JinjaSQLResult object
    with correct script and tables properties.
    """
    database = mocker.MagicMock()
    database.db_engine_spec.engine = "postgresql"

    result = process_jinja_sql(
        sql="SELECT id FROM users WHERE active = true",
        database=database,
    )

    # Test that result is the correct type
    assert isinstance(result, JinjaSQLResult)

    # Test that script property returns a SQLScript
    assert hasattr(result, "script")
    assert isinstance(result.script, SQLScript)

    # Test that tables property returns a set of Tables
    assert hasattr(result, "tables")
    assert isinstance(result.tables, set)
    assert result.tables == {Table("users")}

    # Test that the script contains the expected SQL
    formatted_sql = result.script.format()
    assert "users" in formatted_sql
    assert "active = TRUE" in formatted_sql


def test_process_jinja_sql_template_params_parameter(mocker: MockerFixture) -> None:
    """
    Test that the template_params parameter is properly handled.
    """
    database = mocker.MagicMock()
    database.db_engine_spec.engine = "postgresql"

    processor = JinjaTemplateProcessor(database)
    mocker.patch(
        "superset.jinja_context.get_template_processor",
        return_value=processor,
    )

    # Test that template_params parameter is accepted and passed through
    result = process_jinja_sql(
        sql="SELECT * FROM table_name",
        database=database,
        template_params={"param1": "value1"},
    )

    # Verify the function accepts the parameter without error
    assert isinstance(result, JinjaSQLResult)
    assert result.tables == {Table("table_name")}


@with_feature_flags(ENABLE_TEMPLATE_PROCESSING=True)
def test_process_jinja_sql_renders_exactly_once(mocker: MockerFixture) -> None:
    """
    The authorization path must validate exactly the SQL that executes.

    A template whose first render emits Jinja comment markers inside SQL
    comments used to be rendered a second time, which stripped the markers
    and everything between them from the validated SQL while the executed
    SQL (rendered once) kept the extra statement text.
    """
    database = mocker.MagicMock(backend="postgresql")
    database.db_engine_spec.engine = "postgresql"

    result = process_jinja_sql(
        sql=(
            'SELECT * FROM granted /*{{ "{#" }}*/ '
            'UNION SELECT * FROM restricted /*{{ "#}" }}*/'
        ),
        database=database,
    )

    assert Table("restricted") in result.tables
    assert Table("granted") in result.tables


@pytest.mark.parametrize(
    "sql, engine, expected",
    [
        ("SELECT * FROM users", "postgresql", True),
        ("WITH cte AS (SELECT * FROM users) SELECT * FROM cte", "postgresql", True),
        ("CREATE TABLE users AS SELECT * FROM users", "postgresql", False),
        ("ALTER TABLE users ADD COLUMN age INT", "postgresql", False),
        ("SET @value = 42", "postgresql", False),
    ],
)
def test_sqlstatement_is_select(sql: str, engine: str, expected: bool) -> None:
    """
    Test the `SQLStatement.is_select()` method.
    """
    assert SQLStatement(sql, engine).is_select() == expected


@pytest.mark.parametrize(
    "kql, expected",
    [
        ("StormEvents | take 10", True),
        ("StormEvents | limit 20", True),
        ("StormEvents | where State == 'FL' | summarize count()", True),
        ("StormEvents | where name has 'limit 10'", True),
        ("AnotherTable | take 5", True),
        ("datatable(x:int) [1, 2, 3] | take 100", True),
        (".create table StormEvents (x:int)", False),
        (".ingest inline into table StormEvents <| StormEvents | take 10", False),
    ],
)
def test_kqlstatement_is_select(kql: str, expected: bool) -> None:
    """
    Test the `KustoKQLStatement.is_select()` method.
    """
    assert KustoKQLStatement(kql, "kustokql").is_select() == expected


def test_singlestore_engine_mapping():
    """
    Test the `singlestoredb` dialect is properly used.
    """
    sql = "SELECT COUNT(*) AS `COUNT(*)`"
    statement = SQLStatement(sql, engine="singlestoredb")
    assert statement.is_select()

    # Should parse without errors
    formatted = statement.format()
    assert "COUNT(*)" in formatted


def test_awsathena_engine_mapping():
    """
    Test the `awsathena` dialect is properly mapped to ATHENA instead of PRESTO.
    """
    sql = (
        "USING EXTERNAL FUNCTION my_func(x INT) RETURNS INT LAMBDA 'lambda_name' "
        "SELECT my_func(id) FROM my_table"
    )
    statement = SQLStatement(sql, engine="awsathena")

    # Should parse without errors using Athena dialect
    statement.format()


def test_remove_quotes() -> None:
    """
    Test the `remove_quotes` helper function.
    """
    assert remove_quotes(None) is None
    assert remove_quotes('"foo"') == "foo"
    assert remove_quotes("'foo'") == "foo"
    assert remove_quotes("`foo`") == "foo"
    assert remove_quotes("'foo`") == "'foo`"


@pytest.mark.parametrize(
    "sql, engine, expected",
    [
        ("SELECT * FROM table", "postgresql", False),
        ("SELECT VERSION()", "postgresql", True),
        ("SELECT query_to_xml()", "postgresql", True),
        ("WITH cte AS (SELECT * FROM table) SELECT * FROM cte", "postgresql", False),
        (
            """
SELECT *
FROM query_to_xml('SELECT * from some_table WHERE id = 42')
            """,
            "postgresql",
            True,
        ),
        ("Table | limit 10", "kustokql", False),
    ],
)
def test_check_functions_present(sql: str, engine: str, expected: bool) -> None:
    """
    Check the `check_functions_present` method.
    """
    functions = {"version", "query_to_xml"}
    assert SQLScript(sql, engine).check_functions_present(functions) == expected


@pytest.mark.parametrize(
    "sql, engine, expected",
    [
        ("SELECT * FROM my_table", "postgresql", False),
        ("SELECT * FROM pg_stat_activity", "postgresql", True),
        ("SELECT * FROM PG_STAT_ACTIVITY", "postgresql", True),
        ("SELECT * FROM pg_roles", "postgresql", True),
        (
            "WITH cte AS (SELECT 1) SELECT * FROM cte",
            "postgresql",
            False,
        ),
        (
            "SELECT * FROM my_table; SELECT * FROM pg_settings",
            "postgresql",
            True,
        ),
        (
            "SELECT * FROM schema.pg_stat_activity",
            "postgresql",
            True,
        ),
        ("Table | limit 10", "kustokql", False),
    ],
)
def test_check_tables_present(sql: str, engine: str, expected: bool) -> None:
    """
    Check the `check_tables_present` method.
    """
    tables = {"pg_stat_activity", "pg_roles", "pg_settings"}
    assert SQLScript(sql, engine).check_tables_present(tables) == expected


@pytest.mark.parametrize(
    "engine, sql, denylist, expected",
    [
        # Postgres: schema-qualified denylist entry matches schema-qualified
        # reference.
        (
            "postgresql",
            "SELECT * FROM information_schema.tables",
            {"information_schema.tables"},
            True,
        ),
        # ... and is case-insensitive.
        (
            "postgresql",
            "SELECT * FROM INFORMATION_SCHEMA.TABLES",
            {"information_schema.tables"},
            True,
        ),
        # Schema-qualified denylist entry does NOT match a bare-name table
        # of the same name in another schema. A user table named `tables`
        # remains queryable.
        (
            "postgresql",
            "SELECT * FROM public.tables",
            {"information_schema.tables"},
            False,
        ),
        (
            "postgresql",
            "SELECT * FROM tables",
            {"information_schema.tables"},
            False,
        ),
        # Bare-name denylist entry still matches by table name only
        # (existing behavior, schema-agnostic).
        (
            "postgresql",
            "SELECT * FROM pg_stat_activity",
            {"pg_stat_activity"},
            True,
        ),
        (
            "postgresql",
            "SELECT * FROM pg_catalog.pg_stat_activity",
            {"pg_stat_activity"},
            True,
        ),
        # Mixed entries: one schema-qualified, one bare. Match either.
        (
            "postgresql",
            "SELECT * FROM information_schema.columns",
            {"information_schema.tables", "information_schema.columns"},
            True,
        ),
        (
            "postgresql",
            "SELECT * FROM pg_roles",
            {"information_schema.tables", "pg_roles"},
            True,
        ),
        # Negative control.
        (
            "postgresql",
            "SELECT * FROM my_table",
            {"information_schema.tables", "pg_roles"},
            False,
        ),
        # MySQL: the shipped DISALLOWED_SQL_TABLES['mysql'] entries are all
        # schema-qualified (`mysql.user`, `performance_schema.threads`,
        # `performance_schema.processlist`). Without schema-aware matching
        # the entries are dead config. These cases pin the fix.
        (
            "mysql",
            "SELECT user, host, authentication_string FROM mysql.user",
            {"mysql.user"},
            True,
        ),
        (
            "mysql",
            "SELECT * FROM performance_schema.threads",
            {"performance_schema.threads"},
            True,
        ),
        (
            "mysql",
            "SELECT * FROM performance_schema.processlist",
            {"performance_schema.processlist"},
            True,
        ),
        # MySQL must NOT block a user-authored table that shares the leaf
        # name with the system view.
        (
            "mysql",
            "SELECT * FROM mydb.user",
            {"mysql.user"},
            False,
        ),
        # MSSQL: same shape, `sys.*` entries are schema-qualified.
        (
            "mssql",
            "SELECT name, password_hash FROM sys.sql_logins",
            {"sys.sql_logins"},
            True,
        ),
        (
            "mssql",
            "SELECT name, sid FROM sys.server_principals",
            {"sys.server_principals"},
            True,
        ),
        (
            "mssql",
            "SELECT * FROM sys.configurations",
            {"sys.configurations"},
            True,
        ),
        # MSSQL must NOT block a user-authored table sharing the leaf name.
        (
            "mssql",
            "SELECT * FROM mydb.sql_logins",
            {"sys.sql_logins"},
            False,
        ),
        # Three-part (catalog.schema.table) denylist entries match the
        # fully-qualified reference, the multi-dot form is indexed rather than
        # silently dead.
        (
            "trino",
            "SELECT * FROM cat.sys.sql_logins",
            {"cat.sys.sql_logins"},
            True,
        ),
        # ... and a different catalog must NOT match.
        (
            "trino",
            "SELECT * FROM other.sys.sql_logins",
            {"cat.sys.sql_logins"},
            False,
        ),
    ],
)
def test_check_tables_present_schema_qualified(
    engine: str, sql: str, denylist: set[str], expected: bool
) -> None:
    """
    `check_tables_present` must distinguish schema-qualified denylist
    entries (e.g. `information_schema.tables`, `mysql.user`,
    `sys.sql_logins`) from bare-name entries (e.g. `pg_stat_activity`).
    Schema-qualified entries only match schema-qualified references in
    the SQL; bare entries match the table name regardless of schema.

    Covers Postgres, MySQL, and MSSQL dialects so the shipped
    DISALLOWED_SQL_TABLES entries for each remain effective.
    """
    assert SQLScript(sql, engine).check_tables_present(denylist) == expected


@pytest.mark.parametrize(
    "engine, sql, denylist, expected",
    [
        # A schema-qualified match is reported in its original denylist form,
        # not collapsed to the bare leaf name and not the whole denylist.
        (
            "postgresql",
            "SELECT * FROM information_schema.tables",
            {"information_schema.tables", "information_schema.columns", "pg_roles"},
            {"information_schema.tables"},
        ),
        # Bare-name match is reported as-is.
        (
            "postgresql",
            "SELECT * FROM pg_catalog.pg_stat_activity",
            {"pg_stat_activity", "pg_roles"},
            {"pg_stat_activity"},
        ),
        # Multiple references across statements union their matches.
        (
            "postgresql",
            "SELECT * FROM information_schema.tables; SELECT * FROM pg_roles",
            {"information_schema.tables", "pg_roles", "pg_settings"},
            {"information_schema.tables", "pg_roles"},
        ),
        # No match returns an empty set.
        (
            "postgresql",
            "SELECT * FROM my_table",
            {"information_schema.tables", "pg_roles"},
            set(),
        ),
        # A three-part (catalog.schema.table) denylist entry matches a
        # fully-qualified reference, reported in its original form.
        (
            "trino",
            "SELECT * FROM cat.sys.sql_logins",
            {"cat.sys.sql_logins"},
            {"cat.sys.sql_logins"},
        ),
        # ... but only when the catalog lines up: a different catalog does not
        # match the three-part entry.
        (
            "trino",
            "SELECT * FROM other.sys.sql_logins",
            {"cat.sys.sql_logins"},
            set(),
        ),
    ],
)
def test_get_disallowed_tables(
    engine: str, sql: str, denylist: set[str], expected: set[str]
) -> None:
    """
    `get_disallowed_tables` returns exactly the denylist entries referenced,
    in their original (possibly schema-qualified) form, so callers can report
    precisely which tables were hit instead of echoing the whole denylist.
    """
    assert SQLScript(sql, engine).get_disallowed_tables(denylist) == expected


@pytest.mark.parametrize(
    "sql, default_schema, denylist, expected",
    [
        # Unqualified reference resolves to the default schema, so it matches
        # a schema-qualified denylist entry when the schemas line up (e.g. a
        # connection whose search_path is `information_schema`).
        (
            "SELECT * FROM tables",
            "information_schema",
            {"information_schema.tables"},
            {"information_schema.tables"},
        ),
        # ... case-insensitively.
        (
            "SELECT * FROM tables",
            "INFORMATION_SCHEMA",
            {"information_schema.tables"},
            {"information_schema.tables"},
        ),
        # The same unqualified name under a user schema must NOT match: a user
        # table named `tables` stays queryable.
        (
            "SELECT * FROM tables",
            "public",
            {"information_schema.tables"},
            set(),
        ),
        # An explicit schema on the reference wins over the default schema.
        (
            "SELECT * FROM public.tables",
            "information_schema",
            {"information_schema.tables"},
            set(),
        ),
        # Without a default schema, behavior is unchanged: unqualified
        # references never match schema-qualified entries.
        (
            "SELECT * FROM tables",
            None,
            {"information_schema.tables"},
            set(),
        ),
        # Bare-name denylist entries are schema-agnostic and unaffected by the
        # default schema.
        (
            "SELECT * FROM pg_stat_activity",
            "information_schema",
            {"pg_stat_activity"},
            {"pg_stat_activity"},
        ),
        # The default schema is forwarded to every statement in a script, so an
        # unqualified reference in a later statement is resolved too.
        (
            "SELECT * FROM my_table; SELECT * FROM tables",
            "information_schema",
            {"information_schema.tables"},
            {"information_schema.tables"},
        ),
    ],
)
def test_get_disallowed_tables_default_schema(
    sql: str,
    default_schema: str | None,
    denylist: set[str],
    expected: set[str],
) -> None:
    """
    `get_disallowed_tables` resolves an unqualified reference against the
    supplied default schema, so a denylisted system view (e.g.
    `information_schema.tables`) is still caught when reached without an
    explicit schema under that search_path, without blocking a same-named
    user table under a different schema.
    """
    assert (
        SQLScript(sql, "postgresql").get_disallowed_tables(denylist, default_schema)
        == expected
    )


@pytest.mark.parametrize(
    "sql, default_schema, denylist, expected",
    [
        # `SET search_path` rebinds where an unqualified reference resolves, so
        # the static default schema can no longer be trusted. A qualified
        # denylist entry must still match the later unqualified reference,
        # otherwise the block is trivially bypassable.
        (
            "SET search_path = information_schema; SELECT * FROM tables",
            "public",
            {"information_schema.tables"},
            {"information_schema.tables"},
        ),
        # `SET search_path TO "$user", ...` falls back to an exp.Command (it is
        # not a structured exp.Set), exercising the same conservative matching
        # via the command-name detection branch.
        (
            'SET search_path TO "$user", information_schema; SELECT * FROM tables',
            "public",
            {"information_schema.tables"},
            {"information_schema.tables"},
        ),
        # `set_config('search_path', ...)` rebinds the search path through a
        # function call and must trigger the same conservative matching.
        (
            "SELECT set_config('search_path', 'information_schema', true);"
            " SELECT * FROM tables",
            "public",
            {"information_schema.tables"},
            {"information_schema.tables"},
        ),
        # The search-path change only affects later statements: a statement that
        # runs before it keeps resolving against the original default schema, so
        # its unqualified reference must NOT be widened.
        (
            "SELECT * FROM tables; SET search_path = information_schema",
            "public",
            {"information_schema.tables"},
            set(),
        ),
        # An explicitly qualified reference is unambiguous and must NOT be
        # widened to match a different schema's denylist entry.
        (
            "SET search_path = information_schema; SELECT * FROM public.tables",
            "public",
            {"information_schema.tables"},
            set(),
        ),
        # Without a search_path change, matching is unchanged: an unqualified
        # reference under a user schema does not match the qualified entry.
        (
            "SELECT * FROM tables",
            "public",
            {"information_schema.tables"},
            set(),
        ),
    ],
)
def test_get_disallowed_tables_search_path_change(
    sql: str,
    default_schema: str | None,
    denylist: set[str],
    expected: set[str],
) -> None:
    """
    A `SET search_path` in the script makes unqualified references resolve to a
    schema other than the caller's default, so `get_disallowed_tables` matches
    them against schema-qualified entries too, closing a denylist bypass.
    """
    assert (
        SQLScript(sql, "postgresql").get_disallowed_tables(denylist, default_schema)
        == expected
    )


@pytest.mark.parametrize(
    "sql, expected",
    [
        # Structured `SET search_path` (exp.Set), surfaced via get_settings().
        ("SET search_path = information_schema", True),
        # Exotic form that falls back to exp.Command; the leading setting name
        # is `search_path`.
        ('SET search_path TO "$user", public', True),
        # `SET SESSION ...` can also fall back to exp.Command; the optional
        # SESSION/LOCAL qualifier is skipped before matching the setting name.
        ("SET SESSION search_path FROM CURRENT", True),
        # A quoted identifier is equivalent to the unquoted form in Postgres,
        # so it must be recognized too (both the exp.Set and exp.Command forms).
        ('SET "search_path" = information_schema', True),
        ('SET "search_path" TO "$user", public', True),
        # A `SET` whose value merely contains the substring `search_path` must
        # not be misclassified (the setting being changed is `ROLE`).
        ("SET ROLE app_search_path_user", False),
        # `set_config('search_path', ...)` rebinds the path via a function call.
        ("SELECT set_config('search_path', 'information_schema', true)", True),
        # A different setting changed through `set_config` is not a search-path
        # change.
        ("SELECT set_config('statement_timeout', '0', true)", False),
        # An unrelated (non-`set_config`) function call is not a change either.
        ("SELECT my_custom_func(1)", False),
        ("SELECT 1", False),
    ],
)
def test_changes_search_path(sql: str, expected: bool) -> None:
    """
    `changes_search_path` detects search-path rebinds (via `SET` or
    `set_config`) without misclassifying unrelated `SET` statements.
    """
    assert SQLStatement(sql, "postgresql").changes_search_path() == expected


@pytest.mark.parametrize(
    "sql, engine, expected",
    [
        # `USE` rebinds the schema for every later statement on the cursor.
        ("USE tenant_b; SELECT * FROM orders", "mysql", True),
        ("use `tenant_b`", "mysql", True),
        ("USE SCHEMA tenant_b", "snowflake", True),
        # Warehouse selection changes compute, not name resolution.
        ("USE WAREHOUSE compute_wh", "snowflake", False),
        # Search-path changes are schema rebinds too.
        ("SET search_path = tenant_b", "postgresql", True),
        (
            "SELECT set_config('search_path', 'tenant_b', false)",
            "postgresql",
            True,
        ),
        # A `set_config()` with a computed setting name fails closed.
        (
            "SELECT set_config('search' || '_path', 'tenant_b', false)",
            "postgresql",
            True,
        ),
        # `SET SCHEMA` is an alias for a search-path rebind on Postgres and
        # a schema rebind on DB2-family engines.
        ("SET SCHEMA 'tenant_b'", "postgresql", True),
        ("SELECT * FROM orders", "mysql", False),
        ("SET statement_timeout = 10", "postgresql", False),
        # A structured `SET current_schema = ...` rebinds resolution through
        # a setting rather than a search path.
        ("SET current_schema = foo", "postgresql", True),
        # `SET CATALOG`/`SET SCHEMA` that fall back to an opaque command are
        # schema rebinds, including the `CURRENT` spelling; an unrelated `SET`
        # command (e.g. `SET ROLE`) is not.
        ("SET CATALOG tenant_b", "postgresql", True),
        ("SET CURRENT SCHEMA foo", "postgresql", True),
        ("SET ROLE admin", "postgresql", False),
        # A `set_config()` whose setting name is a column reference rather than
        # a literal is treated conservatively as a schema change.
        ("SELECT set_config(schema_col, 'tenant_b', false)", "postgresql", True),
        # Engines without a sqlglot AST (e.g. Kusto KQL) do not rebind schema
        # resolution through these forms.
        ("print x = 1", "kustokql", False),
    ],
)
def test_changes_default_schema(sql: str, engine: str, expected: bool) -> None:
    """
    `changes_default_schema` detects statements that rebind unqualified-name
    resolution (`USE`, `SET SCHEMA`, search-path changes) so the SQL Lab
    authorization path can reject the script before qualifying tables with
    the schema the user selected.
    """
    assert SQLScript(sql, engine).changes_default_schema() == expected


@pytest.mark.parametrize(
    "sql, denylist, expected",
    [
        ("SELECT * FROM pg_stat_activity", {"pg_stat_activity"}, True),
        ("SELECT * FROM my_table", {"pg_stat_activity"}, False),
    ],
)
def test_statement_check_tables_present(
    sql: str, denylist: set[str], expected: bool
) -> None:
    """
    `SQLStatement.check_tables_present` is the per-statement entry point that
    `SQLScript` no longer routes through (it calls `get_disallowed_tables`
    directly), so exercise it on its own to keep the override covered.
    """
    assert SQLStatement(sql, "postgresql").check_tables_present(denylist) == expected


def test_kustokql_statement_check_tables_present() -> None:
    """
    `KustoKQLStatement.check_tables_present` is unsupported and always reports
    False; exercise it directly so the override stays covered.
    """
    statement = KustoKQLStatement("foo | take 100", "kustokql")
    assert statement.check_tables_present({"foo"}) is False


@pytest.mark.parametrize(
    "kql, expected",
    [
        (
            "StormEvents | take 10",
            [
                (KQLTokenType.WORD, "StormEvents"),
                (KQLTokenType.WHITESPACE, " "),
                (KQLTokenType.OTHER, "|"),
                (KQLTokenType.WHITESPACE, " "),
                (KQLTokenType.WORD, "take"),
                (KQLTokenType.WHITESPACE, " "),
                (KQLTokenType.NUMBER, "10"),
            ],
        ),
        ("'test'", [(KQLTokenType.STRING, "'test'")]),
        ("```test```", [(KQLTokenType.STRING, "```test```")]),
        # Double-quoted strings
        ('"hello"', [(KQLTokenType.STRING, '"hello"')]),
        # Single-quoted string with escaped quote
        (
            "'it\\'s a test'",
            [(KQLTokenType.STRING, "'it\\'s a test'")],
        ),
        # Double-quoted string with escaped quote
        (
            '"say \\"hi\\""',
            [(KQLTokenType.STRING, '"say \\"hi\\""')],
        ),
        # Semicolon token
        (
            "a; b",
            [
                (KQLTokenType.WORD, "a"),
                (KQLTokenType.SEMICOLON, ";"),
                (KQLTokenType.WHITESPACE, " "),
                (KQLTokenType.WORD, "b"),
            ],
        ),
        # Semicolon inside string is not a SEMICOLON token
        (
            "'a;b'",
            [(KQLTokenType.STRING, "'a;b'")],
        ),
        # Numbers
        (
            "42",
            [(KQLTokenType.NUMBER, "42")],
        ),
        # Other/punctuation tokens
        (
            "()",
            [
                (KQLTokenType.OTHER, "("),
                (KQLTokenType.OTHER, ")"),
            ],
        ),
        # Empty input
        ("", []),
        # ARRAY bracket pattern used in Kusto engine spec
        (
            'ARRAY(["age"])',
            [
                (KQLTokenType.WORD, "ARRAY"),
                (KQLTokenType.OTHER, "("),
                (KQLTokenType.OTHER, "["),
                (KQLTokenType.STRING, '"age"'),
                (KQLTokenType.OTHER, "]"),
                (KQLTokenType.OTHER, ")"),
            ],
        ),
        # Mixed identifiers, operators, and strings
        (
            "tbl | where name == 'Alice' | take 5",
            [
                (KQLTokenType.WORD, "tbl"),
                (KQLTokenType.WHITESPACE, " "),
                (KQLTokenType.OTHER, "|"),
                (KQLTokenType.WHITESPACE, " "),
                (KQLTokenType.WORD, "where"),
                (KQLTokenType.WHITESPACE, " "),
                (KQLTokenType.WORD, "name"),
                (KQLTokenType.WHITESPACE, " "),
                (KQLTokenType.OTHER, "="),
                (KQLTokenType.OTHER, "="),
                (KQLTokenType.WHITESPACE, " "),
                (KQLTokenType.STRING, "'Alice'"),
                (KQLTokenType.WHITESPACE, " "),
                (KQLTokenType.OTHER, "|"),
                (KQLTokenType.WHITESPACE, " "),
                (KQLTokenType.WORD, "take"),
                (KQLTokenType.WHITESPACE, " "),
                (KQLTokenType.NUMBER, "5"),
            ],
        ),
        # Underscore in identifiers
        (
            "my_table",
            [(KQLTokenType.WORD, "my_table")],
        ),
        # Identifiers starting with underscore
        (
            "_col1",
            [(KQLTokenType.WORD, "_col1")],
        ),
        # Multiline string with semicolons and quotes
        (
            "```select 'x'; drop```",
            [(KQLTokenType.STRING, "```select 'x'; drop```")],
        ),
        # Adjacent strings without whitespace
        (
            "'a''b'",
            [
                (KQLTokenType.STRING, "'a'"),
                (KQLTokenType.STRING, "'b'"),
            ],
        ),
        # Dot operator
        (
            "db.table",
            [
                (KQLTokenType.WORD, "db"),
                (KQLTokenType.OTHER, "."),
                (KQLTokenType.WORD, "table"),
            ],
        ),
        # Bracket-quoted identifier (KQL style)
        (
            '["column name"]',
            [
                (KQLTokenType.OTHER, "["),
                (KQLTokenType.STRING, '"column name"'),
                (KQLTokenType.OTHER, "]"),
            ],
        ),
        # Whitespace variants (tab, newline)
        (
            "a\t\nb",
            [
                (KQLTokenType.WORD, "a"),
                (KQLTokenType.WHITESPACE, "\t\n"),
                (KQLTokenType.WORD, "b"),
            ],
        ),
        # Summarize with count aggregation
        (
            "T | summarize count() by State",
            [
                (KQLTokenType.WORD, "T"),
                (KQLTokenType.WHITESPACE, " "),
                (KQLTokenType.OTHER, "|"),
                (KQLTokenType.WHITESPACE, " "),
                (KQLTokenType.WORD, "summarize"),
                (KQLTokenType.WHITESPACE, " "),
                (KQLTokenType.WORD, "count"),
                (KQLTokenType.OTHER, "("),
                (KQLTokenType.OTHER, ")"),
                (KQLTokenType.WHITESPACE, " "),
                (KQLTokenType.WORD, "by"),
                (KQLTokenType.WHITESPACE, " "),
                (KQLTokenType.WORD, "State"),
            ],
        ),
        # Aliased aggregation with avg
        (
            "T | summarize avg_val = avg(price) by category",
            [
                (KQLTokenType.WORD, "T"),
                (KQLTokenType.WHITESPACE, " "),
                (KQLTokenType.OTHER, "|"),
                (KQLTokenType.WHITESPACE, " "),
                (KQLTokenType.WORD, "summarize"),
                (KQLTokenType.WHITESPACE, " "),
                (KQLTokenType.WORD, "avg_val"),
                (KQLTokenType.WHITESPACE, " "),
                (KQLTokenType.OTHER, "="),
                (KQLTokenType.WHITESPACE, " "),
                (KQLTokenType.WORD, "avg"),
                (KQLTokenType.OTHER, "("),
                (KQLTokenType.WORD, "price"),
                (KQLTokenType.OTHER, ")"),
                (KQLTokenType.WHITESPACE, " "),
                (KQLTokenType.WORD, "by"),
                (KQLTokenType.WHITESPACE, " "),
                (KQLTokenType.WORD, "category"),
            ],
        ),
        # Multiple aggregations with dcount
        (
            "T | summarize cnt = count(), uniq = dcount(user_id)",
            [
                (KQLTokenType.WORD, "T"),
                (KQLTokenType.WHITESPACE, " "),
                (KQLTokenType.OTHER, "|"),
                (KQLTokenType.WHITESPACE, " "),
                (KQLTokenType.WORD, "summarize"),
                (KQLTokenType.WHITESPACE, " "),
                (KQLTokenType.WORD, "cnt"),
                (KQLTokenType.WHITESPACE, " "),
                (KQLTokenType.OTHER, "="),
                (KQLTokenType.WHITESPACE, " "),
                (KQLTokenType.WORD, "count"),
                (KQLTokenType.OTHER, "("),
                (KQLTokenType.OTHER, ")"),
                (KQLTokenType.OTHER, ","),
                (KQLTokenType.WHITESPACE, " "),
                (KQLTokenType.WORD, "uniq"),
                (KQLTokenType.WHITESPACE, " "),
                (KQLTokenType.OTHER, "="),
                (KQLTokenType.WHITESPACE, " "),
                (KQLTokenType.WORD, "dcount"),
                (KQLTokenType.OTHER, "("),
                (KQLTokenType.WORD, "user_id"),
                (KQLTokenType.OTHER, ")"),
            ],
        ),
        # Summarize with bin time bucketing
        (
            "T | summarize count() by bin(ts, 1h)",
            [
                (KQLTokenType.WORD, "T"),
                (KQLTokenType.WHITESPACE, " "),
                (KQLTokenType.OTHER, "|"),
                (KQLTokenType.WHITESPACE, " "),
                (KQLTokenType.WORD, "summarize"),
                (KQLTokenType.WHITESPACE, " "),
                (KQLTokenType.WORD, "count"),
                (KQLTokenType.OTHER, "("),
                (KQLTokenType.OTHER, ")"),
                (KQLTokenType.WHITESPACE, " "),
                (KQLTokenType.WORD, "by"),
                (KQLTokenType.WHITESPACE, " "),
                (KQLTokenType.WORD, "bin"),
                (KQLTokenType.OTHER, "("),
                (KQLTokenType.WORD, "ts"),
                (KQLTokenType.OTHER, ","),
                (KQLTokenType.WHITESPACE, " "),
                (KQLTokenType.NUMBER, "1"),
                (KQLTokenType.WORD, "h"),
                (KQLTokenType.OTHER, ")"),
            ],
        ),
        (
            "T | summarize dcountif(user_id, status == 'active') by region",
            [
                (KQLTokenType.WORD, "T"),
                (KQLTokenType.WHITESPACE, " "),
                (KQLTokenType.OTHER, "|"),
                (KQLTokenType.WHITESPACE, " "),
                (KQLTokenType.WORD, "summarize"),
                (KQLTokenType.WHITESPACE, " "),
                (KQLTokenType.WORD, "dcountif"),
                (KQLTokenType.OTHER, "("),
                (KQLTokenType.WORD, "user_id"),
                (KQLTokenType.OTHER, ","),
                (KQLTokenType.WHITESPACE, " "),
                (KQLTokenType.WORD, "status"),
                (KQLTokenType.WHITESPACE, " "),
                (KQLTokenType.OTHER, "="),
                (KQLTokenType.OTHER, "="),
                (KQLTokenType.WHITESPACE, " "),
                (KQLTokenType.STRING, "'active'"),
                (KQLTokenType.OTHER, ")"),
                (KQLTokenType.WHITESPACE, " "),
                (KQLTokenType.WORD, "by"),
                (KQLTokenType.WHITESPACE, " "),
                (KQLTokenType.WORD, "region"),
            ],
        ),
        (
            "T | project tostring(value)",
            [
                (KQLTokenType.WORD, "T"),
                (KQLTokenType.WHITESPACE, " "),
                (KQLTokenType.OTHER, "|"),
                (KQLTokenType.WHITESPACE, " "),
                (KQLTokenType.WORD, "project"),
                (KQLTokenType.WHITESPACE, " "),
                (KQLTokenType.WORD, "tostring"),
                (KQLTokenType.OTHER, "("),
                (KQLTokenType.WORD, "value"),
                (KQLTokenType.OTHER, ")"),
            ],
        ),
    ],
)
def test_tokenize_kql(kql: str, expected: list[tuple[KQLTokenType, str]]) -> None:
    """
    Test the `tokenize_kql` function.
    """
    assert tokenize_kql(kql) == expected


@pytest.mark.parametrize(
    "sql, engine, expected",
    [
        ("a = 1", "postgresql", False),
        ("(SELECT * FROM table)", "postgresql", True),
        ("SELECT * FROM table", "postgresql", False),
        ("SELECT * FROM (SELECT 1)", "postgresql", True),
        ("SELECT * FROM (SELECT 1) AS subquery", "postgresql", True),
        ("WITH cte AS (SELECT 1) SELECT * FROM cte", "postgresql", True),
        ("SELECT * FROM table WHERE EXISTS (SELECT 1)", "postgresql", True),
        ("SELECT * FROM table WHERE NOT EXISTS (SELECT 1)", "postgresql", True),
        (
            "SELECT * FROM table WHERE id IN (SELECT id FROM other_table)",
            "postgresql",
            True,
        ),
        # Set operations: a top-level UNION/INTERSECT/EXCEPT is not an
        # exp.Subquery, so it must be detected explicitly. A predicate fragment
        # that introduces one (e.g. supplied through a chart filter) must be
        # flagged.
        ("true UNION SELECT name FROM other_table", "postgresql", True),
        ("1 = 1 UNION ALL SELECT password FROM users", "postgresql", True),
        ("SELECT 1 INTERSECT SELECT 2", "postgresql", True),
        ("SELECT 1 EXCEPT SELECT 2", "postgresql", True),
        # Nested SELECT under non-Select top-level nodes (e.g. extra
        # parentheses) must still be detected.
        ("name IN (((SELECT secret FROM s)))", "postgresql", True),
    ],
)
def test_has_subquery(sql: str, engine: str, expected: bool) -> None:
    """
    Test the `has_subquery` method.
    """
    assert SQLStatement(sql, engine).has_subquery() == expected


@pytest.mark.parametrize(
    "sql, engine",
    [
        # Double-quoted identifiers (#32684 — postgres dataset)
        ('"Adresse E-mail"', "postgresql"),
        ('"Nom de structure"', "postgresql"),
        # Backtick-quoted identifiers (#32541 — mysql view)
        ("`Answer Created Time`", "mysql"),
        ("`Correction Time`", "mysql"),
        # Diacritics, slash, and dot — listed as "working" in #32684 but
        # easily broken by overzealous parser changes; pin them too.
        ('"Appartement / étage"', "postgresql"),
        ('"Bâtiment / Résidence"', "postgresql"),
        ('"C.Postal"', "postgresql"),
    ],
)
def test_quoted_column_name_with_spaces_is_not_subquery(sql: str, engine: str) -> None:
    r"""
    Regression for #32541 and #32684: a quoted identifier that happens to
    contain spaces (or a slash, accents, dots) must not be misclassified
    as a subquery.

    The original symptom was an opaque ``Custom SQL fields cannot contain
    sub-queries.`` error when the user added a column like ``"Adresse
    E-mail"`` (Postgres) or a backtick-quoted equivalent (MySQL) to a
    chart. Snake-case aliases worked; multi-word display names did not.
    The check that raises that error is
    ``parsed_statement.has_subquery()`` in
    ``superset/models/helpers.py:206``.
    """
    assert not SQLStatement(sql, engine).has_subquery(), (
        f"Quoted identifier {sql!r} on {engine!r} was misclassified as a "
        "subquery — would block the column from being used in any chart."
    )


@pytest.mark.parametrize(
    "sql, engine, expected_tables",
    [
        # Issue #31853: Backtick-quoted table names with "Other" database type
        (
            "SELECT * FROM database.`6`",
            "base",
            {Table(table="6", schema="database")},
        ),
        (
            "SELECT * FROM database.`6` LIMIT 100",
            "base",
            {Table(table="6", schema="database")},
        ),
        # Backtick-quoted table name without schema
        (
            "SELECT * FROM `my_table`",
            "base",
            {Table(table="my_table")},
        ),
        # Backtick-quoted schema and table
        (
            "SELECT * FROM `my_schema`.`my_table`",
            "base",
            {Table(table="my_table", schema="my_schema")},
        ),
        # Complex query with multiple backtick-quoted identifiers
        (
            "SELECT `col1`, `col2` FROM `schema`.`table` WHERE `id` = 1",
            "base",
            {Table(table="table", schema="schema")},
        ),
        # Unknown engine should also fall back
        (
            "SELECT * FROM `table_name`",
            "unknown-engine",
            {Table(table="table_name")},
        ),
        # Multiple tables with backticks
        (
            "SELECT * FROM `t1` JOIN `t2` ON `t1`.id = `t2`.id",
            "base",
            {Table(table="t1"), Table(table="t2")},
        ),
        # Backticks in subquery
        (
            "SELECT * FROM (SELECT * FROM `inner_table`) AS sub",
            "base",
            {Table(table="inner_table")},
        ),
    ],
)
def test_backtick_quoted_identifiers_base_dialect(
    sql: str, engine: str, expected_tables: set[Table]
) -> None:
    """
    Test that backtick-quoted identifiers work with base dialect.

    This is a regression test for issue #31853 where SQL parsing fails
    with "Other" database type when using backtick-quoted table names.
    The fix adds a fallback to MySQL dialect when parsing fails with
    base dialect and backticks are present in the SQL.
    """
    script = SQLScript(sql, engine)
    assert len(script.statements) == 1
    assert script.statements[0].tables == expected_tables


def test_backtick_normal_sql_still_works() -> None:
    """
    Test that normal SQL without backticks still works with base dialect.

    This ensures the backtick fallback doesn't break normal parsing.
    """
    sql = "SELECT col1, col2 FROM my_schema.my_table WHERE id = 1"
    script = SQLScript(sql, "base")
    assert len(script.statements) == 1
    assert script.statements[0].tables == {Table(table="my_table", schema="my_schema")}


def test_backtick_invalid_sql_still_fails() -> None:
    """
    Test that invalid SQL with backticks still raises an error.

    The fallback should only succeed when the MySQL dialect can parse
    the SQL successfully.
    """
    # Invalid SQL that should fail even with MySQL dialect
    sql = "SELECT * FROM `table` WHERE"
    with pytest.raises(SupersetParseError):
        SQLScript(sql, "base")


def test_base_sql_statement_is_destructive_raises_not_implemented() -> None:
    """
    BaseSQLStatement.is_destructive is abstract; both concrete subclasses
    (SQLStatement and KustoKQLStatement) override it, so calling the base
    implementation directly must raise. This exercises the abstract stub
    so it stays exercised under coverage.
    """
    with pytest.raises(NotImplementedError):
        BaseSQLStatement.is_destructive(object())  # type: ignore[arg-type]


# ---------------------------------------------------------------------------
# SQL_MAX_PARSE_LENGTH gate
# ---------------------------------------------------------------------------


@pytest.fixture
def _small_parse_cap(mocker: MockerFixture) -> None:
    """
    Pin the parse-length cap to 100 bytes and force the no-app-context
    fallback path so tests are decoupled from the suite's Flask config.
    """
    mocker.patch("superset.config.SQL_MAX_PARSE_LENGTH", 100)
    mocker.patch("superset.sql.parse.has_app_context", return_value=False)


@pytest.mark.usefixtures("_small_parse_cap")
def test_check_script_length_accepts_at_boundary() -> None:
    """A script exactly at the configured cap is accepted."""
    _check_script_length("a" * 100, "postgresql")


@pytest.mark.usefixtures("_small_parse_cap")
def test_check_script_length_rejects_one_over() -> None:
    """One byte above the cap is rejected before sqlglot runs."""
    with pytest.raises(SupersetParseError) as excinfo:
        _check_script_length("a" * 101, "postgresql")
    assert "exceeds the configured maximum" in str(excinfo.value)


def test_check_script_length_counts_utf8_bytes(mocker: MockerFixture) -> None:
    """
    The cap is in UTF-8 bytes, not code points. A multi-byte char string
    whose char-count is under the cap but byte-count is over must reject.
    """
    mocker.patch("superset.config.SQL_MAX_PARSE_LENGTH", 30)
    mocker.patch("superset.sql.parse.has_app_context", return_value=False)
    # 20 emoji = 20 code points (under the 30-byte cap) but 80 UTF-8 bytes (over)
    payload = "\U0001f600" * 20
    with pytest.raises(SupersetParseError):
        _check_script_length(payload, "postgresql")


def test_check_script_length_disabled_when_config_none(
    mocker: MockerFixture,
) -> None:
    """Setting SQL_MAX_PARSE_LENGTH=None disables the check entirely."""
    fake_app = mocker.MagicMock()
    fake_app.config = {"SQL_MAX_PARSE_LENGTH": None}
    mocker.patch("superset.sql.parse.has_app_context", return_value=True)
    mocker.patch("superset.sql.parse.current_app", fake_app)
    _check_script_length("a" * 10_000_000, "postgresql")


def test_check_script_length_uses_app_config_when_present(
    mocker: MockerFixture,
) -> None:
    """When an app context is active, the runtime config value wins."""
    fake_app = mocker.MagicMock()
    fake_app.config = {"SQL_MAX_PARSE_LENGTH": 50}
    mocker.patch("superset.sql.parse.has_app_context", return_value=True)
    mocker.patch("superset.sql.parse.current_app", fake_app)
    with pytest.raises(SupersetParseError):
        _check_script_length("a" * 51, "postgresql")


@pytest.mark.usefixtures("_small_parse_cap")
def test_sqlscript_gate_short_circuits_before_sqlglot(
    mocker: MockerFixture,
) -> None:
    """
    SQLScript construction must reject an over-cap script before any call
    to sqlglot.parse, including the MySQL-backtick fallback path. Captures
    the original behaviour the PR is closing: the previous code parsed
    twice on backtick failures, so the cap MUST short-circuit both.
    """
    spy = mocker.spy(sqlglot, "parse")
    over_cap_with_backtick = "SELECT * FROM `t` -- " + "x" * 200
    with pytest.raises(SupersetParseError):
        SQLScript(over_cap_with_backtick, "base")
    assert spy.call_count == 0, "length gate failed to short-circuit sqlglot.parse"


@pytest.mark.usefixtures("_small_parse_cap")
def test_parse_predicate_length_check() -> None:
    """SQLStatement.parse_predicate also goes through the length gate."""
    stmt = SQLStatement("SELECT 1", "postgresql")
    with pytest.raises(SupersetParseError):
        stmt.parse_predicate("x" * 101)


@pytest.mark.usefixtures("_small_parse_cap")
def test_transpile_to_dialect_length_check() -> None:
    """
    The standalone ``transpile_to_dialect`` entry point also gates input.

    The cap-exceeded error surfaces as ``QueryClauseValidationException`` to
    preserve the function's existing error contract (callers such as
    ``transpile_virtual_dataset_sql`` only catch that type and fall back to
    the original SQL). The underlying ``SupersetParseError`` is attached as
    ``__cause__`` so over-cap input is still distinguishable from a generic
    parse failure.
    """
    with pytest.raises(QueryClauseValidationException) as excinfo:
        transpile_to_dialect("x" * 101, target_engine="mysql")
    assert isinstance(excinfo.value.__cause__, SupersetParseError)


def test_backtick_fallback_logs_warning(caplog: pytest.LogCaptureFixture) -> None:
    """
    Test that the MySQL dialect fallback emits a warning log.

    When the base dialect fails to parse SQL containing backticks and the
    parser falls back to the MySQL dialect, the fallback should be observable
    via a warning log.
    """
    sql = "SELECT * FROM `my_table`"
    with caplog.at_level(logging.WARNING, logger="superset.sql.parse"):
        SQLScript(sql, "base")

    assert any(
        record.levelname == "WARNING" and "MySQL dialect" in record.getMessage()
        for record in caplog.records
    )


@pytest.mark.parametrize(
    "expression,expected",
    [
        ("GREATEST(confirmed, predicted)", False),
        ("MAX(GREATEST(a, b))", True),
        ("SUM(x)", True),
        ("COUNT(*)", True),
        ("SUM(x) OVER (PARTITION BY y)", False),
        ("ROW_NUMBER() OVER ()", False),
        ("SUM(SUM(x)) OVER ()", True),
        ("a + b", False),
        (")(", True),
        ("MY_CUSTOM_AGG(x)", True),
        ("a - (SELECT AVG(b) FROM t)", True),
    ],
)
def test_has_aggregate(expression: str, expected: bool) -> None:
    """
    ``has_aggregate`` detects any aggregate that is not itself directly windowed
    -- one nested inside a windowed aggregate or a subquery still counts -- and
    fails open (returns True) when the expression can't be parsed or uses a
    function sqlglot can't model.
    """
    assert has_aggregate(expression) is expected