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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
# 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.

"""
Tests for SQLExecutor.

These tests cover the SQL execution API including:
- Basic execution
- DML handling
- Jinja2 template rendering
- CTAS/CVAS support
- Security features (RLS, disallowed functions)
- Result caching
- Query model persistence
- Async execution
"""

from typing import Any
from unittest.mock import MagicMock

import msgpack
import pandas as pd
import pytest
from flask import current_app
from pytest_mock import MockerFixture
from superset_core.queries.types import (
    CacheOptions,
    QueryOptions,
    QueryStatus,
)

from superset.models.core import Database

# Note: database, database_with_dml, mock_db_session fixtures and
# mock_query_execution helper are imported from conftest.py
from .conftest import (
    _passthrough_mutate_sql_based_on_config,
    create_mock_cursor,
    mock_query_execution,
)

# =============================================================================
# Basic Execution Tests
# =============================================================================


def test_execute_select_success(
    mocker: MockerFixture, database: Database, app_context: None
) -> None:
    """Test successful SELECT query execution."""
    mock_query_execution(
        mocker,
        database,
        return_data=[(1, "Alice"), (2, "Bob")],
        column_names=["id", "name"],
    )
    mocker.patch.dict(
        current_app.config,
        {
            "SQL_QUERY_MUTATOR": None,
            "SQLLAB_TIMEOUT": 30,
            "SQL_MAX_ROW": None,
            "QUERY_LOGGER": None,
        },
    )

    result = database.execute("SELECT id, name FROM users")

    assert result.status == QueryStatus.SUCCESS
    assert len(result.statements) == 1
    assert result.statements[0].data is not None
    assert result.statements[0].row_count == 2
    assert result.error_message is None


def test_execute_with_options(
    mocker: MockerFixture, database: Database, app_context: None
) -> None:
    """Test query execution with custom options."""
    get_raw_conn_mock = mock_query_execution(
        mocker, database, return_data=[(100,)], column_names=["count"]
    )
    mocker.patch.dict(
        current_app.config,
        {
            "SQL_QUERY_MUTATOR": None,
            "SQLLAB_TIMEOUT": 30,
            "SQL_MAX_ROW": None,
            "QUERY_LOGGER": None,
        },
    )

    options = QueryOptions(catalog="main", schema="public", limit=50)
    result = database.execute("SELECT COUNT(*) FROM users", options=options)

    assert result.status == QueryStatus.SUCCESS
    get_raw_conn_mock.assert_called_once()
    call_kwargs = get_raw_conn_mock.call_args[1]
    assert call_kwargs["catalog"] == "main"
    assert call_kwargs["schema"] == "public"


def test_execute_records_execution_time(
    mocker: MockerFixture, database: Database, app_context: None
) -> None:
    """Test that execution time is recorded."""
    mock_query_execution(mocker, database, return_data=[(1,)], column_names=["id"])
    mocker.patch.dict(
        current_app.config,
        {
            "SQL_QUERY_MUTATOR": None,
            "SQLLAB_TIMEOUT": 30,
            "SQL_MAX_ROW": None,
            "QUERY_LOGGER": None,
        },
    )

    result = database.execute("SELECT id FROM users")

    assert result.status == QueryStatus.SUCCESS
    assert result.total_execution_time_ms is not None
    assert result.total_execution_time_ms >= 0


def test_execute_creates_query_record(
    mocker: MockerFixture,
    database: Database,
    app_context: None,
    mock_db_session: MagicMock,
) -> None:
    """Test that execute creates a Query record for audit."""
    from superset.sql.execution.executor import SQLExecutor

    mock_query_execution(mocker, database, return_data=[(1,)], column_names=["id"])
    mocker.patch.dict(
        current_app.config,
        {
            "SQL_QUERY_MUTATOR": None,
            "SQLLAB_TIMEOUT": 30,
            "SQL_MAX_ROW": None,
            "QUERY_LOGGER": None,
        },
    )

    # Mock _create_query_record to return a mock query with ID
    mock_query = MagicMock()
    mock_query.id = 123
    mock_create_query = mocker.patch.object(
        SQLExecutor, "_create_query_record", return_value=mock_query
    )

    result = database.execute("SELECT id FROM users")

    assert result.status == QueryStatus.SUCCESS
    assert result.query_id == 123
    mock_create_query.assert_called_once()


# =============================================================================
# DML Handling Tests
# =============================================================================


def test_execute_dml_without_permission(
    mocker: MockerFixture, database: Database, app_context: None
) -> None:
    """Test that DML queries fail when database.allow_dml is False."""
    mocker.patch.dict(
        current_app.config,
        {"SQL_QUERY_MUTATOR": None, "SQLLAB_TIMEOUT": 30},
    )

    result = database.execute("INSERT INTO users (name) VALUES ('test')")

    assert result.status == QueryStatus.FAILED
    assert result.error_message is not None
    assert "DML queries are not allowed" in result.error_message


def test_execute_dml_with_permission(
    mocker: MockerFixture, database_with_dml: Database, app_context: None
) -> None:
    """Test that DML queries succeed when database.allow_dml is True."""
    mock_query_execution(mocker, database_with_dml, return_data=[], column_names=[])
    mocker.patch.dict(
        current_app.config,
        {
            "SQL_QUERY_MUTATOR": None,
            "SQLLAB_TIMEOUT": 30,
            "SQL_MAX_ROW": None,
            "QUERY_LOGGER": None,
        },
    )

    result = database_with_dml.execute("INSERT INTO users (name) VALUES ('test')")

    assert result.status == QueryStatus.SUCCESS


def test_execute_update_without_permission(
    mocker: MockerFixture, database: Database, app_context: None
) -> None:
    """Test that UPDATE queries fail when database.allow_dml is False."""
    mocker.patch.dict(
        current_app.config,
        {"SQL_QUERY_MUTATOR": None, "SQLLAB_TIMEOUT": 30},
    )

    result = database.execute("UPDATE users SET name = 'test' WHERE id = 1")

    assert result.status == QueryStatus.FAILED
    assert result.error_message is not None
    assert "DML queries are not allowed" in result.error_message


def test_execute_delete_without_permission(
    mocker: MockerFixture, database: Database, app_context: None
) -> None:
    """Test that DELETE queries fail when database.allow_dml is False."""
    mocker.patch.dict(
        current_app.config,
        {"SQL_QUERY_MUTATOR": None, "SQLLAB_TIMEOUT": 30},
    )

    result = database.execute("DELETE FROM users WHERE id = 1")

    assert result.status == QueryStatus.FAILED
    assert result.error_message is not None
    assert "DML queries are not allowed" in result.error_message


# =============================================================================
# Jinja2 Template Rendering Tests
# =============================================================================


def test_execute_with_template_params(
    mocker: MockerFixture, database: Database, app_context: None
) -> None:
    """Test query execution with Jinja2 template parameters."""
    mock_query_execution(mocker, database, return_data=[(1,)], column_names=["id"])
    mocker.patch.dict(
        current_app.config,
        {
            "SQL_QUERY_MUTATOR": None,
            "SQLLAB_TIMEOUT": 30,
            "SQL_MAX_ROW": None,
            "QUERY_LOGGER": None,
        },
    )

    # Mock the template processor
    mock_tp = MagicMock()
    mock_tp.process_template.return_value = (
        "SELECT * FROM events WHERE date > '2024-01-01'"
    )
    mocker.patch(
        "superset.jinja_context.get_template_processor",
        return_value=mock_tp,
    )

    options = QueryOptions(
        template_params={"table": "events", "start_date": "2024-01-01"}
    )
    result = database.execute(
        "SELECT * FROM {{ table }} WHERE date > '{{ start_date }}'",
        options=options,
    )

    assert result.status == QueryStatus.SUCCESS
    mock_tp.process_template.assert_called_once()


def test_execute_without_template_params_no_rendering(
    mocker: MockerFixture, database: Database, app_context: None
) -> None:
    """Test that template rendering is skipped when no params provided."""
    mock_query_execution(mocker, database, return_data=[(1,)], column_names=["id"])
    mocker.patch.dict(
        current_app.config,
        {
            "SQL_QUERY_MUTATOR": None,
            "SQLLAB_TIMEOUT": 30,
            "SQL_MAX_ROW": None,
            "QUERY_LOGGER": None,
        },
    )

    mock_get_tp = mocker.patch("superset.jinja_context.get_template_processor")

    result = database.execute("SELECT * FROM users")

    assert result.status == QueryStatus.SUCCESS
    mock_get_tp.assert_not_called()


# =============================================================================
# Disallowed Functions Tests
# =============================================================================


def test_execute_disallowed_functions(
    mocker: MockerFixture, database: Database, app_context: None
) -> None:
    """Test that disallowed SQL functions are blocked."""
    mocker.patch.dict(
        current_app.config,
        {
            "SQL_QUERY_MUTATOR": None,
            "SQLLAB_TIMEOUT": 30,
            "DISALLOWED_SQL_FUNCTIONS": {"sqlite": {"LOAD_EXTENSION"}},
        },
    )

    result = database.execute("SELECT LOAD_EXTENSION('malicious.so')")

    assert result.status == QueryStatus.FAILED
    assert result.error_message is not None
    assert "Disallowed SQL functions" in result.error_message


def test_execute_allowed_functions(
    mocker: MockerFixture, database: Database, app_context: None
) -> None:
    """Test that allowed SQL functions work normally."""
    mock_query_execution(mocker, database, return_data=[(5,)], column_names=["count"])
    mocker.patch.dict(
        current_app.config,
        {
            "SQL_QUERY_MUTATOR": None,
            "SQLLAB_TIMEOUT": 30,
            "SQL_MAX_ROW": None,
            "DISALLOWED_SQL_FUNCTIONS": {"sqlite": {"LOAD_EXTENSION"}},
            "QUERY_LOGGER": None,
        },
    )

    result = database.execute("SELECT COUNT(*) FROM users")

    assert result.status == QueryStatus.SUCCESS


def test_execute_disallowed_tables(
    mocker: MockerFixture, database: Database, app_context: None
) -> None:
    """Test that disallowed SQL tables are blocked."""
    mocker.patch.dict(
        current_app.config,
        {
            "SQL_QUERY_MUTATOR": None,
            "SQLLAB_TIMEOUT": 30,
            "DISALLOWED_SQL_FUNCTIONS": {},
            "DISALLOWED_SQL_TABLES": {"sqlite": {"pg_stat_activity", "pg_roles"}},
        },
    )

    result = database.execute("SELECT * FROM pg_stat_activity")

    assert result.status == QueryStatus.FAILED
    assert result.error_message is not None
    assert "Disallowed SQL tables: pg_stat_activity" == result.error_message


def test_execute_allowed_tables(
    mocker: MockerFixture, database: Database, app_context: None
) -> None:
    """Test that allowed SQL tables work normally."""
    mock_query_execution(mocker, database, return_data=[(1,)], column_names=["id"])
    mocker.patch.dict(
        current_app.config,
        {
            "SQL_QUERY_MUTATOR": None,
            "SQLLAB_TIMEOUT": 30,
            "SQL_MAX_ROW": None,
            "DISALLOWED_SQL_FUNCTIONS": {},
            "DISALLOWED_SQL_TABLES": {"sqlite": {"pg_stat_activity", "pg_roles"}},
            "QUERY_LOGGER": None,
        },
    )

    result = database.execute("SELECT * FROM users")

    assert result.status == QueryStatus.SUCCESS


def test_check_disallowed_tables_no_config(
    mocker: MockerFixture, database: Database, app_context: None
) -> None:
    """Test disallowed tables check when no config exists."""
    from superset.sql.execution.executor import SQLExecutor

    mocker.patch.dict(current_app.config, {"DISALLOWED_SQL_TABLES": {}})

    executor = SQLExecutor(database)
    script = MagicMock()
    result = executor._check_disallowed_tables(script)

    assert result is None


# =============================================================================
# Row-Level Security Tests
# =============================================================================


def test_execute_rls_applied(
    mocker: MockerFixture, database: Database, app_context: None
) -> None:
    """Test that RLS is always applied."""
    from superset.sql.execution.executor import SQLExecutor

    mock_query_execution(mocker, database, return_data=[(1,)], column_names=["id"])
    mocker.patch.dict(
        current_app.config,
        {
            "SQL_QUERY_MUTATOR": None,
            "SQLLAB_TIMEOUT": 30,
            "SQL_MAX_ROW": None,
            "QUERY_LOGGER": None,
        },
    )

    # Mock _apply_rls_to_script to verify it's always called
    mock_apply_rls = mocker.patch.object(SQLExecutor, "_apply_rls_to_script")

    result = database.execute("SELECT * FROM users")

    assert result.status == QueryStatus.SUCCESS
    mock_apply_rls.assert_called()


# =============================================================================
# Result Caching Tests
# =============================================================================


def test_execute_returns_cached_result(
    mocker: MockerFixture, database: Database, app_context: None
) -> None:
    """Test that cached results are returned when available."""
    from superset.sql.execution.executor import SQLExecutor

    cached_df = pd.DataFrame({"id": [1, 2]})

    mocker.patch.dict(
        current_app.config,
        {
            "SQL_QUERY_MUTATOR": None,
            "SQLLAB_TIMEOUT": 30,
            "SQL_MAX_ROW": None,
            "QUERY_LOGGER": None,
        },
    )

    # Mock _get_from_cache to simulate a cache hit
    cached_result = MagicMock()
    cached_result.status = QueryStatus.SUCCESS
    cached_result.data = cached_df
    cached_result.is_cached = True
    mocker.patch.object(SQLExecutor, "_get_from_cache", return_value=cached_result)

    # get_raw_connection should NOT be called if cache hit
    get_conn_mock = mocker.patch.object(database, "get_raw_connection")

    result = database.execute("SELECT * FROM users")

    assert result.status == QueryStatus.SUCCESS
    assert result.is_cached is True
    get_conn_mock.assert_not_called()


def test_execute_force_cache_refresh(
    mocker: MockerFixture, database: Database, app_context: None
) -> None:
    """Test that force_cache_refresh bypasses the cache."""
    from superset.sql.execution.executor import SQLExecutor

    mock_query_execution(mocker, database, return_data=[(1,)], column_names=["id"])
    mocker.patch.dict(
        current_app.config,
        {
            "SQL_QUERY_MUTATOR": None,
            "SQLLAB_TIMEOUT": 30,
            "SQL_MAX_ROW": None,
            "QUERY_LOGGER": None,
        },
    )

    # Mock _get_from_cache - should NOT be called when force_refresh=True
    mock_get_cache = mocker.patch.object(SQLExecutor, "_get_from_cache")

    options = QueryOptions(cache=CacheOptions(force_refresh=True))
    result = database.execute("SELECT * FROM users", options=options)

    assert result.status == QueryStatus.SUCCESS
    assert result.is_cached is False
    assert sum(s.row_count for s in result.statements) == 1  # Fresh result
    mock_get_cache.assert_not_called()


def test_execute_stores_in_cache(
    mocker: MockerFixture, database: Database, app_context: None
) -> None:
    """Test that results are stored in cache."""
    from superset.sql.execution.executor import SQLExecutor

    mock_query_execution(mocker, database, return_data=[(1,)], column_names=["id"])
    mocker.patch.dict(
        current_app.config,
        {
            "SQL_QUERY_MUTATOR": None,
            "SQLLAB_TIMEOUT": 30,
            "SQL_MAX_ROW": None,
            "CACHE_DEFAULT_TIMEOUT": 300,
            "QUERY_LOGGER": None,
        },
    )

    # Mock _get_from_cache to return None (cache miss)
    mocker.patch.object(SQLExecutor, "_get_from_cache", return_value=None)
    # Mock _store_in_cache to verify it gets called
    mock_store_cache = mocker.patch.object(SQLExecutor, "_store_in_cache")

    result = database.execute("SELECT * FROM users")

    assert result.status == QueryStatus.SUCCESS
    mock_store_cache.assert_called_once()


# =============================================================================
# Timeout Tests
# =============================================================================


def test_execute_timeout(
    mocker: MockerFixture, database: Database, app_context: None
) -> None:
    """Test query timeout handling."""
    from superset.errors import ErrorLevel, SupersetErrorType
    from superset.exceptions import SupersetTimeoutException

    # Mock get_raw_connection to raise timeout
    mock_conn = MagicMock()
    mock_conn.__enter__ = MagicMock(
        side_effect=SupersetTimeoutException(
            error_type=SupersetErrorType.GENERIC_BACKEND_ERROR,
            message="Query timed out",
            level=ErrorLevel.ERROR,
        )
    )
    mock_conn.__exit__ = MagicMock(return_value=False)
    mocker.patch.object(database, "get_raw_connection", return_value=mock_conn)
    mocker.patch.dict(
        current_app.config,
        {
            "SQL_QUERY_MUTATOR": None,
            "SQLLAB_TIMEOUT": 1,
            "SQL_MAX_ROW": None,
            "QUERY_LOGGER": None,
        },
    )

    result = database.execute("SELECT * FROM large_table")

    assert result.status == QueryStatus.TIMED_OUT
    assert result.error_message is not None


def test_execute_custom_timeout(
    mocker: MockerFixture, database: Database, app_context: None
) -> None:
    """Test query with custom timeout option."""
    mock_query_execution(mocker, database, return_data=[(1,)], column_names=["id"])
    mocker.patch.dict(
        current_app.config,
        {
            "SQL_QUERY_MUTATOR": None,
            "SQLLAB_TIMEOUT": 30,
            "SQL_MAX_ROW": None,
            "QUERY_LOGGER": None,
        },
    )

    mock_timeout = mocker.patch("superset.sql.execution.executor.utils.timeout")
    mock_timeout.return_value.__enter__ = MagicMock()
    mock_timeout.return_value.__exit__ = MagicMock(return_value=False)

    options = QueryOptions(timeout_seconds=60)
    result = database.execute("SELECT * FROM users", options=options)

    assert result.status == QueryStatus.SUCCESS
    mock_timeout.assert_called_with(
        seconds=60,
        error_message="Query exceeded the 60 seconds timeout.",
    )


# =============================================================================
# Error Handling Tests
# =============================================================================


def test_execute_error(
    mocker: MockerFixture, database: Database, app_context: None
) -> None:
    """Test general error handling."""
    # Mock get_raw_connection to raise an error
    mock_conn = MagicMock()
    mock_cursor = MagicMock()
    mock_conn.cursor.return_value = mock_cursor
    mock_conn.__enter__ = MagicMock(return_value=mock_conn)
    mock_conn.__exit__ = MagicMock(return_value=False)
    mocker.patch.object(database, "get_raw_connection", return_value=mock_conn)
    mocker.patch.object(
        database, "mutate_sql_based_on_config", side_effect=lambda sql, **kw: sql
    )
    mocker.patch.object(
        database.db_engine_spec, "execute", side_effect=Exception("Database error")
    )
    mocker.patch.dict(
        current_app.config,
        {
            "SQL_QUERY_MUTATOR": None,
            "SQLLAB_TIMEOUT": 30,
            "SQL_MAX_ROW": None,
            "QUERY_LOGGER": None,
        },
    )

    result = database.execute("SELECT * FROM nonexistent")

    assert result.status == QueryStatus.FAILED
    assert result.error_message is not None
    assert "Database error" in result.error_message


def test_execute_oauth2_redirect_error_propagates(
    mocker: MockerFixture, database: Database, app_context: None
) -> None:
    """Test that OAuth2RedirectError propagates instead of being swallowed."""
    from superset.exceptions import OAuth2RedirectError

    mock_conn = MagicMock()
    mock_cursor = MagicMock()
    mock_conn.cursor.return_value = mock_cursor
    mock_conn.__enter__ = MagicMock(return_value=mock_conn)
    mock_conn.__exit__ = MagicMock(return_value=False)
    mocker.patch.object(database, "get_raw_connection", return_value=mock_conn)
    mocker.patch.object(
        database, "mutate_sql_based_on_config", side_effect=lambda sql, **kw: sql
    )
    mocker.patch.object(
        database.db_engine_spec,
        "execute",
        side_effect=OAuth2RedirectError(
            url="https://oauth.example.com/authorize",
            tab_id="test-tab",
            redirect_uri="https://superset.example.com/callback",
        ),
    )
    mocker.patch.dict(
        current_app.config,
        {
            "SQL_QUERY_MUTATOR": None,
            "SQLLAB_TIMEOUT": 30,
            "SQL_MAX_ROW": None,
            "QUERY_LOGGER": None,
        },
    )

    with pytest.raises(OAuth2RedirectError):
        database.execute("SELECT 1")


def test_execute_oauth2_error_propagates(
    mocker: MockerFixture, database: Database, app_context: None
) -> None:
    """Test that OAuth2Error propagates instead of being swallowed."""
    from superset.exceptions import OAuth2Error

    mock_conn = MagicMock()
    mock_cursor = MagicMock()
    mock_conn.cursor.return_value = mock_cursor
    mock_conn.__enter__ = MagicMock(return_value=mock_conn)
    mock_conn.__exit__ = MagicMock(return_value=False)
    mocker.patch.object(database, "get_raw_connection", return_value=mock_conn)
    mocker.patch.object(
        database, "mutate_sql_based_on_config", side_effect=lambda sql, **kw: sql
    )
    mocker.patch.object(
        database.db_engine_spec,
        "execute",
        side_effect=OAuth2Error("No configuration found for OAuth2"),
    )
    mocker.patch.dict(
        current_app.config,
        {
            "SQL_QUERY_MUTATOR": None,
            "SQLLAB_TIMEOUT": 30,
            "SQL_MAX_ROW": None,
            "QUERY_LOGGER": None,
        },
    )

    with pytest.raises(OAuth2Error):
        database.execute("SELECT 1")


# =============================================================================
# Async Execution Tests
# =============================================================================


def test_execute_async_creates_query(
    mocker: MockerFixture,
    database: Database,
    app_context: None,
    mock_db_session: MagicMock,
) -> None:
    """Test that execute_async creates a Query record and submits to Celery."""
    mocker.patch.dict(
        current_app.config, {"SQL_QUERY_MUTATOR": None, "SQLLAB_TIMEOUT": 30}
    )

    # Mock db.session.add to set query.id (simulating database auto-increment)
    def set_query_id(query: Any) -> None:
        if not hasattr(query, "id") or query.id is None:
            query.id = 123

    mock_db_session.add.side_effect = set_query_id

    mock_celery_task = mocker.patch(
        "superset.sql.execution.celery_task.execute_sql_task"
    )

    result = database.execute_async("SELECT * FROM users")

    assert result.status == QueryStatus.PENDING
    assert result.query_id is not None
    assert result.query_id == 123
    mock_db_session.add.assert_called()
    mock_celery_task.delay.assert_called()


def test_execute_async_with_options(
    mocker: MockerFixture, database: Database, app_context: None
) -> None:
    """Test async execution with custom options."""
    mocker.patch.dict(
        current_app.config, {"SQL_QUERY_MUTATOR": None, "SQLLAB_TIMEOUT": 30}
    )

    mock_celery_task = mocker.patch(
        "superset.sql.execution.celery_task.execute_sql_task"
    )

    options = QueryOptions(catalog="analytics", schema="reports")
    result = database.execute_async("SELECT * FROM sales", options=options)

    assert result.status == QueryStatus.PENDING
    mock_celery_task.delay.assert_called_once()


def test_execute_async_dml_without_permission_raises(
    mocker: MockerFixture, database: Database, app_context: None
) -> None:
    """Test that async DML queries raise exception when not allowed."""
    from superset.exceptions import SupersetSecurityException

    mocker.patch.dict(
        current_app.config, {"SQL_QUERY_MUTATOR": None, "SQLLAB_TIMEOUT": 30}
    )

    with pytest.raises(SupersetSecurityException, match="DML queries are not allowed"):
        database.execute_async("INSERT INTO users (name) VALUES ('test')")


def test_async_handle_get_status(
    mocker: MockerFixture,
    database: Database,
    app_context: None,
    mock_db_session: MagicMock,
) -> None:
    """Test that async handle can retrieve query status."""
    from superset.models.sql_lab import Query

    mock_query = MagicMock(spec=Query)
    mock_query.status = "success"
    filter_mock = mock_db_session.query.return_value.filter_by.return_value
    filter_mock.one_or_none.return_value = mock_query

    mocker.patch.dict(
        current_app.config, {"SQL_QUERY_MUTATOR": None, "SQLLAB_TIMEOUT": 30}
    )
    mocker.patch("superset.sql.execution.celery_task.execute_sql_task")

    result = database.execute_async("SELECT * FROM users")

    status = result.get_status()
    assert status == QueryStatus.SUCCESS


def test_async_handle_cancel(
    mocker: MockerFixture,
    database: Database,
    app_context: None,
    mock_db_session: MagicMock,
) -> None:
    """Test that async handle can cancel a query."""
    from superset.models.sql_lab import Query
    from superset.sql.execution.executor import SQLExecutor

    mock_query = MagicMock(spec=Query)
    mock_query.status = "running"
    mock_query.database = database
    filter_mock = mock_db_session.query.return_value.filter_by.return_value
    filter_mock.one_or_none.return_value = mock_query

    mocker.patch.dict(
        current_app.config, {"SQL_QUERY_MUTATOR": None, "SQLLAB_TIMEOUT": 30}
    )
    mocker.patch("superset.sql.execution.celery_task.execute_sql_task")
    mock_cancel = mocker.patch.object(SQLExecutor, "_cancel_query", return_value=True)

    result = database.execute_async("SELECT * FROM users")

    cancelled = result.cancel()
    assert cancelled is True
    mock_cancel.assert_called_once()


# =============================================================================
# SQL Mutation Tests
# =============================================================================


def test_execute_applies_sql_mutator(
    mocker: MockerFixture, database: Database, app_context: None
) -> None:
    """Test that SQL mutator is applied internally."""
    mock_query_execution(mocker, database, return_data=[(1,)], column_names=["id"])

    # Track what SQL gets mutated
    mutate_mock = mocker.patch.object(
        database, "mutate_sql_based_on_config", side_effect=lambda sql, **kw: sql
    )
    mocker.patch.dict(
        current_app.config,
        {
            "SQL_QUERY_MUTATOR": lambda sql, **kwargs: f"/* mutated */ {sql}",
            "SQLLAB_TIMEOUT": 30,
            "SQL_MAX_ROW": None,
            "QUERY_LOGGER": None,
        },
    )

    result = database.execute("SELECT id FROM users")

    assert result.status == QueryStatus.SUCCESS
    # Verify mutate_sql_based_on_config was called
    mutate_mock.assert_called()


@pytest.mark.parametrize("is_split", [True, False])
def test_execute_sql_with_cursor_forwards_is_split(
    mocker: MockerFixture,
    database: Database,
    app_context: None,
    mock_db_session: MagicMock,
    mock_query: MagicMock,
    is_split: bool,
) -> None:
    """
    `execute_sql_with_cursor` must forward `is_split` to the SQL mutator.

    `Database.mutate_sql_based_on_config` only fires `SQL_QUERY_MUTATOR` when
    `is_split == MUTATE_AFTER_SPLIT`, so passing the wrong value silently skips
    mutation (the SQL Lab bug behind issue #30169). This guards the contract.
    """
    from superset.sql.execution.executor import execute_sql_with_cursor

    mutate_mock: MagicMock = mocker.patch.object(
        database,
        "mutate_sql_based_on_config",
        side_effect=_passthrough_mutate_sql_based_on_config,
    )
    mocker.patch.object(database.db_engine_spec, "execute")
    mocker.patch.object(database.db_engine_spec, "fetch_data", return_value=[(1,)])
    mocker.patch("superset.result_set.SupersetResultSet", return_value=MagicMock())

    cursor: MagicMock = create_mock_cursor(["id"], data=[(1,)])

    execute_sql_with_cursor(
        database=database,
        cursor=cursor,
        statements=["SELECT id FROM t"],
        query=mock_query,
        is_split=is_split,
    )

    mutate_mock.assert_called_once()
    assert mutate_mock.call_args.kwargs["is_split"] is is_split


# =============================================================================
# Progress Tracking Tests
# =============================================================================


def test_execute_multi_statement_updates_query_progress(
    mocker: MockerFixture,
    database: Database,
    app_context: None,
    mock_db_session: MagicMock,
) -> None:
    """Test that multi-statement execution updates Query.progress."""
    from superset.models.sql_lab import Query as QueryModel
    from superset.result_set import SupersetResultSet

    # Mock raw connection for multi-statement execution
    mock_cursor = MagicMock()
    mock_cursor.description = [("id",), ("name",)]
    mock_conn = MagicMock()
    mock_conn.cursor.return_value = mock_cursor
    mock_conn.__enter__ = MagicMock(return_value=mock_conn)
    mock_conn.__exit__ = MagicMock(return_value=False)

    mocker.patch.object(database, "get_raw_connection", return_value=mock_conn)
    mocker.patch.object(
        database,
        "mutate_sql_based_on_config",
        side_effect=lambda sql, **kw: sql,
    )
    mocker.patch.object(database.db_engine_spec, "execute")
    mocker.patch.object(
        database.db_engine_spec, "fetch_data", return_value=[("1", "Alice")]
    )

    mock_result_set = MagicMock(spec=SupersetResultSet)
    mock_result_set.to_pandas_df.return_value = pd.DataFrame(
        {"id": ["1"], "name": ["Alice"]}
    )
    mocker.patch("superset.result_set.SupersetResultSet", return_value=mock_result_set)

    mocker.patch.dict(
        current_app.config,
        {
            "SQL_QUERY_MUTATOR": None,
            "SQLLAB_TIMEOUT": 30,
            "SQL_MAX_ROW": None,
            "QUERY_LOGGER": None,
        },
    )

    # Track progress updates on the Query model
    mock_query = MagicMock(spec=QueryModel)
    mock_query.id = 123
    mocker.patch("superset.models.sql_lab.Query", return_value=mock_query)

    # Execute multiple statements
    result = database.execute("SELECT 1; SELECT 2;")

    assert result.status == QueryStatus.SUCCESS
    # Query.progress should have been updated
    assert mock_query.progress == 100  # Final progress after completion
    # set_extra_json_key should have been called for progress messages
    assert mock_query.set_extra_json_key.call_count >= 2


# =============================================================================
# Query Logging Tests
# =============================================================================


def test_execute_calls_query_logger(
    mocker: MockerFixture, database: Database, app_context: None
) -> None:
    """Test that QUERY_LOGGER is called when configured."""
    mock_query_execution(mocker, database, return_data=[(1,)], column_names=["id"])
    log_calls: list[tuple[str, str, str | None]] = []

    def mock_logger(db, sql, schema, module, security_manager, context) -> None:  # noqa: ARG001
        log_calls.append((db.database_name, sql, schema))

    mocker.patch.dict(
        current_app.config,
        {
            "SQL_QUERY_MUTATOR": None,
            "SQLLAB_TIMEOUT": 30,
            "SQL_MAX_ROW": None,
            "QUERY_LOGGER": mock_logger,
        },
    )

    result = database.execute(
        "SELECT * FROM users", options=QueryOptions(schema="public")
    )

    assert result.status == QueryStatus.SUCCESS
    assert len(log_calls) == 1
    assert log_calls[0][0] == "test_db"
    # SQL may be formatted/prettified, so check for key parts
    logged_sql = log_calls[0][1]
    assert "SELECT" in logged_sql
    assert "FROM users" in logged_sql
    assert log_calls[0][2] == "public"


def test_execute_no_query_logger_configured(
    mocker: MockerFixture, database: Database, app_context: None
) -> None:
    """Test that execution works when QUERY_LOGGER is not configured."""
    mock_query_execution(mocker, database, return_data=[(1,)], column_names=["id"])
    mocker.patch.dict(
        current_app.config,
        {
            "SQL_QUERY_MUTATOR": None,
            "SQLLAB_TIMEOUT": 30,
            "SQL_MAX_ROW": None,
            "QUERY_LOGGER": None,
        },
    )

    # Should not raise any errors
    result = database.execute("SELECT * FROM users")

    assert result.status == QueryStatus.SUCCESS


# =============================================================================
# Dry Run Tests
# =============================================================================


def test_execute_dry_run_returns_transformed_sql(
    mocker: MockerFixture, database: Database, app_context: None
) -> None:
    """Test dry run returns transformed SQL without execution."""
    from superset.sql.execution.executor import SQLExecutor

    mocker.patch.dict(
        current_app.config,
        {"SQL_QUERY_MUTATOR": None, "SQLLAB_TIMEOUT": 30, "SQL_MAX_ROW": 100},
    )

    # Mock _apply_rls_to_script to verify it's called even in dry run
    mock_apply_rls = mocker.patch.object(SQLExecutor, "_apply_rls_to_script")

    # get_raw_connection should NOT be called in dry run
    get_conn_mock = mocker.patch.object(database, "get_raw_connection")

    options = QueryOptions(dry_run=True, limit=50)
    result = database.execute("SELECT * FROM users", options=options)

    assert result.status == QueryStatus.SUCCESS
    assert len(result.statements) > 0  # Transformed SQL returned in statements
    assert result.statements[0].original_sql is not None  # Has original SQL
    assert result.statements[0].executed_sql is not None  # Has transformed SQL
    assert result.statements[0].data is None  # No data in dry run
    assert result.query_id is None  # No Query model created
    mock_apply_rls.assert_called()  # RLS still applied
    get_conn_mock.assert_not_called()  # No execution


def test_execute_async_dry_run_returns_transformed_sql(
    mocker: MockerFixture, database: Database, app_context: None
) -> None:
    """Test async dry run returns transformed SQL without Celery submission."""
    mocker.patch.dict(
        current_app.config,
        {"SQL_QUERY_MUTATOR": None, "SQLLAB_TIMEOUT": 30},
    )

    # Mock Celery task - should NOT be called
    mock_celery_task = mocker.patch(
        "superset.sql.execution.celery_task.execute_sql_task"
    )

    options = QueryOptions(dry_run=True)
    result = database.execute_async("SELECT * FROM users", options=options)

    assert result.status == QueryStatus.SUCCESS
    assert result.query_id is None  # None for cached/dry-run results
    mock_celery_task.delay.assert_not_called()

    # Handle should return the dry run result
    status = result.get_status()
    assert status == QueryStatus.SUCCESS


def test_execute_async_cached_result_returns_immediately(
    mocker: MockerFixture, database: Database, app_context: None
) -> None:
    """Test async execution with cached result returns immediately."""
    from superset.sql.execution.executor import SQLExecutor

    cached_df = pd.DataFrame({"id": [1, 2]})
    cached_result = MagicMock()
    cached_result.status = QueryStatus.SUCCESS
    cached_result.data = cached_df
    cached_result.is_cached = True

    mocker.patch.dict(
        current_app.config,
        {"SQL_QUERY_MUTATOR": None, "SQLLAB_TIMEOUT": 30},
    )
    mocker.patch.object(SQLExecutor, "_get_from_cache", return_value=cached_result)

    # Mock Celery task - should NOT be called
    mock_celery_task = mocker.patch(
        "superset.sql.execution.celery_task.execute_sql_task"
    )

    result = database.execute_async("SELECT * FROM users")

    assert result.status == QueryStatus.SUCCESS
    assert result.query_id is None
    mock_celery_task.delay.assert_not_called()


# =============================================================================
# Empty Statement Tests
# =============================================================================


def test_execute_empty_sql(
    mocker: MockerFixture, database: Database, app_context: None
) -> None:
    """Test execution with empty SQL."""
    from superset.sql.execution.executor import SQLExecutor

    mock_query_execution(mocker, database, return_data=[], column_names=[])
    mocker.patch.dict(
        current_app.config,
        {
            "SQL_QUERY_MUTATOR": None,
            "SQLLAB_TIMEOUT": 30,
            "SQL_MAX_ROW": None,
            "QUERY_LOGGER": None,
        },
    )

    # Mock _create_query_record
    mock_query = MagicMock()
    mock_query.id = 123
    mocker.patch.object(SQLExecutor, "_create_query_record", return_value=mock_query)

    result = database.execute("")

    assert result.status == QueryStatus.SUCCESS
    assert sum(s.row_count for s in result.statements) == 0


def test_execute_sql_with_cursor_empty_statements(app_context: None) -> None:
    """Test execute_sql_with_cursor with empty statement list."""
    from superset.sql.execution.executor import execute_sql_with_cursor

    mock_database = MagicMock()
    mock_cursor = MagicMock()
    mock_query = MagicMock()

    result = execute_sql_with_cursor(
        database=mock_database,
        cursor=mock_cursor,
        statements=[],
        query=mock_query,
    )

    assert result == []  # Returns empty list for empty statements


@pytest.mark.parametrize("mutated_output", ["   \n", "-- governance comment\n"])
def test_execute_sql_with_cursor_empty_after_mutation(
    app_context: None,
    mutated_output: str,
) -> None:
    """A mutator that strips a statement to nothing executable (whitespace or
    comments only) raises a clean error."""
    from superset.errors import SupersetErrorType
    from superset.exceptions import SupersetErrorException
    from superset.sql.execution.executor import execute_sql_with_cursor

    mock_database = MagicMock()
    mock_database.db_engine_spec.engine = "postgresql"
    mock_database.mutate_sql_based_on_config = lambda sql, **kw: mutated_output

    mock_cursor = MagicMock()
    mock_query = MagicMock()

    with pytest.raises(SupersetErrorException) as excinfo:
        execute_sql_with_cursor(
            database=mock_database,
            cursor=mock_cursor,
            statements=["SELECT 1"],
            query=mock_query,
        )

    assert excinfo.value.error.error_type == SupersetErrorType.INVALID_SQL_ERROR
    mock_database.db_engine_spec.execute.assert_not_called()


def test_execute_sql_with_cursor_stopped_mid_execution(
    mocker: MockerFixture, app_context: None
) -> None:
    """Test execute_sql_with_cursor when query is stopped mid-execution."""
    from superset.sql.execution.executor import execute_sql_with_cursor

    mock_database = MagicMock()
    mock_database.mutate_sql_based_on_config = lambda sql, **kw: sql
    mock_database.db_engine_spec.execute = MagicMock()
    mock_database.db_engine_spec.fetch_data = MagicMock(return_value=[])

    mock_cursor = MagicMock()
    mock_cursor.description = [("id",)]
    mock_cursor.fetchall = MagicMock()

    mock_query = MagicMock()
    mock_query.schema = "public"
    mock_query.progress = 0
    mock_query.set_extra_json_key = MagicMock()

    mocker.patch("superset.sql.execution.executor.db.session")

    # Check stopped function returns True after first statement
    call_count = {"count": 0}

    def check_stopped():
        call_count["count"] += 1
        return call_count["count"] > 1

    result = execute_sql_with_cursor(
        database=mock_database,
        cursor=mock_cursor,
        statements=["SELECT 1", "SELECT 2", "SELECT 3"],
        query=mock_query,
        check_stopped_fn=check_stopped,
    )

    # Returns results collected before stopped (first statement completed)
    assert len(result) == 1  # Only first statement completed before stop


def test_execute_sql_with_cursor_custom_execute_fn(
    mocker: MockerFixture, app_context: None
) -> None:
    """Test execute_sql_with_cursor with custom execute function."""
    from superset.sql.execution.executor import execute_sql_with_cursor

    mock_database = MagicMock()
    mock_database.mutate_sql_based_on_config = lambda sql, **kw: sql
    mock_database.db_engine_spec = MagicMock()

    mock_cursor = MagicMock()
    mock_cursor.description = [("count",)]
    mock_cursor.fetchall = MagicMock()

    mock_query = MagicMock()
    mock_query.schema = "public"
    mock_query.progress = 0
    mock_query.set_extra_json_key = MagicMock()

    mocker.patch("superset.sql.execution.executor.db.session")
    mock_database.db_engine_spec.fetch_data = MagicMock(return_value=[(100,)])

    custom_execute_calls = []

    def custom_execute(cursor, sql):
        custom_execute_calls.append(sql)

    result = execute_sql_with_cursor(
        database=mock_database,
        cursor=mock_cursor,
        statements=["SELECT COUNT(*) FROM users"],
        query=mock_query,
        execute_fn=custom_execute,
    )

    assert len(custom_execute_calls) == 1
    assert result is not None


# =============================================================================
# Limit Application Tests
# =============================================================================


def test_execute_applies_limit(
    mocker: MockerFixture, database: Database, app_context: None
) -> None:
    """Test that limit is applied to SELECT queries."""
    from superset.sql.execution.executor import SQLExecutor

    mock_query_execution(mocker, database, return_data=[(1,)], column_names=["id"])
    mocker.patch.dict(
        current_app.config,
        {
            "SQL_QUERY_MUTATOR": None,
            "SQLLAB_TIMEOUT": 30,
            "SQL_MAX_ROW": None,
            "QUERY_LOGGER": None,
        },
    )

    # Mock _apply_limit_to_script
    apply_limit_mock = mocker.patch.object(SQLExecutor, "_apply_limit_to_script")

    options = QueryOptions(limit=50)
    result = database.execute("SELECT * FROM users", options=options)

    assert result.status == QueryStatus.SUCCESS
    # Verify limit was applied
    assert apply_limit_mock.called


def test_execute_respects_sql_max_row(
    mocker: MockerFixture, database: Database, app_context: None
) -> None:
    """Test that SQL_MAX_ROW config limits the effective limit."""
    from superset.sql.execution.executor import SQLExecutor

    mock_query_execution(mocker, database, return_data=[(1,)], column_names=["id"])
    mocker.patch.dict(
        current_app.config,
        {
            "SQL_QUERY_MUTATOR": None,
            "SQLLAB_TIMEOUT": 30,
            "SQL_MAX_ROW": 100,
            "QUERY_LOGGER": None,
        },
    )

    apply_limit_mock = mocker.patch.object(SQLExecutor, "_apply_limit_to_script")

    # Request 1000 but should be capped at 100
    options = QueryOptions(limit=1000)
    result = database.execute("SELECT * FROM users", options=options)

    assert result.status == QueryStatus.SUCCESS
    # Verify limit was applied
    assert apply_limit_mock.called


def test_execute_no_limit_for_dml(
    mocker: MockerFixture, database_with_dml: Database, app_context: None
) -> None:
    """Test that limit is not applied to DML queries."""
    from superset.sql.execution.executor import SQLExecutor

    mock_query_execution(mocker, database_with_dml, return_data=[], column_names=[])
    mocker.patch.dict(
        current_app.config,
        {
            "SQL_QUERY_MUTATOR": None,
            "SQLLAB_TIMEOUT": 30,
            "SQL_MAX_ROW": 100,
            "QUERY_LOGGER": None,
        },
    )

    apply_limit_mock = mocker.patch.object(SQLExecutor, "_apply_limit_to_script")

    options = QueryOptions(limit=50)
    database_with_dml.execute("INSERT INTO users VALUES (1)", options=options)

    # Should not apply limit to DML
    apply_limit_mock.assert_not_called()


def test_apply_limit_to_script_respects_sql_max_row(
    mocker: MockerFixture, database: Database, app_context: None
) -> None:
    """Test that _apply_limit_to_script caps limit at SQL_MAX_ROW."""
    from superset.sql.execution.executor import SQLExecutor
    from superset.sql.parse import SQLScript

    mocker.patch.dict(
        current_app.config,
        {
            "SQL_MAX_ROW": 100,
        },
    )

    executor = SQLExecutor(database)

    # Create a script with a statement
    script = SQLScript("SELECT * FROM users", database.db_engine_spec.engine)

    # Mock set_limit_value on the first statement
    set_limit_mock = mocker.patch.object(script.statements[0], "set_limit_value")

    options = QueryOptions(limit=1000)  # Request 1000 but should be capped at 100
    executor._apply_limit_to_script(script, options)

    # Verify limit was capped at SQL_MAX_ROW (100)
    set_limit_mock.assert_called_once_with(100, database.db_engine_spec.limit_method)


def test_apply_limit_to_script_with_empty_statements(
    mocker: MockerFixture, database: Database, app_context: None
) -> None:
    """Test that _apply_limit_to_script handles empty script.statements."""
    from superset.sql.execution.executor import SQLExecutor
    from superset.sql.parse import SQLScript

    mocker.patch.dict(
        current_app.config,
        {
            "SQL_MAX_ROW": 100,
        },
    )

    executor = SQLExecutor(database)

    # Create a script with no statements (empty string)
    script = SQLScript("", database.db_engine_spec.engine)

    options = QueryOptions(limit=50)
    # Should not raise any errors when statements is empty
    executor._apply_limit_to_script(script, options)

    # Verify no error occurred and statements is still empty
    assert script.statements == []


# =============================================================================
# Catalog/Schema Resolution Tests
# =============================================================================


def test_execute_uses_default_catalog_and_schema(
    mocker: MockerFixture, database: Database, app_context: None
) -> None:
    """Test that default catalog and schema are used when not specified."""
    mock_query_execution(mocker, database, return_data=[(1,)], column_names=["id"])
    get_default_catalog_mock = mocker.patch.object(
        database, "get_default_catalog", return_value="main"
    )
    # Schema is resolved through the query-aware ``get_default_schema_for_query``
    # (so per-query engine gates run), not the static ``get_default_schema``.
    get_default_schema_mock = mocker.patch.object(
        database, "get_default_schema_for_query", return_value="public"
    )
    mocker.patch.dict(
        current_app.config,
        {
            "SQL_QUERY_MUTATOR": None,
            "SQLLAB_TIMEOUT": 30,
            "SQL_MAX_ROW": None,
            "QUERY_LOGGER": None,
        },
    )

    result = database.execute("SELECT * FROM users")

    assert result.status == QueryStatus.SUCCESS
    # Verify default catalog/schema were fetched
    get_default_catalog_mock.assert_called()
    get_default_schema_mock.assert_called()


def test_resolve_query_schema_uses_query_aware_resolution(
    mocker: MockerFixture, database: Database, app_context: None
) -> None:
    """``_resolve_query_schema`` resolves through the query-aware
    ``get_default_schema_for_query`` (which runs per-query engine security gates),
    handing it a transient probe Query that carries the request's SQL, schema,
    catalog and template params."""
    from superset.models.sql_lab import Query
    from superset.sql.execution.executor import SQLExecutor

    resolve_mock = mocker.patch.object(
        database, "get_default_schema_for_query", return_value="resolved_schema"
    )

    executor = SQLExecutor(database)
    options = QueryOptions(schema="explicit", template_params={"p": 1})

    result = executor._resolve_query_schema("SELECT 1", options, "cat")

    assert result == "resolved_schema"
    probe, template_params = resolve_mock.call_args.args
    assert isinstance(probe, Query)
    assert probe.sql == "SELECT 1"
    assert probe.schema == "explicit"
    assert probe.catalog == "cat"
    assert template_params == {"p": 1}


def test_resolve_query_schema_omits_blank_schema(
    mocker: MockerFixture, database: Database, app_context: None
) -> None:
    """An unset request schema reaches the probe as ``None`` so the engine spec
    resolves the runtime default instead of matching on an empty string."""
    resolve_mock = mocker.patch.object(
        database, "get_default_schema_for_query", return_value="public"
    )

    from superset.sql.execution.executor import SQLExecutor

    executor = SQLExecutor(database)

    result = executor._resolve_query_schema("SELECT 1", QueryOptions(), None)

    assert result == "public"
    probe = resolve_mock.call_args.args[0]
    assert probe.schema is None
    assert probe.catalog is None


def test_prepare_sql_runs_schema_gate_with_explicit_schema(
    mocker: MockerFixture, database: Database, app_context: None
) -> None:
    """The per-query schema gate must run even when an explicit schema is
    supplied, so an explicit-schema request cannot smuggle a ``SET search_path``
    past the gate the resolver enforces (parity with the estimate path, which
    resolves unconditionally)."""
    from superset.errors import ErrorLevel, SupersetError, SupersetErrorType
    from superset.exceptions import SupersetSecurityException
    from superset.sql.execution.executor import SQLExecutor

    gate = mocker.patch.object(
        database,
        "get_default_schema_for_query",
        side_effect=SupersetSecurityException(
            SupersetError(
                message="blocked",
                error_type=SupersetErrorType.QUERY_SECURITY_ACCESS_ERROR,
                level=ErrorLevel.ERROR,
            )
        ),
    )
    executor = SQLExecutor(database)

    with pytest.raises(SupersetSecurityException):
        executor._prepare_sql(
            "SET search_path = secret; SELECT 1",
            QueryOptions(schema="explicit"),
        )

    gate.assert_called_once()


# =============================================================================
# Async Query Status and Result Tests
# =============================================================================


def test_async_handle_get_result_query_not_found(
    mocker: MockerFixture,
    database: Database,
    app_context: None,
    mock_db_session: MagicMock,
) -> None:
    """Test getting result for non-existent query."""

    # Query not found
    filter_mock = mock_db_session.query.return_value.filter_by.return_value
    filter_mock.one_or_none.return_value = None

    mocker.patch.dict(
        current_app.config, {"SQL_QUERY_MUTATOR": None, "SQLLAB_TIMEOUT": 30}
    )
    mocker.patch("superset.sql.execution.celery_task.execute_sql_task")

    result = database.execute_async("SELECT * FROM users")

    # Try to get result
    query_result = result.get_result()

    assert query_result.status == QueryStatus.FAILED
    assert query_result.error_message is not None
    assert "not found" in query_result.error_message.lower()


def test_async_handle_get_result_pending(
    mocker: MockerFixture,
    database: Database,
    app_context: None,
    mock_db_session: MagicMock,
) -> None:
    """Test getting result for pending query."""
    from superset.models.sql_lab import Query

    mock_query = MagicMock(spec=Query)
    mock_query.status = "pending"
    mock_query.error_message = None
    mock_query.executed_sql = "SELECT * FROM users"
    mock_query.results_key = None

    filter_mock = mock_db_session.query.return_value.filter_by.return_value
    filter_mock.one_or_none.return_value = mock_query

    mocker.patch.dict(
        current_app.config, {"SQL_QUERY_MUTATOR": None, "SQLLAB_TIMEOUT": 30}
    )
    mocker.patch("superset.sql.execution.celery_task.execute_sql_task")

    result = database.execute_async("SELECT * FROM users")

    query_result = result.get_result()

    assert query_result.status == QueryStatus.PENDING


def test_async_handle_get_result_with_results_backend(
    mocker: MockerFixture,
    database: Database,
    app_context: None,
    mock_db_session: MagicMock,
) -> None:
    """Test getting result from results backend."""
    from superset.models.sql_lab import Query

    mock_query = MagicMock(spec=Query)
    mock_query.status = "success"
    mock_query.error_message = None
    mock_query.executed_sql = "SELECT * FROM users"
    mock_query.results_key = "result_key_123"

    filter_mock = mock_db_session.query.return_value.filter_by.return_value
    filter_mock.one_or_none.return_value = mock_query

    # Mock results backend with new multi-statement format
    payload = msgpack.dumps(
        {
            "statements": [
                {
                    "original_sql": "SELECT * FROM users",
                    "executed_sql": "SELECT * FROM users",
                    "data": [{"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}],
                    "columns": [
                        {"column_name": "id", "name": "id"},
                        {"column_name": "name", "name": "name"},
                    ],
                    "row_count": 2,
                    "execution_time_ms": 10.0,
                }
            ],
            "total_execution_time_ms": 10.0,
        }
    )
    compressed_payload = b"compressed_data"

    mock_results_backend = MagicMock()
    mock_results_backend.get.return_value = compressed_payload

    mock_results_backend_manager = MagicMock()
    mock_results_backend_manager.results_backend = mock_results_backend

    mocker.patch(
        "superset.results_backend_manager",
        mock_results_backend_manager,
    )
    mocker.patch("superset.utils.core.zlib_decompress", return_value=payload)
    mocker.patch.dict(
        current_app.config, {"SQL_QUERY_MUTATOR": None, "SQLLAB_TIMEOUT": 30}
    )
    mocker.patch("superset.sql.execution.celery_task.execute_sql_task")

    result = database.execute_async("SELECT * FROM users")

    query_result = result.get_result()

    assert query_result.status == QueryStatus.SUCCESS
    assert len(query_result.statements) > 0
    assert query_result.statements[0].data is not None
    assert sum(s.row_count for s in query_result.statements) == 2


def test_async_handle_get_result_backend_load_error(
    mocker: MockerFixture,
    database: Database,
    app_context: None,
    mock_db_session: MagicMock,
) -> None:
    """Test error handling when loading results from backend."""
    from superset.models.sql_lab import Query

    mock_query = MagicMock(spec=Query)
    mock_query.status = "success"
    mock_query.error_message = None
    mock_query.executed_sql = "SELECT * FROM users"
    mock_query.results_key = "result_key_123"

    filter_mock = mock_db_session.query.return_value.filter_by.return_value
    filter_mock.one_or_none.return_value = mock_query

    # Mock results backend with error
    mock_results_backend = MagicMock()
    mock_results_backend.get.return_value = b"invalid_data"

    mock_results_backend_manager = MagicMock()
    mock_results_backend_manager.results_backend = mock_results_backend

    mocker.patch(
        "superset.results_backend_manager",
        mock_results_backend_manager,
    )
    mocker.patch(
        "superset.utils.core.zlib_decompress",
        side_effect=Exception("Decompression failed"),
    )
    mocker.patch.dict(
        current_app.config, {"SQL_QUERY_MUTATOR": None, "SQLLAB_TIMEOUT": 30}
    )
    mocker.patch("superset.sql.execution.celery_task.execute_sql_task")

    result = database.execute_async("SELECT * FROM users")

    query_result = result.get_result()

    assert query_result.status == QueryStatus.FAILED
    assert query_result.error_message is not None
    assert "Error loading results" in query_result.error_message


def test_async_handle_get_result_no_results_key(
    mocker: MockerFixture,
    database: Database,
    app_context: None,
    mock_db_session: MagicMock,
) -> None:
    """Test getting result when results_key is missing."""
    from superset.models.sql_lab import Query

    mock_query = MagicMock(spec=Query)
    mock_query.status = "success"
    mock_query.error_message = None
    mock_query.executed_sql = "SELECT * FROM users"
    mock_query.results_key = None  # No results key

    filter_mock = mock_db_session.query.return_value.filter_by.return_value
    filter_mock.one_or_none.return_value = mock_query

    mocker.patch.dict(
        current_app.config, {"SQL_QUERY_MUTATOR": None, "SQLLAB_TIMEOUT": 30}
    )
    mocker.patch("superset.sql.execution.celery_task.execute_sql_task")

    result = database.execute_async("SELECT * FROM users")

    query_result = result.get_result()

    assert query_result.status == QueryStatus.FAILED
    assert query_result.error_message is not None
    assert "Results not available" in query_result.error_message


def test_async_handle_get_status_query_not_found(
    mocker: MockerFixture,
    database: Database,
    app_context: None,
    mock_db_session: MagicMock,
) -> None:
    """Test getting status for non-existent query."""
    # Query not found
    filter_mock = mock_db_session.query.return_value.filter_by.return_value
    filter_mock.one_or_none.return_value = None

    mocker.patch.dict(
        current_app.config, {"SQL_QUERY_MUTATOR": None, "SQLLAB_TIMEOUT": 30}
    )
    mocker.patch("superset.sql.execution.celery_task.execute_sql_task")

    result = database.execute_async("SELECT * FROM users")

    # Override the query_id to simulate looking up a non-existent query
    object.__setattr__(result, "query_id", 999999)

    status = result.get_status()

    assert status == QueryStatus.FAILED


# =============================================================================
# Query Cancellation Tests
# =============================================================================


def test_cancel_query_implicit_cancel(
    mocker: MockerFixture, database: Database, app_context: None
) -> None:
    """Test cancel_query with implicit cancellation."""
    from superset.sql.execution.executor import SQLExecutor

    mock_query = MagicMock()
    mock_query.extra = {}

    mocker.patch.object(
        database.db_engine_spec, "has_implicit_cancel", return_value=True
    )

    result = SQLExecutor._cancel_query(database, mock_query)

    assert result is True


def test_cancel_query_early_cancel_flag(
    mocker: MockerFixture, database: Database, app_context: None
) -> None:
    """Test cancel_query with early cancel flag set."""
    from superset.constants import QUERY_EARLY_CANCEL_KEY
    from superset.sql.execution.executor import SQLExecutor

    mock_query = MagicMock()
    mock_query.extra = {QUERY_EARLY_CANCEL_KEY: True}

    mocker.patch.object(
        database.db_engine_spec, "has_implicit_cancel", return_value=False
    )
    prepare_cancel_mock = mocker.patch.object(
        database.db_engine_spec, "prepare_cancel_query"
    )

    result = SQLExecutor._cancel_query(database, mock_query)

    assert result is True
    prepare_cancel_mock.assert_called_with(mock_query)


def test_cancel_query_no_cancel_id(
    mocker: MockerFixture, database: Database, app_context: None
) -> None:
    """Test cancel_query when no cancel ID is available."""
    from superset.sql.execution.executor import SQLExecutor

    mock_query = MagicMock()
    mock_query.extra = {}

    mocker.patch.object(
        database.db_engine_spec, "has_implicit_cancel", return_value=False
    )
    mocker.patch.object(database.db_engine_spec, "prepare_cancel_query")

    result = SQLExecutor._cancel_query(database, mock_query)

    assert result is False


def test_cancel_query_with_cancel_id(
    mocker: MockerFixture, database: Database, app_context: None
) -> None:
    """Test cancel_query executes cancellation with cancel ID."""
    from superset.constants import QUERY_CANCEL_KEY
    from superset.sql.execution.executor import SQLExecutor
    from superset.utils.core import QuerySource

    mock_query = MagicMock()
    mock_query.extra = {QUERY_CANCEL_KEY: "cancel_123"}
    mock_query.catalog = "main"
    mock_query.schema = "public"

    mocker.patch.object(
        database.db_engine_spec, "has_implicit_cancel", return_value=False
    )
    mocker.patch.object(database.db_engine_spec, "prepare_cancel_query")
    cancel_query_mock = mocker.patch.object(
        database.db_engine_spec, "cancel_query", return_value=True
    )

    # Mock engine and connection
    mock_cursor = MagicMock()
    mock_conn = MagicMock()
    mock_conn.cursor.return_value.__enter__ = MagicMock(return_value=mock_cursor)
    mock_conn.cursor.return_value.__exit__ = MagicMock(return_value=False)
    mock_conn.__enter__ = MagicMock(return_value=mock_conn)
    mock_conn.__exit__ = MagicMock(return_value=False)

    mock_engine = MagicMock()
    mock_engine.raw_connection.return_value.__enter__ = MagicMock(
        return_value=mock_conn
    )
    mock_engine.raw_connection.return_value.__exit__ = MagicMock(return_value=False)
    mock_engine.__enter__ = MagicMock(return_value=mock_engine)
    mock_engine.__exit__ = MagicMock(return_value=False)

    get_sqla_engine_mock = mocker.patch.object(
        database, "get_sqla_engine", return_value=mock_engine
    )

    result = SQLExecutor._cancel_query(database, mock_query)

    assert result is True
    get_sqla_engine_mock.assert_called_with(
        catalog="main", schema="public", source=QuerySource.SQL_LAB
    )
    cancel_query_mock.assert_called_once()


def test_async_handle_cancel_query_not_found(
    mocker: MockerFixture,
    database: Database,
    app_context: None,
    mock_db_session: MagicMock,
) -> None:
    """Test cancelling non-existent query."""

    # Query not found
    filter_mock = mock_db_session.query.return_value.filter_by.return_value
    filter_mock.one_or_none.return_value = None

    mocker.patch.dict(
        current_app.config, {"SQL_QUERY_MUTATOR": None, "SQLLAB_TIMEOUT": 30}
    )
    mocker.patch("superset.sql.execution.celery_task.execute_sql_task")

    result = database.execute_async("SELECT * FROM users")

    # Override to simulate non-existent query
    object.__setattr__(result, "query_id", 999999)

    cancelled = result.cancel()

    assert cancelled is False


# =============================================================================
# Cache Timeout Tests
# =============================================================================


def test_execute_uses_database_cache_timeout(
    mocker: MockerFixture, database: Database, app_context: None
) -> None:
    """Test that database cache timeout is used when available."""
    from superset.sql.execution.executor import SQLExecutor

    mock_query_execution(mocker, database, return_data=[(1,)], column_names=["id"])
    mocker.patch.dict(
        current_app.config,
        {
            "SQL_QUERY_MUTATOR": None,
            "SQLLAB_TIMEOUT": 30,
            "SQL_MAX_ROW": None,
            "QUERY_LOGGER": None,
            "CACHE_DEFAULT_TIMEOUT": 300,
        },
    )

    database.cache_timeout = 600  # Custom timeout

    # Mock cache operations
    mocker.patch.object(SQLExecutor, "_get_from_cache", return_value=None)
    mock_cache_set = mocker.patch("superset.extensions.cache_manager.data_cache.set")

    result = database.execute("SELECT * FROM users")

    assert result.status == QueryStatus.SUCCESS
    # Verify cache timeout used
    if mock_cache_set.called:
        call_kwargs = mock_cache_set.call_args[1]
        assert call_kwargs.get("timeout") == 600


def test_execute_uses_custom_cache_timeout_option(
    mocker: MockerFixture, database: Database, app_context: None
) -> None:
    """Test that custom cache timeout from options is used."""
    from superset.sql.execution.executor import SQLExecutor

    mock_query_execution(mocker, database, return_data=[(1,)], column_names=["id"])
    mocker.patch.dict(
        current_app.config,
        {
            "SQL_QUERY_MUTATOR": None,
            "SQLLAB_TIMEOUT": 30,
            "SQL_MAX_ROW": None,
            "QUERY_LOGGER": None,
            "CACHE_DEFAULT_TIMEOUT": 300,
        },
    )

    # Mock cache operations
    mocker.patch.object(SQLExecutor, "_get_from_cache", return_value=None)
    mock_cache_set = mocker.patch("superset.extensions.cache_manager.data_cache.set")

    options = QueryOptions(cache=CacheOptions(timeout=1200))
    result = database.execute("SELECT * FROM users", options=options)

    assert result.status == QueryStatus.SUCCESS
    # Verify custom timeout used
    if mock_cache_set.called:
        call_kwargs = mock_cache_set.call_args[1]
        assert call_kwargs.get("timeout") == 1200


# =============================================================================
# Celery Submission Error Tests
# =============================================================================


def test_execute_async_celery_submission_error(
    mocker: MockerFixture,
    database: Database,
    app_context: None,
    mock_db_session: MagicMock,
) -> None:
    """Test error handling when Celery submission fails."""
    mocker.patch.dict(
        current_app.config, {"SQL_QUERY_MUTATOR": None, "SQLLAB_TIMEOUT": 30}
    )

    # Mock Celery task to raise exception
    mock_celery_task = mocker.patch(
        "superset.sql.execution.celery_task.execute_sql_task"
    )
    mock_celery_task.delay.side_effect = Exception("Celery connection failed")

    with pytest.raises(Exception, match="Celery connection failed"):
        database.execute_async("SELECT * FROM users")


# =============================================================================
# Additional Edge Case Tests for 100% Coverage
# =============================================================================


def test_execute_sql_with_cursor_no_rows_or_description(
    mocker: MockerFixture, app_context: None
) -> None:
    """Test execute_sql_with_cursor when cursor returns no rows and description."""
    from superset.sql.execution.executor import execute_sql_with_cursor

    mock_database = MagicMock()
    mock_database.mutate_sql_based_on_config = lambda sql, **kw: sql
    mock_database.db_engine_spec.execute = MagicMock()
    mock_database.db_engine_spec.fetch_data = MagicMock(return_value=None)

    mock_cursor = MagicMock()
    mock_cursor.description = None  # No description
    mock_cursor.fetchall = MagicMock()

    mock_query = MagicMock()
    mock_query.schema = "public"
    mock_query.progress = 0
    mock_query.set_extra_json_key = MagicMock()

    mocker.patch("superset.sql.execution.executor.db.session")

    result = execute_sql_with_cursor(
        database=mock_database,
        cursor=mock_cursor,
        statements=["INSERT INTO users VALUES (1)"],
        query=mock_query,
    )

    # DML statement returns result with result_set=None
    assert len(result) == 1
    assert result[0][1] is None  # result_set is None for DML


def test_execute_with_exception_on_execute(
    mocker: MockerFixture, database: Database, app_context: None
) -> None:
    """Test that _execute_statements returns empty DataFrame on None result."""
    from superset.sql.execution.executor import SQLExecutor

    # Mock to simulate None result_set
    mocker.patch(
        "superset.sql.execution.executor.execute_sql_with_cursor",
        return_value=[],  # Empty list for no results
    )

    mock_query = MagicMock()
    mock_query.id = 123
    mocker.patch.object(SQLExecutor, "_create_query_record", return_value=mock_query)

    mock_conn = MagicMock()
    mock_conn.cursor.return_value = MagicMock()
    mock_conn.__enter__ = MagicMock(return_value=mock_conn)
    mock_conn.__exit__ = MagicMock(return_value=False)
    mocker.patch.object(database, "get_raw_connection", return_value=mock_conn)

    mocker.patch.dict(
        current_app.config,
        {
            "SQL_QUERY_MUTATOR": None,
            "SQLLAB_TIMEOUT": 30,
            "SQL_MAX_ROW": None,
            "QUERY_LOGGER": None,
        },
    )

    result = database.execute("SELECT * FROM nonexistent")

    # Should handle None result_set gracefully
    assert result.status == QueryStatus.SUCCESS
    assert sum(s.row_count for s in result.statements) == 0


def test_check_disallowed_functions_no_config(
    mocker: MockerFixture, database: Database, app_context: None
) -> None:
    """Test disallowed functions check when no config exists."""
    from superset.sql.execution.executor import SQLExecutor

    mocker.patch.dict(current_app.config, {"DISALLOWED_SQL_FUNCTIONS": {}})

    executor = SQLExecutor(database)
    script = MagicMock()
    result = executor._check_disallowed_functions(script)

    assert result is None


def test_try_get_cached_result_with_mutation(
    mocker: MockerFixture, database: Database, app_context: None
) -> None:
    """Test that cache is skipped for mutation queries."""
    from superset.sql.execution.executor import SQLExecutor

    executor = SQLExecutor(database)

    script = MagicMock()
    script.has_mutation.return_value = True

    result = executor._try_get_cached_result(script, "INSERT INTO foo", MagicMock())

    # Should skip cache for mutations
    assert result is None


def test_store_in_cache_with_failed_status(
    mocker: MockerFixture, database: Database, app_context: None
) -> None:
    """Test that failed queries are not cached."""
    from superset_core.queries.types import QueryResult as QueryResultType

    from superset.sql.execution.executor import SQLExecutor

    executor = SQLExecutor(database)

    failed_result = QueryResultType(
        status=QueryStatus.FAILED,
        error_message="Test error",
    )

    mock_cache_set = mocker.patch("superset.extensions.cache_manager.data_cache.set")

    executor._store_in_cache(failed_result, "SELECT 1", QueryOptions())

    # Should not cache failed queries
    mock_cache_set.assert_not_called()


def test_store_in_cache_with_no_data(
    mocker: MockerFixture, database: Database, app_context: None
) -> None:
    """Test that DML queries (with no data) are cached."""
    from superset_core.queries.types import (
        QueryResult as QueryResultType,
        StatementResult,
    )

    from superset.sql.execution.executor import SQLExecutor

    executor = SQLExecutor(database)

    result_no_data = QueryResultType(
        status=QueryStatus.SUCCESS,
        statements=[
            StatementResult(
                original_sql="INSERT INTO t VALUES (1)",
                executed_sql="INSERT INTO t VALUES (1)",
                data=None,
                row_count=1,
            )
        ],
    )

    mock_cache_set = mocker.patch("superset.extensions.cache_manager.data_cache.set")

    executor._store_in_cache(result_no_data, "INSERT INTO t VALUES (1)", QueryOptions())

    # DML queries are cached too
    mock_cache_set.assert_called_once()


def test_create_cached_async_result_cancel(
    mocker: MockerFixture, database: Database, app_context: None
) -> None:
    """Test that cached async result cancel returns False."""
    from superset_core.queries.types import (
        QueryResult as QueryResultType,
        StatementResult,
    )

    from superset.sql.execution.executor import SQLExecutor

    mocker.patch.dict(
        current_app.config, {"SQL_QUERY_MUTATOR": None, "SQLLAB_TIMEOUT": 30}
    )

    executor = SQLExecutor(database)

    cached_result = QueryResultType(
        status=QueryStatus.SUCCESS,
        statements=[
            StatementResult(
                original_sql="SELECT 1",
                executed_sql="SELECT 1",
                data=pd.DataFrame({"id": [1]}),
                row_count=1,
            )
        ],
    )

    async_result = executor._create_cached_handle(cached_result)

    # Try to cancel a cached result
    cancelled = async_result.cancel()

    # Should return False (nothing to cancel)
    assert cancelled is False


def test_async_handle_get_result_with_empty_blob(
    mocker: MockerFixture,
    database: Database,
    app_context: None,
    mock_db_session: MagicMock,
) -> None:
    """Test getting result when backend returns None for blob."""
    from superset.models.sql_lab import Query

    mock_query = MagicMock(spec=Query)
    mock_query.status = "success"
    mock_query.error_message = None
    mock_query.executed_sql = "SELECT * FROM users"
    mock_query.results_key = "result_key_123"

    filter_mock = mock_db_session.query.return_value.filter_by.return_value
    filter_mock.one_or_none.return_value = mock_query

    # Mock results backend returning None for blob
    mock_results_backend = MagicMock()
    mock_results_backend.get.return_value = None  # No blob found

    mock_results_backend_manager = MagicMock()
    mock_results_backend_manager.results_backend = mock_results_backend

    mocker.patch(
        "superset.results_backend_manager",
        mock_results_backend_manager,
    )
    mocker.patch.dict(
        current_app.config, {"SQL_QUERY_MUTATOR": None, "SQLLAB_TIMEOUT": 30}
    )
    mocker.patch("superset.sql.execution.celery_task.execute_sql_task")

    result = database.execute_async("SELECT * FROM users")

    query_result = result.get_result()

    # Should return failure when blob not found
    assert query_result.status == QueryStatus.FAILED
    assert query_result.error_message is not None
    assert "Results not available" in query_result.error_message


def test_async_handle_get_result_no_results_backend(
    mocker: MockerFixture,
    database: Database,
    app_context: None,
    mock_db_session: MagicMock,
) -> None:
    """Test getting result when results_backend is None."""
    from superset.models.sql_lab import Query

    mock_query = MagicMock(spec=Query)
    mock_query.status = "success"
    mock_query.error_message = None
    mock_query.executed_sql = "SELECT * FROM users"
    mock_query.results_key = "result_key_123"

    filter_mock = mock_db_session.query.return_value.filter_by.return_value
    filter_mock.one_or_none.return_value = mock_query

    # Mock results_backend_manager with None backend
    mock_results_backend_manager = MagicMock()
    mock_results_backend_manager.results_backend = None  # No backend configured

    mocker.patch(
        "superset.results_backend_manager",
        mock_results_backend_manager,
    )
    mocker.patch.dict(
        current_app.config, {"SQL_QUERY_MUTATOR": None, "SQLLAB_TIMEOUT": 30}
    )
    mocker.patch("superset.sql.execution.celery_task.execute_sql_task")

    result = database.execute_async("SELECT * FROM users")

    query_result = result.get_result()

    # Should return failure when no results backend
    assert query_result.status == QueryStatus.FAILED
    assert query_result.error_message is not None
    assert "Results not available" in query_result.error_message


def test_create_query_record_with_user(
    mocker: MockerFixture, database: Database, app_context: None
) -> None:
    """Test that _create_query_record captures user_id when user exists."""
    from flask import g

    mock_query_execution(mocker, database, return_data=[(1,)], column_names=["id"])

    # Mock a user with get_id
    mock_user = MagicMock()
    mock_user.get_id.return_value = 42

    mocker.patch("superset.sql.execution.executor.has_app_context", return_value=True)
    mocker.patch.object(g, "user", mock_user, create=True)

    mocker.patch.dict(
        current_app.config,
        {
            "SQL_QUERY_MUTATOR": None,
            "SQLLAB_TIMEOUT": 30,
            "SQL_MAX_ROW": None,
            "QUERY_LOGGER": None,
        },
    )

    result = database.execute("SELECT * FROM users")

    assert result.status == QueryStatus.SUCCESS
    mock_user.get_id.assert_called_once()


def test_get_from_cache_returns_cached_result(
    mocker: MockerFixture, database: Database, app_context: None
) -> None:
    """Test that _get_from_cache returns cached result when available."""
    from superset.extensions import cache_manager
    from superset.sql.execution.executor import SQLExecutor

    executor = SQLExecutor(database)

    cached_data = {
        "statements": [
            {
                "original_sql": "SELECT * FROM users",
                "executed_sql": "SELECT * FROM users",
                "data": pd.DataFrame({"id": [1, 2]}),
                "row_count": 2,
                "execution_time_ms": 10.0,
            }
        ],
        "total_execution_time_ms": 10.0,
    }

    mocker.patch.object(cache_manager.data_cache, "get", return_value=cached_data)

    options = QueryOptions()
    result = executor._get_from_cache("SELECT * FROM users", options)

    assert result is not None
    assert result.status == QueryStatus.SUCCESS
    assert result.is_cached is True
    assert sum(s.row_count for s in result.statements) == 2


def test_cached_async_result_get_result_returns_cached(
    mocker: MockerFixture, database: Database, app_context: None
) -> None:
    """Test that cached async result returns the original cached result."""
    from superset_core.queries.types import (
        QueryResult as QueryResultType,
        StatementResult,
    )

    from superset.sql.execution.executor import SQLExecutor

    mocker.patch.dict(
        current_app.config, {"SQL_QUERY_MUTATOR": None, "SQLLAB_TIMEOUT": 30}
    )

    executor = SQLExecutor(database)

    cached_result = QueryResultType(
        status=QueryStatus.SUCCESS,
        statements=[
            StatementResult(
                original_sql="SELECT 1",
                executed_sql="SELECT 1",
                data=pd.DataFrame({"id": [1, 2, 3]}),
                row_count=3,
            )
        ],
    )

    async_result = executor._create_cached_handle(cached_result)

    # Get the result back
    retrieved_result = async_result.get_result()

    # Should return the same cached result
    assert retrieved_result.status == QueryStatus.SUCCESS
    assert sum(s.row_count for s in retrieved_result.statements) == 3
    assert retrieved_result is cached_result


def test_build_statement_blocks_skips_validation_for_unparseable_mutated_sql(
    mocker: MockerFixture, mock_database: MagicMock, app_context: None
) -> None:
    """
    A mutator may emit engine-specific SQL the parser can't handle. The
    empty-statement validation on the joined block is skipped in that case
    instead of blocking execution, leaving the database as the authority
    on validity.
    """
    from superset.exceptions import SupersetParseError
    from superset.sql.execution.executor import build_statement_blocks
    from superset.sql.parse import SQLScript

    mocker.patch.dict(current_app.config, {"MUTATE_AFTER_SPLIT": True})
    mock_database.db_engine_spec.run_multiple_statements_as_one = True
    mocker.patch.object(
        mock_database,
        "mutate_sql_based_on_config",
        side_effect=lambda sql, **kw: f"ENGINE SPECIFIC {sql}",
    )
    parsed_script = SQLScript("SELECT 1; SELECT 2;", engine="bigquery")
    mocker.patch(
        "superset.sql.execution.executor.SQLScript",
        side_effect=SupersetParseError("ENGINE SPECIFIC SQL"),
    )

    _, blocks = build_statement_blocks(
        parsed_script, mock_database.db_engine_spec, mock_database
    )

    assert len(blocks) == 1
    assert blocks[0].count("ENGINE SPECIFIC") == 2


# =============================================================================
# Cache Key Identity Tests
# =============================================================================


def test_generate_cache_key_ignores_user_without_impersonation(
    mocker: MockerFixture, database: Database, app_context: None
) -> None:
    """
    When the connection does not carry per-user identity, the cache key
    must not depend on the calling user -- unrelated users legitimately
    share cache entries for identical queries.
    """
    from superset.sql.execution.executor import SQLExecutor

    executor = SQLExecutor(database)
    options = QueryOptions()

    mocker.patch("superset.sql.execution.executor.utils.get_user_id", return_value=1)
    key_user_1 = executor._generate_cache_key("SELECT * FROM salaries", options)

    mocker.patch("superset.sql.execution.executor.utils.get_user_id", return_value=2)
    key_user_2 = executor._generate_cache_key("SELECT * FROM salaries", options)

    assert key_user_1 is not None
    assert key_user_1 == key_user_2


def test_generate_cache_key_scopes_by_user_when_impersonation_enabled(
    mocker: MockerFixture, database: Database, app_context: None
) -> None:
    """
    Regression: when the database impersonates the connecting user (or
    uses per-user OAuth2), the effective identity the database sees
    differs per user even for byte-identical SQL text. The cache key must
    incorporate that identity so one user's cached rows can never be
    served to another user the database itself would have denied.
    """
    from superset.sql.execution.executor import SQLExecutor

    database.impersonate_user = True
    executor = SQLExecutor(database)
    options = QueryOptions()

    mocker.patch("superset.sql.execution.executor.utils.get_user_id", return_value=1)
    key_analyst_a = executor._generate_cache_key("SELECT * FROM salaries", options)

    mocker.patch("superset.sql.execution.executor.utils.get_user_id", return_value=2)
    key_analyst_b = executor._generate_cache_key("SELECT * FROM salaries", options)

    assert key_analyst_a is not None
    assert key_analyst_b is not None
    assert key_analyst_a != key_analyst_b


def test_generate_cache_key_includes_impersonation_key_when_present(
    mocker: MockerFixture, database: Database, app_context: None
) -> None:
    """
    The executor's result cache mirrors the chart-data cache-key path:
    when CACHE_IMPERSONATION / CACHE_QUERY_BY_USER / per_user_caching
    resolves an impersonation key for the connection, that key must be
    folded into the generated cache key so it can't collide with a key
    generated for a different impersonated identity.
    """
    from superset.sql.execution.executor import SQLExecutor

    executor = SQLExecutor(database)
    options = QueryOptions()

    mocker.patch(
        "superset.utils.cache_keys.add_impersonation_cache_key_if_needed",
        side_effect=lambda db, cache_dict: cache_dict.__setitem__(
            "impersonation_key", "engineer_a"
        ),
    )
    key_engineer_a = executor._generate_cache_key("SELECT * FROM salaries", options)

    mocker.patch(
        "superset.utils.cache_keys.add_impersonation_cache_key_if_needed",
        side_effect=lambda db, cache_dict: cache_dict.__setitem__(
            "impersonation_key", "engineer_b"
        ),
    )
    key_engineer_b = executor._generate_cache_key("SELECT * FROM salaries", options)

    mocker.patch(
        "superset.utils.cache_keys.add_impersonation_cache_key_if_needed",
        side_effect=lambda db, cache_dict: None,
    )
    key_no_impersonation = executor._generate_cache_key(
        "SELECT * FROM salaries", options
    )

    assert key_engineer_a is not None
    assert key_engineer_b is not None
    assert key_no_impersonation is not None
    assert len({key_engineer_a, key_engineer_b, key_no_impersonation}) == 3


def test_generate_cache_key_none_when_identity_unknown(
    mocker: MockerFixture, database: Database, app_context: None
) -> None:
    """
    If the database carries per-user identity but the effective user
    cannot be determined (e.g. no request context), the query must be
    treated as uncacheable rather than risk a shared cache entry.
    """
    from superset.sql.execution.executor import SQLExecutor

    database.impersonate_user = True
    executor = SQLExecutor(database)
    options = QueryOptions()

    mocker.patch("superset.sql.execution.executor.utils.get_user_id", return_value=None)

    assert executor._generate_cache_key("SELECT * FROM salaries", options) is None


def test_get_from_cache_skips_when_identity_unknown(
    mocker: MockerFixture, database: Database, app_context: None
) -> None:
    """
    ``_get_from_cache`` must not read from the cache backend at all when
    ``_generate_cache_key`` reports the query as uncacheable.
    """
    from superset.extensions import cache_manager
    from superset.sql.execution.executor import SQLExecutor

    database.impersonate_user = True
    executor = SQLExecutor(database)
    mocker.patch("superset.sql.execution.executor.utils.get_user_id", return_value=None)
    mock_cache_get = mocker.patch.object(cache_manager.data_cache, "get")

    result = executor._get_from_cache("SELECT * FROM salaries", QueryOptions())

    assert result is None
    mock_cache_get.assert_not_called()


def test_store_in_cache_skips_when_identity_unknown(
    mocker: MockerFixture, database: Database, app_context: None
) -> None:
    """
    ``_store_in_cache`` must not write to the cache backend at all when
    ``_generate_cache_key`` reports the query as uncacheable.
    """
    from superset_core.queries.types import (
        QueryResult as QueryResultType,
        StatementResult,
    )

    from superset.extensions import cache_manager
    from superset.sql.execution.executor import SQLExecutor

    database.impersonate_user = True
    executor = SQLExecutor(database)
    mocker.patch("superset.sql.execution.executor.utils.get_user_id", return_value=None)
    mock_cache_set = mocker.patch.object(cache_manager.data_cache, "set")

    result = QueryResultType(
        status=QueryStatus.SUCCESS,
        statements=[
            StatementResult(
                original_sql="SELECT * FROM salaries",
                executed_sql="SELECT * FROM salaries",
                data=pd.DataFrame({"salary": [1]}),
                row_count=1,
            )
        ],
    )

    executor._store_in_cache(result, "SELECT * FROM salaries", QueryOptions())

    mock_cache_set.assert_not_called()