apexbase 1.17.0

High-performance HTAP embedded database with Rust core
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
"""
Comprehensive test suite for ApexBase SQL Execute Operations and SqlResult

This module tests:
- SQL execute operations with various SELECT statements
- SqlResult functionality and conversions
- SQL syntax support (ORDER BY, LIMIT, DISTINCT, aggregates, GROUP BY)
- Edge cases and error handling
- Performance considerations
- Complex SQL queries
"""

import pytest
import tempfile
import time
import re
import shutil
from pathlib import Path
import sys
import os
import numpy as np

# Add the apexbase python module to path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'apexbase', 'python'))

try:
    from apexbase import ApexClient, ResultView, ARROW_AVAILABLE, POLARS_AVAILABLE
except ImportError as e:
    pytest.skip(f"ApexBase not available: {e}", allow_module_level=True)

# Optional imports
try:
    import pandas as pd
    PANDAS_AVAILABLE = True
except ImportError:
    PANDAS_AVAILABLE = False

try:
    import polars as pl
    POLARS_DF_AVAILABLE = True
except ImportError:
    POLARS_DF_AVAILABLE = False

try:
    import pyarrow as pa
    PYARROW_AVAILABLE = True
except ImportError:
    PYARROW_AVAILABLE = False


def _execute_or_xfail(client: ApexClient, sql: str):
    return client.execute(sql)


class TestBasicSQLExecute:
    """Test basic SQL execute operations"""
    
    def test_execute_basic_select(self):
        """Test basic SELECT statement"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")
            
            # Store test data
            test_data = [
                {"name": "Alice", "age": 25, "city": "NYC"},
                {"name": "Bob", "age": 30, "city": "LA"},
                {"name": "Charlie", "age": 35, "city": "Chicago"},
            ]
            client.store(test_data)
            
            # Execute basic SELECT
            result = client.execute("SELECT * FROM default")
            
            assert isinstance(result, ResultView)
            assert len(result) == 3
            assert "name" in result.columns
            assert "age" in result.columns
            assert "city" in result.columns
            assert "_id" not in result.columns  # _id should be hidden
            
            client.close()

    def test_execute_between_without_limit_returns_all_matches(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")

            client.store(
                {
                    "age": list(range(200)),
                    "name": [f"user_{i}" for i in range(200)],
                }
            )
            client.flush()

            result = client.execute(
                "SELECT age FROM default WHERE age BETWEEN 25 AND 150"
            ).to_dict()

            assert len(result) == 126
            assert result[0]["age"] == 25
            assert result[-1]["age"] == 150

            client.close()

    def test_execute_cast_expression(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")

            client.store([{"s": "123", "f": "1.25", "b": "true", "n": 7}])
            client.flush()

            res = client.execute(
                """
                SELECT
                  CAST('123' AS INT) AS i1,
                  CAST(s AS BIGINT) AS i2,
                  CAST(f AS DOUBLE) AS d1,
                  CAST(n AS VARCHAR) AS s1,
                  CAST(b AS BOOLEAN) AS bo
                FROM default
                """.strip()
            )
            row = res.first()
            assert row["i1"] == 123
            assert row["i2"] == 123
            assert row["d1"] == pytest.approx(1.25)
            assert row["s1"] == "7"
            assert row["bo"] is True

            # NULL propagation
            r2 = client.execute("SELECT CAST(NULL AS INT) AS x FROM default").first()
            assert r2["x"] is None

            # Invalid cast should error
            with pytest.raises(Exception):
                client.execute("SELECT CAST('abc' AS INT) AS x FROM default").to_dict()

            client.close()

    def test_where_multi_column_arithmetic_predicate(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")

            client.store(
                [
                    {"a": 3, "b": 7},
                    {"a": 6, "b": 5},
                    {"a": 1, "b": 2},
                    {"a": 10, "b": 0},
                ]
            )
            client.flush()

            res = client.execute(
                "SELECT a, b FROM default WHERE a + b > 10 ORDER BY a ASC"
            )
            out = res.to_dict()
            assert out == [{"a": 6, "b": 5}]

            client.close()

    def test_where_multi_column_arithmetic_predicate_with_limit_offset(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")

            client.store(
                [
                    {"a": 9, "b": 3},
                    {"a": 8, "b": 4},
                    {"a": 7, "b": 4},
                    {"a": 6, "b": 6},
                    {"a": 5, "b": 6},
                ]
            )
            client.flush()

            res = client.execute(
                "SELECT a, b FROM default WHERE a + b > 10 ORDER BY a DESC LIMIT 2 OFFSET 1"
            )
            out = res.to_dict()
            assert out == [{"a": 8, "b": 4}, {"a": 7, "b": 4}]

            client.close()

    def test_execute_persistent_view_create_select_drop(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")

            client.store([{"a": 1}, {"a": 2}])
            client.flush()

            # View should persist after the CREATE statement and be queryable separately.
            res = client.execute(
                """
                CREATE VIEW v AS SELECT a FROM default WHERE a >= 2;
                SELECT * FROM v;
                """.strip()
            )
            out = res.to_dict()
            assert out == [{"a": 2}]

            out2 = client.execute("SELECT * FROM v").to_dict()
            assert out2 == [{"a": 2}]

            client.execute("DROP VIEW v")
            with pytest.raises(Exception):
                client.execute("SELECT * FROM v").to_dict()

            client.close()

    def test_execute_temporary_view_name_conflict_with_table(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)

            client.create_table("t")
            client.store([{"x": 1}])
            client.flush()

            with pytest.raises(Exception):
                client.execute("CREATE VIEW t AS SELECT 1 AS x")

            client.close()

    def test_execute_string_scalar_functions(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")

            client.store([{"s": "  Abc-XYZ  ", "n": 2}])
            client.flush()

            res = client.execute(
                """
                SELECT
                  LEN('你好') AS l_unicode,
                  MID('abcdef', 2, 3) AS mid1,
                  MID('abcdef', 3) AS mid2,
                  REPLACE('a-b-c', '-', '_') AS rep,
                  TRIM('  hi  ') AS tr,
                  UPPER('aBc') AS up,
                  LOWER('aBc') AS lo,
                  UCASE('aBc') AS uca,
                  LCASE('aBc') AS lca
                FROM default
                """.strip()
            )
            row = res.first()

            assert row["l_unicode"] == 2
            assert row["mid1"] == "bcd"
            assert row["mid2"] == "cdef"
            assert row["rep"] == "a_b_c"
            assert row["tr"] == "hi"
            assert row["up"] == "ABC"
            assert row["lo"] == "abc"
            assert row["uca"] == "ABC"
            assert row["lca"] == "abc"

            res2 = client.execute(
                """
                SELECT
                  UCASE(NULL) AS u_null,
                  LCASE(NULL) AS l_null
                FROM default
                """.strip()
            )
            row2 = res2.first()
            assert row2["u_null"] is None
            assert row2["l_null"] is None

            # UCASE/LCASE: only allow string literal or column name
            with pytest.raises(Exception):
                client.execute("SELECT UCASE(1) AS x FROM default").to_dict()

            with pytest.raises(Exception):
                client.execute("SELECT LCASE(1) AS x FROM default").to_dict()

            # Column exists but non-string values should error
            with pytest.raises(Exception):
                client.execute("SELECT UCASE(n) AS x FROM default").to_dict()

            # Nested expression is supported
            r3 = client.execute("SELECT UCASE(LOWER('a')) AS x FROM default").first()
            assert r3["x"] == "A"

            client.close()

    def test_execute_scalar_standard_functions(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")

            client.store([{"v": 1}])
            client.flush()

            res = client.execute(
                """
                SELECT
                  ROUND(1.2345, 2) AS r2,
                  ROUND(1.6) AS r0,
                  SQRT(9) AS s,
                  CONCAT('a', 'b', 'c') AS c,
                  COALESCE(NULL, 'x', 'y') AS co,
                  IFNULL(NULL, 7) AS ifn,
                  NVL(NULL, 'z') AS nv,
                  ISNULL(NULL, 'k') AS isn
                FROM default
                """.strip()
            )
            row = res.first()

            assert row["r2"] == pytest.approx(1.23)
            assert row["r0"] == pytest.approx(2.0)
            assert row["s"] == pytest.approx(3.0)
            assert row["c"] == "abc"
            assert row["co"] == "x"
            assert row["ifn"] == 7
            assert row["nv"] == "z"
            assert row["isn"] == "k"

            # NOW(): returns formatted datetime string, stable within one execute
            now_res = client.execute("SELECT NOW() AS t FROM default")
            t = now_res.first()["t"]
            assert isinstance(t, str)
            assert re.match(r"^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$", t)

            now2 = client.execute("SELECT NOW() AS a, NOW() AS b FROM default").first()
            assert now2["a"] == now2["b"]

            client.close()

    def test_execute_rand_function(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")

            rows = [{"v": i} for i in range(100)]
            client.store(rows)
            client.flush()

            result = client.execute("SELECT rand() AS r FROM default")
            out = result.to_dict()
            assert len(out) == 100
            for row in out[:10]:
                assert isinstance(row["r"], float)
                assert 0.0 <= row["r"] < 1.0

            # Non-deterministic: expect not all values identical.
            rs = [row["r"] for row in out]
            assert len(set(rs)) > 1

            client.close()

    def test_execute_join_group_by_agg_order_alias_flexible(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)

            client.create_table("users")
            client.store([
                {"user_id": 1, "name": "Alice", "tier": "pro"},
                {"user_id": 2, "name": "Bob", "tier": "free"},
                {"user_id": 3, "name": "Charlie", "tier": "pro"},
            ])
            client.flush()

            client.create_table("orders")
            client.store([
                {"order_id": 10, "user_id": 1, "amount": 120},
                {"order_id": 11, "user_id": 1, "amount": 80},
                {"order_id": 12, "user_id": 2, "amount": 30},
                {"order_id": 13, "user_id": 3, "amount": 200},
            ])
            client.flush()

            # Select order/aliases differ from perf case; should still be correct.
            result = _execute_or_xfail(
                client,
                """
                SELECT SUM(o.amount) AS s, u.tier AS t, COUNT(*) AS c
                FROM users u
                JOIN orders o ON u.user_id = o.user_id
                WHERE o.amount >= 50
                GROUP BY u.tier
                ORDER BY s DESC
                """.strip(),
            )
            rows = result.to_dict()
            assert [r["t"] for r in rows] == ["pro"]
            assert rows[0]["c"] == 3
            assert rows[0]["s"] == 400

            client.close()

    def test_execute_join_group_by_count_col(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)

            client.create_table("users")
            client.store([
                {"user_id": 1, "tier": "pro"},
                {"user_id": 2, "tier": "free"},
            ])
            client.flush()

            client.create_table("orders")
            client.store([
                {"order_id": 10, "user_id": 1, "amount": 120},
                {"order_id": 11, "user_id": 1, "amount": None},
                {"order_id": 12, "user_id": 2, "amount": 80},
            ])
            client.flush()

            result = _execute_or_xfail(
                client,
                """
                SELECT u.tier, COUNT(o.amount) AS cnt
                FROM users u
                JOIN orders o ON u.user_id = o.user_id
                GROUP BY u.tier
                ORDER BY u.tier
                """.strip(),
            )
            rows = result.to_dict()
            assert [(r["tier"], r["cnt"]) for r in rows] == [("free", 1), ("pro", 1)]

            client.close()

    def test_execute_join_group_by_min_max_avg_with_and_where(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)

            client.create_table("users")
            client.store([
                {"user_id": 1, "tier": "pro"},
                {"user_id": 2, "tier": "free"},
                {"user_id": 3, "tier": "pro"},
            ])
            client.flush()

            client.create_table("orders")
            client.store([
                {"order_id": 10, "user_id": 1, "amount": 120},
                {"order_id": 11, "user_id": 1, "amount": 80},
                {"order_id": 12, "user_id": 2, "amount": 30},
                {"order_id": 13, "user_id": 3, "amount": 200},
            ])
            client.flush()

            # AND predicates split across both tables.
            result = _execute_or_xfail(
                client,
                """
                SELECT u.tier, MIN(o.amount) AS mi, MAX(o.amount) AS ma, AVG(o.amount) AS av
                FROM users u
                JOIN orders o ON u.user_id = o.user_id
                WHERE u.tier = 'pro' AND o.amount >= 80
                GROUP BY u.tier
                """.strip(),
            )
            rows = result.to_dict()
            assert len(rows) == 1
            assert rows[0]["tier"] == "pro"
            assert rows[0]["mi"] == 80
            assert rows[0]["ma"] == 200
            assert rows[0]["av"] == pytest.approx((120 + 80 + 200) / 3)

            client.close()

    def test_execute_aggregate_implicit_alias_keyword(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")

            rows = [{"v": i} for i in range(10)]
            client.store(rows)
            client.flush()

            result = client.execute(
                "select min(_id) min_id, max(_id) max_id, count(1) count from default"
            )
            rows = result.to_dict()
            assert isinstance(rows, list)
            assert len(rows) == 1
            assert rows[0]["min_id"] == 1
            assert rows[0]["max_id"] == 10
            assert rows[0]["count"] == 10

            client.close()

    def test_execute_aggregate_implicit_alias(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")

            rows = [{"v": i} for i in range(10)]
            client.store(rows)
            client.flush()

            result = client.execute(
                "select min(_id) min_id, max(_id) as max_id, count(1) as count from default"
            )
            rows = result.to_dict()
            assert isinstance(rows, list)
            assert len(rows) == 1
            assert rows[0]["min_id"] == 1
            assert rows[0]["max_id"] == 10
            assert rows[0]["count"] == 10

            client.close()

    def test_execute_min_max_count_constant_on_internal_id(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")

            rows = [{"v": i} for i in range(100)]
            client.store(rows)
            client.flush()

            result = client.execute("select min(_id), max(_id), count(1) from default")
            rows = result.to_dict()
            assert isinstance(rows, list)
            assert len(rows) == 1
            assert rows[0]["MIN(_id)"] == 1
            assert rows[0]["MAX(_id)"] == 100
            assert rows[0]["COUNT(1)"] == 100

            client.close()

    def test_execute_count_constant(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")

            rows = [{"v": i} for i in range(10)]
            client.store(rows)
            client.flush()

            result = client.execute("select min(_id), max(_id), count(1) from default")
            rows = result.to_dict()
            assert isinstance(rows, list)
            assert len(rows) == 1
            assert rows[0]["MIN(_id)"] == 1
            assert rows[0]["MAX(_id)"] == 10
            assert rows[0]["COUNT(1)"] == 10

            client.close()

    def test_execute_min_max_count_on_internal_id(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")

            rows = [{"v": i} for i in range(100)]
            client.store(rows)
            client.flush()

            result = client.execute("select min(_id), max(_id), count(*) from default")
            rows = result.to_dict()
            assert isinstance(rows, list)
            assert len(rows) == 1
            assert rows[0]["MIN(_id)"] == 1
            assert rows[0]["MAX(_id)"] == 100
            assert rows[0]["COUNT(*)"] == 100

            client.close()

    def test_execute_select_star_plus_id_arrow_fast_path_column_order(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            if not (ARROW_AVAILABLE and PYARROW_AVAILABLE):
                pytest.skip("Arrow/PyArrow not available")

            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")

            # Trigger large-result Arrow paths (threshold is > 10_000)
            rows = [{"name": f"u{i}", "age": i} for i in range(12000)]
            client.store(rows)
            client.flush()

            # Keep user-specified order: '*' then '_id'
            result = client.execute("SELECT *, _id FROM default")
            assert len(result) == 12000
            assert "_id" in result.columns
            assert result.columns[-1] == "_id"

            # Keep user-specified order: '_id' then '*'
            result2 = client.execute("SELECT _id, * FROM default")
            assert len(result2) == 12000
            assert "_id" in result2.columns
            assert result2.columns[0] == "_id"

            client.close()

    def test_execute_select_qualified_id_column(self):
        """Test SELECT with qualified internal id column (e.g., default._id)"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")

            client.store([
                {"name": "Alice", "age": 25},
                {"name": "Bob", "age": 30},
            ])

            result = client.execute("SELECT default._id, name FROM default ORDER BY default._id")
            assert "_id" in result.columns
            rows = result.to_dict()
            assert rows[0]["_id"] == 1
            assert rows[1]["_id"] == 2

            client.close()

    def test_execute_select_quoted_id_column(self):
        """Test SELECT with quoted internal id column (\"_id\")"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")

            client.store([
                {"name": "Alice", "age": 25},
                {"name": "Bob", "age": 30},
            ])

            result = client.execute('SELECT "_id", name FROM default ORDER BY "_id"')
            assert "_id" in result.columns
            rows = result.to_dict()
            assert rows[0]["_id"] == 1
            assert rows[1]["_id"] == 2

            client.close()

    def test_execute_select_star_plus_id_column(self):
        """Test SELECT *, _id should explicitly expose _id"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")

            client.store([
                {"name": "Alice", "age": 25},
                {"name": "Bob", "age": 30},
            ])

            result = client.execute("SELECT *, _id FROM default ORDER BY _id")
            assert "_id" in result.columns
            # _id should appear at the user-specified position (after '*')
            assert result.columns[-1] == "_id"
            rows = result.to_dict()
            assert rows[0]["_id"] == 1
            assert rows[1]["_id"] == 2

            client.close()

    def test_execute_select_explicit_id_column(self):
        """Test SELECT explicitly returning internal _id column"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")

            client.store([
                {"name": "Alice", "age": 25},
                {"name": "Bob", "age": 30},
            ])

            result = client.execute("SELECT _id, name FROM default ORDER BY _id")

            assert "_id" in result.columns
            rows = result.to_dict()
            assert isinstance(rows, list)
            assert len(rows) == 2
            assert "_id" in rows[0]
            assert rows[0]["_id"] == 1
            assert rows[1]["_id"] == 2

            client.close()

    def test_execute_projected_point_lookup_respects_projection(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")

            client.store([
                {"name": "Alice", "age": 25, "city": "NYC"},
                {"name": "Bob", "age": 30, "city": "LA"},
            ])

            result = client.execute("SELECT name FROM default WHERE _id = 1")
            assert result.columns == ["name"]
            rows = result.to_dict()
            assert rows == [{"name": "Alice"}]

            client.close()

    def test_execute_projected_id_in_lookup_respects_projection(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")

            client.store([
                {"name": "Alice", "age": 25, "city": "NYC"},
                {"name": "Bob", "age": 30, "city": "LA"},
                {"name": "Charlie", "age": 35, "city": "Chicago"},
            ])

            result = client.execute("SELECT name FROM default WHERE _id IN (3, 1, 3, 2)")
            assert result.columns == ["name"]
            rows = result.to_dict()
            assert rows == [{"name": "Alice"}, {"name": "Bob"}, {"name": "Charlie"}]

            client.close()

    def test_execute_id_in_lookup_deduplicates_sql_results(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")

            client.store([
                {"name": "Alice", "age": 25},
                {"name": "Bob", "age": 30},
                {"name": "Charlie", "age": 35},
            ])

            result = client.execute("SELECT * FROM default WHERE _id IN (3, 1, 3, 2)")
            ids = result.get_ids(return_list=True)
            assert len(result) == 3
            assert ids == [1, 2, 3]
            assert [row["name"] for row in result.to_dict()] == ["Alice", "Bob", "Charlie"]

            client.close()

    def test_execute_id_in_lookup_can_show_internal_ids(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")

            client.store([
                {"name": "Alice", "age": 25},
                {"name": "Bob", "age": 30},
                {"name": "Charlie", "age": 35},
            ])

            result = client.execute(
                "SELECT * FROM default WHERE _id IN (3, 1, 3, 2)",
                show_internal_id=True,
            )
            rows = result.to_dict()
            assert result.columns[0] == "_id"
            assert [row["_id"] for row in rows] == [1, 2, 3]
            assert [row["name"] for row in rows] == ["Alice", "Bob", "Charlie"]

            client.close()

    def test_execute_projected_string_equality_filter_respects_projection(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")

            client.store([
                {"name": "Alice", "age": 25, "city": "NYC"},
                {"name": "Bob", "age": 30, "city": "LA"},
                {"name": "Charlie", "age": 35, "city": "NYC"},
            ])

            result = client.execute("SELECT name FROM default WHERE city = 'NYC'")
            assert result.columns == ["name"]
            assert result.to_dict() == [{"name": "Alice"}, {"name": "Charlie"}]

            client.close()

    def test_execute_arrow_dictionary_string_schema_match(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            if not (ARROW_AVAILABLE and PYARROW_AVAILABLE and PANDAS_AVAILABLE):
                pytest.skip("Arrow/PyArrow/Pandas not available")

            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")

            repeated = [{"title": "Python编程指南", "content": "same", "number": i % 10} for i in range(6000)]
            client.store(repeated)
            client.flush()

            df = client.execute("select * from default where title like 'Python%'").to_pandas()
            assert len(df) == 6000
            assert "title" in df.columns
            assert "content" in df.columns
            assert "number" in df.columns
            assert df["title"].iloc[0].startswith("Python")

            # Regression: ensure schema matches Dictionary-encoded string arrays on Arrow fast path
            # when explicitly requesting _id in addition to '*'.
            df2 = client.execute("select *, _id from default").to_pandas()
            assert len(df2) == 6000
            assert "_id" in df2.columns

            client.close()

    def test_execute_where_not_like_and_like(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")

            rows = [
                {"title": "Python编程指南第1章", "content": "a"},
                {"title": "Python编程指南第2章", "content": "b"},
                {"title": "Python入门", "content": "c"},
                {"title": "Rust编程指南第1章", "content": "d"},
            ]
            client.store(rows)
            client.flush()

            result = client.execute(
                "select * from default where title like 'Python%' and title not like '%编程指南第1%'")
            titles = [r["title"] for r in result.to_dict()]
            assert "Python编程指南第1章" not in titles
            assert "Python编程指南第2章" in titles
            assert "Python入门" in titles
            assert "Rust编程指南第1章" not in titles

            client.close()
    
    def test_execute_select_specific_columns(self):
        """Test SELECT with specific columns"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")
            
            # Store test data
            test_data = [
                {"name": "Alice", "age": 25, "city": "NYC", "salary": 50000},
                {"name": "Bob", "age": 30, "city": "LA", "salary": 60000},
            ]
            client.store(test_data)
            
            # Execute SELECT with specific columns
            result = client.execute("SELECT name, age FROM default")
            
            assert len(result) == 2
            assert result.columns == ["name", "age"]
            assert "city" not in result.columns
            assert "salary" not in result.columns
            
            # Check data
            rows = list(result)
            names = [row["name"] for row in rows]
            ages = [row["age"] for row in rows]
            assert "Alice" in names
            assert "Bob" in names
            assert 25 in ages
            assert 30 in ages
            
            client.close()
    
    def test_execute_select_with_where(self):
        """Test SELECT with WHERE clause"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")
            
            # Store test data
            test_data = [
                {"name": "Alice", "age": 25, "city": "NYC", "active": True},
                {"name": "Bob", "age": 30, "city": "LA", "active": False},
                {"name": "Charlie", "age": 35, "city": "Chicago", "active": True},
            ]
            client.store(test_data)
            
            # Execute SELECT with WHERE
            result = client.execute("SELECT name, age FROM default WHERE age > 25")
            
            assert len(result) == 2
            rows = list(result)
            assert len(rows) == 2
            assert isinstance(rows[0], dict)
            assert "name" in rows[0]
            assert "age" in rows[0]
            names = [row["name"] for row in rows]
            assert "Bob" in names
            assert "Charlie" in names
            assert "Alice" not in names
            
            client.close()
    
    def test_execute_select_with_order_by(self):
        """Test SELECT with ORDER BY clause"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")
            
            # Store test data
            test_data = [
                {"name": "Charlie", "age": 35},
                {"name": "Alice", "age": 25},
                {"name": "Bob", "age": 30},
            ]
            client.store(test_data)
            
            # Execute SELECT with ORDER BY ASC
            result = client.execute("SELECT name, age FROM default ORDER BY age ASC")
            
            assert len(result) == 3
            rows = list(result)
            ages = [row["age"] for row in rows]
            assert ages == [25, 30, 35]  # Sorted ascending
            
            # Execute SELECT with ORDER BY DESC
            result = client.execute("SELECT name, age FROM default ORDER BY age DESC")
            
            rows = list(result)
            ages = [row["age"] for row in rows]
            assert ages == [35, 30, 25]  # Sorted descending
            
            client.close()
    
    def test_execute_select_with_limit(self):
        """Test SELECT with LIMIT clause"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")
            
            # Store test data
            test_data = [{"id": i, "value": f"item_{i}"} for i in range(10)]
            client.store(test_data)
            
            # Execute SELECT with LIMIT
            result = client.execute("SELECT * FROM default LIMIT 5")
            
            assert len(result) == 5
            
            # Execute SELECT with LIMIT and ORDER BY
            result = client.execute("SELECT * FROM default ORDER BY id DESC LIMIT 3")
            
            assert len(result) == 3
            rows = list(result)
            ids = [row["id"] for row in rows]
            assert ids == [9, 8, 7]  # Last 3 IDs in descending order
            
            client.close()

    def test_execute_projected_select_with_limit(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")

            client.store([
                {"name": "Alice", "age": 25, "city": "NYC"},
                {"name": "Bob", "age": 30, "city": "LA"},
                {"name": "Charlie", "age": 35, "city": "Chicago"},
            ])

            result = client.execute("SELECT name, city FROM default LIMIT 2")
            assert result.columns == ["name", "city"]
            assert result.to_dict() == [
                {"name": "Alice", "city": "NYC"},
                {"name": "Bob", "city": "LA"},
            ]

            client.close()
    
    def test_execute_select_with_limit_offset(self):
        """Test SELECT with LIMIT and OFFSET"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")
            
            # Store test data
            test_data = [{"id": i, "value": f"item_{i}"} for i in range(10)]
            client.store(test_data)
            
            # Execute SELECT with LIMIT and OFFSET
            result = client.execute("SELECT * FROM default LIMIT 3 OFFSET 5")
            
            assert len(result) == 3
            rows = list(result)
            ids = [row["id"] for row in rows]
            assert ids == [5, 6, 7]  # IDs 5, 6, 7
            
            client.close()
    
    def test_execute_select_distinct(self):
        """Test SELECT DISTINCT"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")
            
            # Store test data with duplicates
            test_data = [
                {"city": "NYC", "country": "USA"},
                {"city": "LA", "country": "USA"},
                {"city": "NYC", "country": "USA"},
                {"city": "Chicago", "country": "USA"},
                {"city": "Toronto", "country": "Canada"},
                {"city": "Vancouver", "country": "Canada"},
            ]
            client.store(test_data)
            
            # Execute SELECT DISTINCT on single column
            result = client.execute("SELECT DISTINCT city FROM default")
            
            assert len(result) == 5  # NYC, LA, Chicago, Toronto, Vancouver
            cities = [row["city"] for row in result]
            assert "NYC" in cities
            assert "LA" in cities
            assert "Chicago" in cities
            assert "Toronto" in cities
            assert "Vancouver" in cities
            
            # Execute SELECT DISTINCT on multiple columns
            result = client.execute("SELECT DISTINCT city, country FROM default")
            
            assert len(result) == 5  # 5 unique combinations
            
            client.close()


class TestSQLAggregates:
    """Test SQL aggregate functions"""
    
    def test_execute_count_aggregate(self):
        """Test COUNT aggregate function"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")
            
            # Store test data
            test_data = [
                {"name": "Alice", "age": 25, "city": "NYC"},
                {"name": "Bob", "age": 30, "city": "LA"},
                {"name": "Charlie", "age": 35, "city": "NYC"},
            ]
            client.store(test_data)
            
            # Test COUNT(*)
            result = client.execute("SELECT COUNT(*) as total FROM default")
            
            assert len(result) == 1
            assert result.scalar() == 3
            
            # Test COUNT(column)
            result = client.execute("SELECT COUNT(city) as city_count FROM default")
            
            assert len(result) == 1
            assert result.scalar() == 3
            
            # Test COUNT with WHERE
            result = client.execute("SELECT COUNT(*) as nyc_count FROM default WHERE city = 'NYC'")
            
            assert len(result) == 1
            assert result.scalar() == 2

            result = client.execute("SELECT COUNT(city) as nyc_city_count FROM default WHERE city = 'NYC'")

            assert len(result) == 1
            assert result.scalar() == 2
            
            client.close()
    
    def test_execute_sum_aggregate(self):
        """Test SUM aggregate function"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")
            
            # Store test data
            test_data = [
                {"name": "Alice", "salary": 50000},
                {"name": "Bob", "salary": 60000},
                {"name": "Charlie", "salary": 70000},
            ]
            client.store(test_data)
            
            # Test SUM
            result = client.execute("SELECT SUM(salary) as total_salary FROM default")
            
            assert len(result) == 1
            assert result.scalar() == 180000
            
            # Test SUM with WHERE
            result = client.execute("SELECT SUM(salary) as high_salary FROM default WHERE salary > 55000")
            
            assert len(result) == 1
            assert result.scalar() == 130000  # 60000 + 70000
            
            client.close()
    
    def test_execute_avg_aggregate(self):
        """Test AVG aggregate function"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")
            
            # Store test data
            test_data = [
                {"name": "Alice", "age": 25},
                {"name": "Bob", "age": 30},
                {"name": "Charlie", "age": 35},
            ]
            client.store(test_data)
            
            # Test AVG
            result = client.execute("SELECT AVG(age) as avg_age FROM default")
            
            assert len(result) == 1
            avg_age = result.scalar()
            assert abs(avg_age - 30.0) < 0.001  # (25 + 30 + 35) / 3 = 30
            
            client.close()
    
    def test_execute_min_max_aggregates(self):
        """Test MIN and MAX aggregate functions"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")
            
            # Store test data
            test_data = [
                {"name": "Alice", "age": 25, "salary": 50000},
                {"name": "Bob", "age": 30, "salary": 60000},
                {"name": "Charlie", "age": 35, "salary": 70000},
            ]
            client.store(test_data)
            
            # Test MIN
            result = client.execute("SELECT MIN(age) as min_age FROM default")
            
            assert len(result) == 1
            assert result.scalar() == 25
            
            # Test MAX
            result = client.execute("SELECT MAX(salary) as max_salary FROM default")
            
            assert len(result) == 1
            assert result.scalar() == 70000
            
            # Test MIN and MAX together
            result = client.execute("SELECT MIN(age) as min_age, MAX(salary) as max_salary FROM default")
            
            assert len(result) == 1
            row = result.first()
            assert row["min_age"] == 25
            assert row["max_salary"] == 70000
            
            client.close()


class TestSQLGroupBy:
    """Test SQL GROUP BY operations"""
    
    def test_execute_group_by_basic(self):
        """Test basic GROUP BY"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")
            
            # Store test data
            test_data = [
                {"city": "NYC", "salary": 50000},
                {"city": "LA", "salary": 60000},
                {"city": "NYC", "salary": 55000},
            ]
            client.store(test_data)
            
            # Test GROUP BY - behavior may vary
            try:
                result = client.execute("SELECT city, COUNT(*) as count FROM default GROUP BY city")
                # GROUP BY support may be limited
                assert len(result) >= 0
            except Exception as e:
                print(f"GROUP BY basic: {e}")
            
            client.close()
    
    def test_execute_group_by_with_aggregates(self):
        """Test GROUP BY with various aggregates"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")
            
            # Store test data
            test_data = [
                {"dept": "Engineering", "salary": 80000},
                {"dept": "Sales", "salary": 60000},
            ]
            client.store(test_data)
            
            # Test GROUP BY with aggregates - behavior may vary
            try:
                result = client.execute("SELECT COUNT(*) as count FROM default")
                assert len(result) >= 0
            except Exception as e:
                print(f"GROUP BY aggregates: {e}")
            
            client.close()
    
    def test_execute_group_by_with_having(self):
        """Test GROUP BY with HAVING clause"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")
            
            # Store test data
            test_data = [
                {"city": "NYC", "population": 1000000},
                {"city": "NYC", "population": 1100000},
                {"city": "LA", "population": 800000},
            ]
            client.store(test_data)

            # HAVING should filter on aggregated result
            result = client.execute(
                "SELECT city, COUNT(*) AS c FROM default GROUP BY city HAVING COUNT(*) > 1"
            )
            rows = result.to_dict()
            assert isinstance(rows, list)
            # Only NYC has >1 rows
            assert len(rows) == 1
            assert rows[0]["city"] == "NYC"
            assert rows[0]["c"] == 2
            
            client.close()


class TestSQLRealWorldQueries:
    def test_execute_union_and_union_all(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")

            client.store([
                {"k": 1, "city": "NYC"},
                {"k": 2, "city": "NYC"},
                {"k": 3, "city": "LA"},
                {"k": 4, "city": "Chicago"},
            ])
            client.flush()

            result_union = _execute_or_xfail(
                client,
                """
                SELECT city FROM default WHERE city = 'NYC'
                UNION
                SELECT city FROM default WHERE city = 'LA'
                ORDER BY city
                """.strip(),
            )
            rows_union = result_union.to_dict()
            assert [r["city"] for r in rows_union] == ["LA", "NYC"]

            result_union_all = _execute_or_xfail(
                client,
                """
                SELECT city FROM default WHERE city = 'NYC'
                UNION ALL
                SELECT city FROM default WHERE city = 'LA'
                ORDER BY city
                """.strip(),
            )
            rows_union_all = result_union_all.to_dict()
            assert [r["city"] for r in rows_union_all] == ["LA", "NYC", "NYC"]

            client.close()

    def test_execute_multi_table_join_inner(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)

            client.create_table("users")
            client.store([
                {"user_id": 1, "name": "Alice", "tier": "pro"},
                {"user_id": 2, "name": "Bob", "tier": "free"},
                {"user_id": 3, "name": "Charlie", "tier": "pro"},
            ])
            client.flush()

            client.create_table("orders")
            client.store([
                {"order_id": 10, "user_id": 1, "amount": 120},
                {"order_id": 11, "user_id": 1, "amount": 80},
                {"order_id": 12, "user_id": 2, "amount": 30},
            ])
            client.flush()

            result = _execute_or_xfail(
                client,
                """
                SELECT u.name, u.tier, o.order_id, o.amount
                FROM users u
                JOIN orders o ON u.user_id = o.user_id
                WHERE o.amount >= 50
                ORDER BY o.order_id
                """.strip(),
            )
            rows = result.to_dict()
            assert [(r["name"], r["order_id"], r["amount"]) for r in rows] == [
                ("Alice", 10, 120),
                ("Alice", 11, 80),
            ]

            client.close()

    def test_execute_multi_group_by_having(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")

            client.store([
                {"region": "CN", "channel": "online", "amount": 120},
                {"region": "CN", "channel": "online", "amount": 90},
                {"region": "CN", "channel": "store", "amount": 30},
                {"region": "US", "channel": "online", "amount": 200},
                {"region": "US", "channel": "store", "amount": 40},
            ])
            client.flush()

            result = _execute_or_xfail(
                client,
                """
                SELECT region, channel, COUNT(*) AS c, SUM(amount) AS s
                FROM default
                GROUP BY region, channel
                HAVING SUM(amount) >= 150
                ORDER BY region, channel
                """.strip(),
            )
            rows = result.to_dict()
            assert [(r["region"], r["channel"], r["c"], r["s"]) for r in rows] == [
                ("CN", "online", 2, 210),
                ("US", "online", 1, 200),
            ]

            client.close()

    def test_execute_nested_aggregation_second_stage(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")

            client.store([
                {"region": "CN", "amount": 120},
                {"region": "CN", "amount": 90},
                {"region": "CN", "amount": 30},
                {"region": "US", "amount": 200},
                {"region": "US", "amount": 40},
            ])
            client.flush()

            result = _execute_or_xfail(
                client,
                """
                SELECT COUNT(*) AS big_regions
                FROM (
                    SELECT region, SUM(amount) AS total
                    FROM default
                    GROUP BY region
                ) t
                WHERE t.total >= 200
                """.strip(),
            )
            assert result.scalar() == 2

            client.close()

    def test_execute_left_join_preserve_rows(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)

            client.create_table("users")
            client.store([
                {"user_id": 1, "name": "Alice"},
                {"user_id": 2, "name": "Bob"},
                {"user_id": 3, "name": "Charlie"},
            ])
            client.flush()

            client.create_table("orders")
            client.store([
                {"order_id": 10, "user_id": 1, "amount": 120},
                {"order_id": 11, "user_id": 1, "amount": 80},
                {"order_id": 12, "user_id": 2, "amount": 30},
            ])
            client.flush()

            result = _execute_or_xfail(
                client,
                """
                SELECT u.user_id, u.name, o.order_id
                FROM users u
                LEFT JOIN orders o ON u.user_id = o.user_id
                ORDER BY u.user_id, o.order_id
                """.strip(),
            )
            rows = result.to_dict()
            assert [r["user_id"] for r in rows] == [1, 1, 2, 3]
            assert [r["order_id"] for r in rows] == [10, 11, 12, None]

            client.close()

    def test_execute_join_group_by_having_top_customers(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)

            client.create_table("users")
            client.store([
                {"user_id": 1, "name": "Alice", "tier": "pro"},
                {"user_id": 2, "name": "Bob", "tier": "free"},
                {"user_id": 3, "name": "Charlie", "tier": "pro"},
            ])
            client.flush()

            client.create_table("orders")
            client.store([
                {"order_id": 10, "user_id": 1, "amount": 120},
                {"order_id": 11, "user_id": 1, "amount": 80},
                {"order_id": 12, "user_id": 2, "amount": 30},
                {"order_id": 13, "user_id": 3, "amount": 200},
            ])
            client.flush()

            result = _execute_or_xfail(
                client,
                """
                SELECT u.tier, COUNT(DISTINCT u.user_id) AS users, SUM(o.amount) AS revenue
                FROM users u
                JOIN orders o ON u.user_id = o.user_id
                GROUP BY u.tier
                HAVING SUM(o.amount) >= 200
                ORDER BY u.tier
                """.strip(),
            )
            rows = result.to_dict()
            assert len(rows) == 1
            assert rows[0]["tier"] == "pro"
            assert rows[0]["users"] == 2
            assert rows[0]["revenue"] == 400

            client.close()

    def test_execute_join_distinct_dimension_values(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)

            client.create_table("users")
            client.store([
                {"user_id": 1, "name": "Alice", "tier": "pro"},
                {"user_id": 2, "name": "Bob", "tier": "free"},
            ])
            client.flush()

            client.create_table("orders")
            client.store([
                {"order_id": 10, "user_id": 1, "amount": 120},
                {"order_id": 11, "user_id": 1, "amount": 80},
                {"order_id": 12, "user_id": 2, "amount": 30},
            ])
            client.flush()

            result = _execute_or_xfail(
                client,
                """
                SELECT DISTINCT u.tier
                FROM users u
                JOIN orders o ON u.user_id = o.user_id
                ORDER BY u.tier
                """.strip(),
            )
            tiers = [r["tier"] for r in result.to_dict()]
            assert tiers == ["free", "pro"]

            client.close()

    def test_execute_union_with_limit_offset(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")

            client.store([
                {"k": 1, "city": "NYC"},
                {"k": 2, "city": "NYC"},
                {"k": 3, "city": "LA"},
                {"k": 4, "city": "Chicago"},
                {"k": 5, "city": "Seattle"},
            ])
            client.flush()

            result = _execute_or_xfail(
                client,
                """
                SELECT city FROM default WHERE city LIKE 'C%'
                UNION ALL
                SELECT city FROM default WHERE city LIKE 'N%'
                ORDER BY city
                LIMIT 2 OFFSET 1
                """.strip(),
            )
            rows = result.to_dict()
            assert [r["city"] for r in rows] == ["NYC", "NYC"]

            client.close()

    def test_execute_in_and_not_in_subquery(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)

            client.create_table("users")
            client.store([
                {"user_id": 1, "name": "Alice"},
                {"user_id": 2, "name": "Bob"},
                {"user_id": 3, "name": "Charlie"},
            ])
            client.flush()

            client.create_table("orders")
            client.store([
                {"order_id": 10, "user_id": 1, "amount": 120},
                {"order_id": 11, "user_id": 1, "amount": 80},
                {"order_id": 12, "user_id": 2, "amount": 30},
            ])
            client.flush()

            result_in = _execute_or_xfail(
                client,
                """
                SELECT name
                FROM users
                WHERE user_id IN (SELECT user_id FROM orders WHERE amount >= 80)
                ORDER BY name
                """.strip(),
            )
            assert [r["name"] for r in result_in.to_dict()] == ["Alice"]

            result_not_in = _execute_or_xfail(
                client,
                """
                SELECT name
                FROM users
                WHERE user_id NOT IN (SELECT user_id FROM orders)
                ORDER BY name
                """.strip(),
            )
            assert [r["name"] for r in result_not_in.to_dict()] == ["Charlie"]

            client.close()

    def test_execute_exists_subquery(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)

            client.create_table("users")
            client.store([
                {"user_id": 1, "name": "Alice"},
                {"user_id": 2, "name": "Bob"},
                {"user_id": 3, "name": "Charlie"},
            ])
            client.flush()

            client.create_table("orders")
            client.store([
                {"order_id": 10, "user_id": 1, "amount": 120},
                {"order_id": 11, "user_id": 1, "amount": 80},
                {"order_id": 12, "user_id": 2, "amount": 30},
            ])
            client.flush()

            result = _execute_or_xfail(
                client,
                """
                SELECT u.name
                FROM users u
                WHERE EXISTS (
                    SELECT 1 FROM orders o
                    WHERE o.user_id = u.user_id AND o.amount >= 100
                )
                ORDER BY u.name
                """.strip(),
            )
            assert [r["name"] for r in result.to_dict()] == ["Alice"]

            client.close()

    def test_execute_two_stage_aggregation_bucketed(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")

            client.store([
                {"region": "CN", "amount": 120},
                {"region": "CN", "amount": 90},
                {"region": "CN", "amount": 30},
                {"region": "US", "amount": 200},
                {"region": "US", "amount": 40},
                {"region": "EU", "amount": 10},
                {"region": "EU", "amount": 20},
            ])
            client.flush()

            result = _execute_or_xfail(
                client,
                """
                SELECT t.bucket, COUNT(*) AS regions
                FROM (
                    SELECT region,
                           CASE WHEN SUM(amount) >= 200 THEN 'big' ELSE 'small' END AS bucket
                    FROM default
                    GROUP BY region
                ) t
                GROUP BY t.bucket
                ORDER BY t.bucket
                """.strip(),
            )
            rows = result.to_dict()
            assert [(r["bucket"], r["regions"]) for r in rows] == [("big", 2), ("small", 1)]

            client.close()


class TestSQLSubqueriesAdvanced:
    def test_execute_not_exists_correlated(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)

            client.create_table("users")
            client.store(
                [
                    {"user_id": 1, "name": "Alice"},
                    {"user_id": 2, "name": "Bob"},
                    {"user_id": 3, "name": "Charlie"},
                ]
            )
            client.flush()

            client.create_table("orders")
            client.store(
                [
                    {"order_id": 10, "user_id": 1, "amount": 120},
                    {"order_id": 11, "user_id": 1, "amount": 80},
                    {"order_id": 12, "user_id": 2, "amount": 30},
                ]
            )
            client.flush()

            result = _execute_or_xfail(
                client,
                """
                SELECT u.name
                FROM users u
                WHERE NOT EXISTS (
                    SELECT 1 FROM orders o
                    WHERE o.user_id = u.user_id
                )
                ORDER BY u.name
                """.strip(),
            )
            assert [r["name"] for r in result.to_dict()] == ["Charlie"]

            client.close()

    def test_execute_correlated_in_subquery(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)

            client.create_table("users")
            client.store(
                [
                    {"user_id": 1, "name": "Alice"},
                    {"user_id": 2, "name": "Bob"},
                    {"user_id": 3, "name": "Charlie"},
                ]
            )
            client.flush()

            client.create_table("orders")
            client.store(
                [
                    {"order_id": 10, "user_id": 1, "amount": 120},
                    {"order_id": 11, "user_id": 1, "amount": 80},
                    {"order_id": 12, "user_id": 2, "amount": 30},
                ]
            )
            client.flush()

            result = _execute_or_xfail(
                client,
                """
                SELECT u.name
                FROM users u
                WHERE u.user_id IN (
                    SELECT o.user_id
                    FROM orders o
                    WHERE o.user_id = u.user_id AND o.amount >= 100
                )
                ORDER BY u.name
                """.strip(),
            )
            assert [r["name"] for r in result.to_dict()] == ["Alice"]

            client.close()

    def test_execute_scalar_correlated_subquery_in_select_list(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)

            client.create_table("users")
            client.store(
                [
                    {"user_id": 1, "name": "Alice"},
                    {"user_id": 2, "name": "Bob"},
                    {"user_id": 3, "name": "Charlie"},
                ]
            )
            client.flush()

            client.create_table("orders")
            client.store(
                [
                    {"order_id": 10, "user_id": 1, "amount": 120},
                    {"order_id": 11, "user_id": 1, "amount": 80},
                    {"order_id": 12, "user_id": 2, "amount": 30},
                ]
            )
            client.flush()

            result = _execute_or_xfail(
                client,
                """
                SELECT u.name,
                       (SELECT MAX(amount) FROM orders o WHERE o.user_id = u.user_id) AS max_amount
                FROM users u
                ORDER BY u.name
                """.strip(),
            )
            rows = result.to_dict()
            assert [(r["name"], r["max_amount"]) for r in rows] == [
                ("Alice", 120),
                ("Bob", 30),
                ("Charlie", None),
            ]

            client.close()


class TestSqlResultFunctionality:
    """Test ResultView functionality and conversions"""
    
    def test_sql_result_basic_properties(self):
        """Test ResultView basic properties"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")
            
            # Store test data
            test_data = [
                {"name": "Alice", "age": 25},
                {"name": "Bob", "age": 30},
            ]
            client.store(test_data)
            
            result = client.execute("SELECT name, age FROM default")
            
            # Test basic properties
            assert isinstance(result, ResultView)
            assert len(result) >= 0
            # Columns may vary based on implementation
            assert result.columns is not None
            
            client.close()
    
    def test_sql_result_iteration(self):
        """Test ResultView iteration"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")
            
            # Store test data
            test_data = [
                {"name": "Alice", "age": 25},
                {"name": "Bob", "age": 30},
                {"name": "Charlie", "age": 35},
            ]
            client.store(test_data)
            
            result = client.execute("SELECT name, age FROM default ORDER BY age")
            
            # Test iteration
            names = []
            ages = []
            for row in result:
                names.append(row["name"])
                ages.append(row["age"])
            
            assert len(names) == 3
            assert names == ["Alice", "Bob", "Charlie"]
            assert ages == [25, 30, 35]
            
            client.close()
    
    def test_sql_result_to_dicts(self):
        """Test ResultView.to_dict() method"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")
            
            # Store test data
            test_data = [
                {"name": "Alice", "age": 25},
                {"name": "Bob", "age": 30},
            ]
            client.store(test_data)
            
            result = client.execute("SELECT name, age FROM default")
            dict_list = result.to_dict()
            
            assert isinstance(dict_list, list)
            assert len(dict_list) == 2
            assert isinstance(dict_list[0], dict)
            assert dict_list[0]["name"] == "Alice"
            assert dict_list[1]["name"] == "Bob"
            
            client.close()

    def test_sql_result_tolist(self):
        """Test ResultView.tolist() method via execute()"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")

            test_data = [
                {"name": "Alice", "age": 25},
                {"name": "Bob", "age": 30},
                {"name": "Charlie", "age": 35},
            ]
            client.store(test_data)

            result = client.execute("SELECT name, age FROM default ORDER BY age")
            rows = result.tolist()

            # Basic type and length checks
            assert isinstance(rows, list)
            assert len(rows) == 3
            assert isinstance(rows[0], dict)

            # Values and order are correct
            assert rows[0]["name"] == "Alice"
            assert rows[0]["age"] == 25
            assert rows[1]["name"] == "Bob"
            assert rows[1]["age"] == 30
            assert rows[2]["name"] == "Charlie"
            assert rows[2]["age"] == 35

            # Internal _id must be hidden
            assert "_id" not in rows[0]

            # tolist() and to_dict() must return equivalent data
            assert rows == result.to_dict()

            client.close()

    def test_sql_result_tolist_empty(self):
        """Test ResultView.tolist() on empty result via execute()"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")

            result = client.execute("SELECT name, age FROM default WHERE age > 999")
            rows = result.tolist()

            assert isinstance(rows, list)
            assert len(rows) == 0

            client.close()

    @pytest.mark.skipif(not PANDAS_AVAILABLE, reason="Pandas not available")
    def test_sql_result_to_pandas(self):
        """Test ResultView.to_pandas() method"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")
            
            # Store test data
            test_data = [
                {"name": "Alice", "age": 25, "city": "NYC"},
                {"name": "Bob", "age": 30, "city": "LA"},
            ]
            client.store(test_data)
            
            result = client.execute("SELECT name, age, city FROM default")
            df = result.to_pandas()
            
            assert isinstance(df, pd.DataFrame)
            assert len(df) == 2
            assert "name" in df.columns
            assert "age" in df.columns
            assert "city" in df.columns
            assert "_id" not in df.columns  # _id should be hidden
            
            client.close()
    
    @pytest.mark.skipif(not POLARS_DF_AVAILABLE, reason="Polars not available")
    def test_sql_result_to_polars(self):
        """Test ResultView.to_polars() method"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")
            
            # Store test data
            test_data = [
                {"name": "Alice", "age": 25},
                {"name": "Bob", "age": 30},
            ]
            client.store(test_data)
            
            result = client.execute("SELECT name, age FROM default")
            df = result.to_polars()
            
            assert isinstance(df, pl.DataFrame)
            assert len(df) == 2
            assert "name" in df.columns
            assert "age" in df.columns
            assert "_id" not in df.columns  # _id should be hidden
            
            client.close()
    
    def test_sql_result_get_ids(self):
        """Test ResultView.get_ids() method"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")
            
            # Store test data
            test_data = [
                {"name": "Alice", "age": 25},
                {"name": "Bob", "age": 30},
                {"name": "Charlie", "age": 35},
            ]
            client.store(test_data)
            
            result = client.execute("SELECT name, age FROM default")
            
            # Test get_ids with numpy array (default)
            ids = result.get_ids()
            assert isinstance(ids, np.ndarray)
            assert len(ids) == 3
            assert all(isinstance(id, (int, np.integer)) for id in ids)
            
            # Test get_ids with list
            ids_list = result.get_ids(return_list=True)
            assert isinstance(ids_list, list)
            assert len(ids_list) == 3
            assert all(isinstance(id, int) for id in ids_list)
            
            client.close()
    
    def test_sql_result_scalar(self):
        """Test ResultView.scalar() method"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")
            
            # Store test data
            test_data = [
                {"name": "Alice", "age": 25},
                {"name": "Bob", "age": 30},
            ]
            client.store(test_data)
            
            # Test scalar with aggregate
            result = client.execute("SELECT COUNT(*) as count FROM default")
            count = result.scalar()
            assert count == 2
            
            # Test scalar with single value
            result = client.execute("SELECT age FROM default WHERE name = 'Alice'")
            age = result.scalar()
            assert age == 25
            
            # Test scalar with no results
            result = client.execute("SELECT age FROM default WHERE name = 'Nonexistent'")
            value = result.scalar()
            assert value is None
            
            client.close()
    
    def test_sql_result_first(self):
        """Test ResultView.first() method"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")
            
            # Store test data
            test_data = [
                {"name": "Alice", "age": 25},
                {"name": "Bob", "age": 30},
                {"name": "Charlie", "age": 35},
            ]
            client.store(test_data)
            
            result = client.execute("SELECT name, age FROM default ORDER BY age")
            
            # Test first
            first_row = result.first()
            assert isinstance(first_row, dict)
            assert first_row["name"] == "Alice"
            assert first_row["age"] == 25
            
            # Test first with no results
            empty_result = client.execute("SELECT name, age FROM default WHERE age > 100")
            first_row = empty_result.first()
            assert first_row is None
            
            client.close()
    
    def test_sql_result_repr(self):
        """Test ResultView.__repr__ method"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")
            
            # Store test data
            test_data = [
                {"name": "Alice", "age": 25},
                {"name": "Bob", "age": 30},
            ]
            client.store(test_data)
            
            result = client.execute("SELECT name, age FROM default")
            repr_str = repr(result)
            
            # Basic repr check - format may vary
            assert "ResultView" in repr_str
            
            client.close()


class TestSQLEdgeCases:
    """Test edge cases and error handling for SQL operations"""
    
    def test_execute_invalid_sql(self):
        """Test invalid SQL syntax"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")
            
            # Store test data
            test_data = [{"name": "Alice", "age": 25}]
            client.store(test_data)
            
            # Test invalid SQL
            with pytest.raises(Exception):  # Should raise some kind of SQL error
                client.execute("INVALID SQL SYNTAX")
            
            with pytest.raises(Exception):
                client.execute("SELECT * FROM nonexistent_table")
            
            client.close()
    
    def test_execute_nonexistent_columns(self):
        """Test SELECT with nonexistent columns"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")
            
            # Store test data
            test_data = [{"name": "Alice", "age": 25}]
            client.store(test_data)
            
            # Test with nonexistent column
            try:
                result = client.execute("SELECT nonexistent_column FROM default")
                # If no exception, should return empty results or handle gracefully
                assert len(result) == 0 or result.columns == []
            except Exception as e:
                # Exception is also acceptable behavior
                print(f"Nonexistent column handled: {e}")
            
            client.close()
    
    def test_execute_on_closed_client(self):
        """Test execute operations on closed client"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")
            client.close()
            
            with pytest.raises(RuntimeError, match="connection has been closed"):
                client.execute("SELECT * FROM default")
            
            with pytest.raises(RuntimeError, match="connection has been closed"):
                client.execute("SELECT COUNT(*) FROM default")
    
    def test_execute_empty_database(self):
        """Test execute operations on empty database"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")
            
            # Test SELECT on empty database
            result = client.execute("SELECT * FROM default")
            assert len(result) == 0
            
            # Test aggregate on empty database
            result = client.execute("SELECT COUNT(*) as count FROM default")
            assert result.scalar() == 0
            
            client.close()
    
    def test_execute_with_special_characters(self):
        """Test execute with special characters in data"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")
            
            # Store test data with special characters
            test_data = [
                {"name": "Alice", "description": "Test data"},
                {"name": "Bob", "description": "Another test"},
            ]
            client.store(test_data)
            
            # Test basic queries - special character handling may vary
            try:
                result = client.execute("SELECT name FROM default")
                assert len(result) >= 0
            except Exception as e:
                print(f"Special char query: {e}")
            
            client.close()
    
    def test_execute_complex_joins(self):
        """Test complex SQL operations (if supported)"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")
            
            # Store test data
            test_data = [
                {"name": "Alice", "age": 25, "dept": "Engineering"},
                {"name": "Bob", "age": 30, "dept": "Sales"},
                {"name": "Charlie", "age": 35, "dept": "Engineering"},
            ]
            client.store(test_data)
            
            # Test subquery (if supported)
            try:
                result = client.execute("""
                    SELECT name, age 
                    FROM default 
                    WHERE age > (SELECT AVG(age) FROM default)
                """)
                
                # Should return employees older than average (30)
                assert len(result) == 1
                assert result.first()["name"] == "Charlie"
                
            except Exception as e:
                print(f"Subqueries not supported: {e}")
            
            # Test complex CASE statement (if supported)
            try:
                result = client.execute("""
                    SELECT name, age,
                           CASE 
                               WHEN age < 30 THEN 'Young'
                               WHEN age < 40 THEN 'Middle'
                               ELSE 'Senior'
                           END as category
                    FROM default
                    ORDER BY age
                """)
                
                assert len(result) == 3
                
            except Exception as e:
                print(f"CASE statements not supported: {e}")
            
            client.close()


class TestSQLPerformance:
    """Test SQL performance considerations"""
    
    def test_execute_performance_large_dataset(self):
        """Test execute performance with large dataset"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")
            
            # Store dataset
            data = [
                {"id": i, "category": f"cat_{i % 10}", "value": i * 1.5}
                for i in range(1000)
            ]
            client.store(data)
            
            import time
            
            # Test aggregate performance
            start_time = time.time()
            try:
                result = client.execute("SELECT COUNT(*) as count FROM default")
                assert result.scalar() >= 0
            except Exception as e:
                print(f"Perf test: {e}")
            end_time = time.time()
            
            assert (end_time - start_time) < 5.0  # Should be reasonably fast
            
            client.close()
    
    def test_execute_arrow_optimization(self):
        """Test Arrow optimization in execute when available"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")
            
            # Store test data
            test_data = [
                {"name": "Alice", "age": 25},
                {"name": "Bob", "age": 30},
                {"name": "Charlie", "age": 35},
            ]
            client.store(test_data)
            
            result = client.execute("SELECT name, age FROM default")
            
            # If Arrow is available, result should use Arrow internally
            if ARROW_AVAILABLE and PYARROW_AVAILABLE:
                # Test that Arrow conversion works
                try:
                    table = result.to_arrow()
                    assert isinstance(table, pa.Table)
                except Exception:
                    pass  # Arrow optimization might not be active
            
            client.close()


def _store_rows_in_chunks(client: ApexClient, rows_iter, chunk_size: int = 50_000):
    buf = []
    for r in rows_iter:
        buf.append(r)
        if len(buf) >= chunk_size:
            client.store(buf)
            buf.clear()
    if buf:
        client.store(buf)


# Keep pytest fast while preserving the large-query shape. Set these env vars to
# 200000/1000000/1000000 to run the original 1M-row stress profile locally.
_PERF_JOIN_USER_ROWS = int(os.environ.get("APEXBASE_TEST_JOIN_USER_ROWS", "50000"))
_PERF_JOIN_ORDER_ROWS = int(os.environ.get("APEXBASE_TEST_JOIN_ORDER_ROWS", "250000"))
_PERF_SUBQUERY_ROWS = int(os.environ.get("APEXBASE_TEST_SUBQUERY_ROWS", "250000"))
_PERF_QUERY_RUNS = int(os.environ.get("APEXBASE_TEST_QUERY_RUNS", "3"))


class TestSQLPerformance1M:
    @pytest.mark.perf
    @pytest.mark.slow
    def test_perf_1m_join_filter_order_limit(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)

            client.create_table("users")
            t_store0 = time.perf_counter()
            _store_rows_in_chunks(
                client,
                (
                    {"user_id": i, "tier": "pro" if (i % 10 == 0) else "free"}
                    for i in range(_PERF_JOIN_USER_ROWS)
                ),
                chunk_size=50_000,
            )
            t_store1 = time.perf_counter()
            client.flush()
            t_flush1 = time.perf_counter()

            client.create_table("orders")
            _store_rows_in_chunks(
                client,
                (
                    {
                        "order_id": i,
                        "user_id": i % _PERF_JOIN_USER_ROWS,
                        "amount": (i % 97) * 1.0,
                    }
                    for i in range(_PERF_JOIN_ORDER_ROWS)
                ),
                chunk_size=50_000,
            )
            t_store2 = time.perf_counter()
            client.flush()
            t_flush2 = time.perf_counter()

            sql = """
            SELECT u.tier, COUNT(*) AS c, SUM(o.amount) AS s
            FROM users u
            JOIN orders o ON u.user_id = o.user_id
            WHERE o.amount >= 50
            GROUP BY u.tier
            ORDER BY s DESC
            LIMIT 10
            """.strip()

            # Warmup + repeated runs to measure executor-only improvements
            _execute_or_xfail(client, sql).to_dict()
            times = []
            for _ in range(_PERF_QUERY_RUNS):
                t0 = time.perf_counter()
                result = _execute_or_xfail(client, sql)
                rows = result.to_dict()
                t1 = time.perf_counter()
                times.append(t1 - t0)

            assert isinstance(rows, list)
            assert len(rows) <= 2
            assert all("tier" in r and "c" in r and "s" in r for r in rows)
            avg = sum(times) / len(times)
            print(
                f"perf_1m_join_filter_order_limit: query_avg={avg:.3f}s query_runs={[round(x, 3) for x in times]} "
                f"users={_PERF_JOIN_USER_ROWS} orders={_PERF_JOIN_ORDER_ROWS} "
                f"store_users={t_store1 - t_store0:.3f}s flush_users={t_flush1 - t_store1:.3f}s "
                f"store_orders={t_store2 - t_flush1:.3f}s flush_orders={t_flush2 - t_store2:.3f}s"
            )

            client.close()

    @pytest.mark.perf
    @pytest.mark.slow
    def test_perf_1m_nested_subquery_two_stage(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")

            t_store0 = time.perf_counter()
            _store_rows_in_chunks(
                client,
                (
                    {
                        "k": i,
                        "region": f"r{i % 200}",
                        "channel": f"c{i % 20}",
                        "amount": float(i % 101),
                    }
                    for i in range(_PERF_SUBQUERY_ROWS)
                ),
                chunk_size=50_000,
            )
            t_store1 = time.perf_counter()
            client.flush()
            t_flush1 = time.perf_counter()

            sql = """
            SELECT COUNT(*) AS big_groups
            FROM (
                SELECT region, channel, SUM(amount) AS s
                FROM default
                GROUP BY region, channel
                HAVING SUM(amount) >= 20000
            ) t
            WHERE t.s >= 20000
            """.strip()

            _execute_or_xfail(client, sql).scalar()
            times = []
            for _ in range(_PERF_QUERY_RUNS):
                t0 = time.perf_counter()
                result = _execute_or_xfail(client, sql)
                v = result.scalar()
                t1 = time.perf_counter()
                times.append(t1 - t0)

            assert v is None or isinstance(v, (int, float, np.integer, np.floating))
            avg = sum(times) / len(times)
            print(
                f"perf_1m_nested_subquery_two_stage: query_avg={avg:.3f}s query_runs={[round(x, 3) for x in times]} "
                f"rows={_PERF_SUBQUERY_ROWS} "
                f"store={t_store1 - t_store0:.3f}s flush={t_flush1 - t_store1:.3f}s"
            )

            client.close()


if __name__ == "__main__":
    pytest.main([__file__, "-v"])