1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
|
from sqlalchemy import bindparam
from sqlalchemy import Column
from sqlalchemy import delete
from sqlalchemy import exc
from sqlalchemy import ForeignKey
from sqlalchemy import func
from sqlalchemy import insert
from sqlalchemy import inspect
from sqlalchemy import Integer
from sqlalchemy import literal
from sqlalchemy import literal_column
from sqlalchemy import null
from sqlalchemy import or_
from sqlalchemy import select
from sqlalchemy import String
from sqlalchemy import testing
from sqlalchemy import text
from sqlalchemy import union
from sqlalchemy import update
from sqlalchemy import util
from sqlalchemy.orm import aliased
from sqlalchemy.orm import column_property
from sqlalchemy.orm import contains_eager
from sqlalchemy.orm import deferred
from sqlalchemy.orm import join as orm_join
from sqlalchemy.orm import joinedload
from sqlalchemy.orm import query_expression
from sqlalchemy.orm import relationship
from sqlalchemy.orm import undefer
from sqlalchemy.orm import with_expression
from sqlalchemy.orm import with_loader_criteria
from sqlalchemy.orm import with_polymorphic
from sqlalchemy.sql import and_
from sqlalchemy.sql import sqltypes
from sqlalchemy.sql.selectable import Join as core_join
from sqlalchemy.sql.selectable import LABEL_STYLE_DISAMBIGUATE_ONLY
from sqlalchemy.sql.selectable import LABEL_STYLE_TABLENAME_PLUS_COL
from sqlalchemy.testing import assert_raises_message
from sqlalchemy.testing import AssertsCompiledSQL
from sqlalchemy.testing import eq_
from sqlalchemy.testing import fixtures
from sqlalchemy.testing import is_
from sqlalchemy.testing import Variation
from sqlalchemy.testing.fixtures import fixture_session
from sqlalchemy.testing.util import resolve_lambda
from sqlalchemy.util.langhelpers import hybridproperty
from .inheritance import _poly_fixtures
from .test_query import QueryTest
from ..sql import test_compiler
from ..sql.test_compiler import CorrelateTest as _CoreCorrelateTest
# TODO:
# composites / unions, etc.
class SelectableTest(QueryTest, AssertsCompiledSQL):
__dialect__ = "default"
def test_filter_by(self):
User, Address = self.classes("User", "Address")
stmt = select(User).filter_by(name="ed")
self.assert_compile(
stmt,
"SELECT users.id, users.name FROM users "
"WHERE users.name = :name_1",
)
def test_c_accessor_not_mutated_subq(self):
"""test #6394, ensure all_selected_columns is generated each time"""
User = self.classes.User
s1 = select(User.id)
eq_(s1.subquery().c.keys(), ["id"])
eq_(s1.subquery().c.keys(), ["id"])
def test_integration_w_8285_subc(self):
Address = self.classes.Address
s1 = select(
Address.id, Address.__table__.c["user_id", "email_address"]
)
self.assert_compile(
s1,
"SELECT addresses.id, addresses.user_id, "
"addresses.email_address FROM addresses",
)
subq = s1.subquery()
self.assert_compile(
select(subq.c.user_id, subq.c.id),
"SELECT anon_1.user_id, anon_1.id FROM (SELECT addresses.id AS "
"id, addresses.user_id AS user_id, addresses.email_address "
"AS email_address FROM addresses) AS anon_1",
)
def test_scalar_subquery_from_subq_same_source(self):
"""test #6394, ensure all_selected_columns is generated each time"""
User = self.classes.User
s1 = select(User.id)
for i in range(2):
stmt = s1.subquery().select().scalar_subquery()
self.assert_compile(
stmt,
"(SELECT anon_1.id FROM "
"(SELECT users.id AS id FROM users) AS anon_1)",
)
def test_froms_single_table(self):
User, Address = self.classes("User", "Address")
stmt = select(User).filter_by(name="ed")
eq_(stmt.get_final_froms(), [self.tables.users])
def test_froms_join(self):
User, Address = self.classes("User", "Address")
users, addresses = self.tables("users", "addresses")
stmt = select(User).join(User.addresses)
assert stmt.get_final_froms()[0].compare(users.join(addresses))
@testing.combinations(
(
lambda User: (User,),
lambda User: [
{
"name": "User",
"type": User,
"aliased": False,
"expr": User,
"entity": User,
}
],
),
(
lambda user_alias: (user_alias,),
lambda User, user_alias: [
{
"name": None,
"type": User,
"aliased": True,
"expr": user_alias,
"entity": user_alias,
}
],
),
(
lambda User: (User.id,),
lambda User: [
{
"name": "id",
"type": testing.eq_type_affinity(sqltypes.Integer),
"aliased": False,
"expr": User.id,
"entity": User,
}
],
),
(
lambda User, Address: (User.id, Address),
lambda User, Address: [
{
"name": "id",
"type": testing.eq_type_affinity(sqltypes.Integer),
"aliased": False,
"expr": User.id,
"entity": User,
},
{
"name": "Address",
"type": Address,
"aliased": False,
"expr": Address,
"entity": Address,
},
],
),
(
lambda User, Address: (User.id, text("whatever")),
lambda User, Address: [
{
"name": "id",
"type": testing.eq_type_affinity(sqltypes.Integer),
"aliased": False,
"expr": User.id,
"entity": User,
},
{
"name": None,
"type": testing.eq_type_affinity(sqltypes.NullType),
"aliased": False,
"expr": testing.eq_clause_element(text("whatever")),
"entity": None,
},
],
),
(
lambda user_table: (user_table,),
lambda user_table: [
{
"name": "id",
"type": testing.eq_type_affinity(sqltypes.Integer),
"expr": user_table.c.id,
},
{
"name": "name",
"type": testing.eq_type_affinity(sqltypes.String),
"expr": user_table.c.name,
},
],
),
argnames="cols, expected",
)
def test_column_descriptions(self, cols, expected):
User, Address = self.classes("User", "Address")
ua = aliased(User)
cols = testing.resolve_lambda(
cols,
User=User,
Address=Address,
user_alias=ua,
user_table=inspect(User).local_table,
)
expected = testing.resolve_lambda(
expected,
User=User,
Address=Address,
user_alias=ua,
user_table=inspect(User).local_table,
)
stmt = select(*cols)
eq_(stmt.column_descriptions, expected)
if stmt._propagate_attrs:
stmt = select(*cols).from_statement(stmt)
eq_(stmt.column_descriptions, expected)
@testing.combinations(insert, update, delete, argnames="dml_construct")
@testing.combinations(
(
lambda User: User,
lambda User: (User.id, User.name),
lambda User, user_table: {
"name": "User",
"type": User,
"expr": User,
"entity": User,
"table": user_table,
},
lambda User: [
{
"name": "id",
"type": testing.eq_type_affinity(sqltypes.Integer),
"aliased": False,
"expr": User.id,
"entity": User,
},
{
"name": "name",
"type": testing.eq_type_affinity(sqltypes.String),
"aliased": False,
"expr": User.name,
"entity": User,
},
],
),
argnames="entity, cols, expected_entity, expected_returning",
)
def test_dml_descriptions(
self, dml_construct, entity, cols, expected_entity, expected_returning
):
User, Address = self.classes("User", "Address")
lambda_args = dict(
User=User,
Address=Address,
user_table=inspect(User).local_table,
)
entity = testing.resolve_lambda(entity, **lambda_args)
cols = testing.resolve_lambda(cols, **lambda_args)
expected_entity = testing.resolve_lambda(
expected_entity, **lambda_args
)
expected_returning = testing.resolve_lambda(
expected_returning, **lambda_args
)
stmt = dml_construct(entity)
if cols:
stmt = stmt.returning(*cols)
eq_(stmt.entity_description, expected_entity)
eq_(stmt.returning_column_descriptions, expected_returning)
@testing.combinations(
(
lambda User, Address: select(User.name)
.select_from(User, Address)
.where(User.id == Address.user_id),
"SELECT users.name FROM users, addresses "
"WHERE users.id = addresses.user_id",
),
(
lambda User, Address: select(User.name)
.select_from(Address, User)
.where(User.id == Address.user_id),
"SELECT users.name FROM addresses, users "
"WHERE users.id = addresses.user_id",
),
)
def test_select_from_ordering(self, stmt, expected):
User, Address = self.classes("User", "Address")
lambda_args = dict(
User=User,
Address=Address,
user_table=inspect(User).local_table,
)
stmt = testing.resolve_lambda(stmt, **lambda_args)
self.assert_compile(stmt, expected)
def test_limit_offset_select(self):
User = self.classes.User
stmt = select(User.id).limit(5).offset(6)
self.assert_compile(
stmt,
"SELECT users.id FROM users LIMIT :param_1 OFFSET :param_2",
checkparams={"param_1": 5, "param_2": 6},
)
@testing.combinations(
(None, "ROWS ONLY"),
({"percent": True}, "PERCENT ROWS ONLY"),
({"percent": True, "with_ties": True}, "PERCENT ROWS WITH TIES"),
)
def test_fetch_offset_select(self, options, fetch_clause):
User = self.classes.User
if options is None:
stmt = select(User.id).fetch(5).offset(6)
else:
stmt = select(User.id).fetch(5, **options).offset(6)
self.assert_compile(
stmt,
"SELECT users.id FROM users OFFSET :param_1 "
"ROWS FETCH FIRST :param_2 %s" % (fetch_clause,),
checkparams={"param_1": 6, "param_2": 5},
)
class DMLTest(QueryTest, AssertsCompiledSQL):
__dialect__ = "default"
@testing.variation("stmt_type", ["update", "delete"])
def test_dml_ctes(self, stmt_type: testing.Variation):
User = self.classes.User
if stmt_type.update:
fn = update
elif stmt_type.delete:
fn = delete
else:
stmt_type.fail()
inner_cte = fn(User).returning(User.id).cte("uid")
stmt = select(inner_cte)
if stmt_type.update:
self.assert_compile(
stmt,
"WITH uid AS (UPDATE users SET id=:id, name=:name "
"RETURNING users.id) SELECT uid.id FROM uid",
)
elif stmt_type.delete:
self.assert_compile(
stmt,
"WITH uid AS (DELETE FROM users "
"RETURNING users.id) SELECT uid.id FROM uid",
)
else:
stmt_type.fail()
class ColumnsClauseFromsTest(QueryTest, AssertsCompiledSQL):
__dialect__ = "default"
def test_exclude_eagerloads(self):
User, Address = self.classes("User", "Address")
stmt = select(User).options(joinedload(User.addresses))
froms = stmt.columns_clause_froms
mapper = inspect(User)
is_(froms[0], inspect(User).__clause_element__())
eq_(
froms[0]._annotations,
{
"entity_namespace": mapper,
"parententity": mapper,
"parentmapper": mapper,
},
)
eq_(len(froms), 1)
def test_maintain_annotations_from_table(self):
User, Address = self.classes("User", "Address")
stmt = select(User)
mapper = inspect(User)
froms = stmt.columns_clause_froms
is_(froms[0], inspect(User).__clause_element__())
eq_(
froms[0]._annotations,
{
"entity_namespace": mapper,
"parententity": mapper,
"parentmapper": mapper,
},
)
eq_(len(froms), 1)
def test_maintain_annotations_from_annoated_cols(self):
User, Address = self.classes("User", "Address")
stmt = select(User.id)
mapper = inspect(User)
froms = stmt.columns_clause_froms
is_(froms[0], inspect(User).__clause_element__())
eq_(
froms[0]._annotations,
{
"entity_namespace": mapper,
"parententity": mapper,
"parentmapper": mapper,
},
)
eq_(len(froms), 1)
@testing.combinations((True,), (False,))
def test_replace_into_select_from_maintains_existing(self, use_flag):
User, Address = self.classes("User", "Address")
stmt = select(User.id).select_from(Address)
if use_flag:
stmt = stmt.with_only_columns(
func.count(), maintain_column_froms=True
)
else:
stmt = stmt.select_from(
*stmt.columns_clause_froms
).with_only_columns(func.count())
# Address is maintained in the FROM list
self.assert_compile(
stmt, "SELECT count(*) AS count_1 FROM addresses, users"
)
@testing.combinations((True,), (False,))
def test_replace_into_select_from_with_loader_criteria(self, use_flag):
User, Address = self.classes("User", "Address")
stmt = select(User.id).options(
with_loader_criteria(User, User.name == "ed")
)
if use_flag:
stmt = stmt.with_only_columns(
func.count(), maintain_column_froms=True
)
else:
stmt = stmt.select_from(
*stmt.columns_clause_froms
).with_only_columns(func.count())
self.assert_compile(
stmt,
"SELECT count(*) AS count_1 FROM users WHERE users.name = :name_1",
)
class JoinTest(QueryTest, AssertsCompiledSQL):
__dialect__ = "default"
def test_join_from_no_onclause(self):
User, Address = self.classes("User", "Address")
stmt = select(literal_column("1")).join_from(User, Address)
self.assert_compile(
stmt,
"SELECT 1 FROM users JOIN addresses "
"ON users.id = addresses.user_id",
)
def test_join_from_w_relationship(self):
User, Address = self.classes("User", "Address")
stmt = select(literal_column("1")).join_from(
User, Address, User.addresses
)
self.assert_compile(
stmt,
"SELECT 1 FROM users JOIN addresses "
"ON users.id = addresses.user_id",
)
def test_join_from_alised_w_relationship(self):
User, Address = self.classes("User", "Address")
u1 = aliased(User)
stmt = select(literal_column("1")).join_from(u1, Address, u1.addresses)
self.assert_compile(
stmt,
"SELECT 1 FROM users AS users_1 JOIN addresses "
"ON users_1.id = addresses.user_id",
)
def test_join_conflicting_right_side(self):
User, Address = self.classes("User", "Address")
stmt = select(User).join(Address, User.orders)
assert_raises_message(
exc.InvalidRequestError,
"Join target .*Address.* does not correspond to the right side "
"of join condition User.orders",
stmt.compile,
)
def test_join_from_conflicting_left_side_plain(self):
User, Address, Order = self.classes("User", "Address", "Order")
stmt = select(User).join_from(User, Address, Order.address)
assert_raises_message(
exc.InvalidRequestError,
r"explicit from clause .*User.* does not match .* Order.address",
stmt.compile,
)
def test_join_from_conflicting_left_side_mapper_vs_aliased(self):
User, Address = self.classes("User", "Address")
u1 = aliased(User)
stmt = select(User).join_from(User, Address, u1.addresses)
assert_raises_message(
exc.InvalidRequestError,
# the display of the attribute here is not consistent vs.
# the straight aliased class, should improve this.
r"explicit from clause .*User.* does not match left side .*"
r"of relationship attribute aliased\(User\).addresses",
stmt.compile,
)
def test_join_from_conflicting_left_side_aliased_vs_mapper(self):
User, Address = self.classes("User", "Address")
u1 = aliased(User)
stmt = select(u1).join_from(u1, Address, User.addresses)
assert_raises_message(
exc.InvalidRequestError,
r"explicit from clause aliased\(User\) does not match left "
"side of relationship attribute User.addresses",
stmt.compile,
)
def test_join_from_we_can_explicitly_tree_joins(self):
User, Address, Order, Item, Keyword = self.classes(
"User", "Address", "Order", "Item", "Keyword"
)
stmt = (
select(User)
.join(User.addresses)
.join_from(User, Order, User.orders)
.join(Order.items)
)
self.assert_compile(
stmt,
"SELECT users.id, users.name FROM users JOIN addresses "
"ON users.id = addresses.user_id JOIN orders "
"ON users.id = orders.user_id JOIN order_items AS order_items_1 "
"ON orders.id = order_items_1.order_id JOIN items "
"ON items.id = order_items_1.item_id",
)
def test_join_from_w_filter_by(self):
User, Address, Order, Item, Keyword = self.classes(
"User", "Address", "Order", "Item", "Keyword"
)
stmt = (
select(User)
.filter_by(name="n1")
.join(User.addresses)
.filter_by(email_address="a1")
.join_from(User, Order, User.orders)
.filter_by(description="d1")
.join(Order.items)
.filter_by(description="d2")
)
self.assert_compile(
stmt,
"SELECT users.id, users.name FROM users "
"JOIN addresses ON users.id = addresses.user_id "
"JOIN orders ON users.id = orders.user_id "
"JOIN order_items AS order_items_1 "
"ON orders.id = order_items_1.order_id "
"JOIN items ON items.id = order_items_1.item_id "
"WHERE users.name = :name_1 "
"AND addresses.email_address = :email_address_1 "
"AND orders.description = :description_1 "
"AND items.description = :description_2",
checkparams={
"name_1": "n1",
"email_address_1": "a1",
"description_1": "d1",
"description_2": "d2",
},
)
@testing.combinations(
(
lambda User: select(User).where(User.id == bindparam("foo")),
"SELECT users.id, users.name FROM users WHERE users.id = :foo",
{"foo": "bar"},
{"foo": "bar"},
),
(
lambda User, Address: select(User)
.join_from(User, Address)
.where(User.id == bindparam("foo")),
"SELECT users.id, users.name FROM users JOIN addresses "
"ON users.id = addresses.user_id WHERE users.id = :foo",
{"foo": "bar"},
{"foo": "bar"},
),
(
lambda User, Address: select(User)
.join_from(User, Address, User.addresses)
.where(User.id == bindparam("foo")),
"SELECT users.id, users.name FROM users JOIN addresses "
"ON users.id = addresses.user_id WHERE users.id = :foo",
{"foo": "bar"},
{"foo": "bar"},
),
(
lambda User, Address: select(User)
.join(User.addresses)
.where(User.id == bindparam("foo")),
"SELECT users.id, users.name FROM users JOIN addresses "
"ON users.id = addresses.user_id WHERE users.id = :foo",
{"foo": "bar"},
{"foo": "bar"},
),
)
def test_params_with_join(
self, test_case, expected, bindparams, expected_params
):
User, Address = self.classes("User", "Address")
stmt = resolve_lambda(test_case, **locals())
stmt = stmt.params(**bindparams)
self.assert_compile(stmt, expected, checkparams=expected_params)
class LoadersInSubqueriesTest(QueryTest, AssertsCompiledSQL):
"""The Query object calls eanble_eagerloads(False) when you call
.subquery(). With Core select, we don't have that information, we instead
have to look at the "toplevel" flag to know where we are. make sure
the many different combinations that these two objects and still
too many flags at the moment work as expected on the outside.
"""
__dialect__ = "default"
run_setup_mappers = None
@testing.fixture
def joinedload_fixture(self):
users, Address, addresses, User = (
self.tables.users,
self.classes.Address,
self.tables.addresses,
self.classes.User,
)
self.mapper_registry.map_imperatively(
User,
users,
properties={"addresses": relationship(Address, lazy="joined")},
)
self.mapper_registry.map_imperatively(Address, addresses)
return User, Address
@testing.fixture
def deferred_fixture(self):
User = self.classes.User
users = self.tables.users
self.mapper_registry.map_imperatively(
User,
users,
properties={
"name": deferred(users.c.name),
"name_upper": column_property(
func.upper(users.c.name), deferred=True
),
},
)
return User
@testing.fixture
def non_deferred_fixture(self):
User = self.classes.User
users = self.tables.users
self.mapper_registry.map_imperatively(
User,
users,
properties={
"name_upper": column_property(func.upper(users.c.name))
},
)
return User
def test_no_joinedload_in_subquery_select_rows(self, joinedload_fixture):
User, Address = joinedload_fixture
sess = fixture_session()
stmt1 = sess.query(User).subquery()
stmt1 = sess.query(stmt1)
stmt2 = select(User).subquery()
stmt2 = select(stmt2)
expected = (
"SELECT anon_1.id, anon_1.name FROM "
"(SELECT users.id AS id, users.name AS name "
"FROM users) AS anon_1"
)
self.assert_compile(
stmt1._final_statement(legacy_query_style=False),
expected,
)
self.assert_compile(stmt2, expected)
def test_no_joinedload_in_subquery_select_entity(self, joinedload_fixture):
User, Address = joinedload_fixture
sess = fixture_session()
stmt1 = sess.query(User).subquery()
ua = aliased(User, stmt1)
stmt1 = sess.query(ua)
stmt2 = select(User).subquery()
ua = aliased(User, stmt2)
stmt2 = select(ua)
expected = (
"SELECT anon_1.id, anon_1.name, addresses_1.id AS id_1, "
"addresses_1.user_id, addresses_1.email_address FROM "
"(SELECT users.id AS id, users.name AS name FROM users) AS anon_1 "
"LEFT OUTER JOIN addresses AS addresses_1 "
"ON anon_1.id = addresses_1.user_id"
)
self.assert_compile(
stmt1._final_statement(legacy_query_style=False),
expected,
)
self.assert_compile(stmt2, expected)
def test_deferred_subq_one(self, deferred_fixture):
"""test for #6661"""
User = deferred_fixture
subq = select(User).subquery()
u1 = aliased(User, subq)
q = select(u1)
self.assert_compile(
q,
"SELECT anon_1.id "
"FROM (SELECT users.id AS id, users.name AS name "
"FROM users) AS anon_1",
)
# testing deferred opts separately for deterministic SQL generation
q = select(u1).options(undefer(u1.name))
self.assert_compile(
q,
"SELECT anon_1.id, anon_1.name "
"FROM (SELECT users.id AS id, users.name AS name "
"FROM users) AS anon_1",
)
q = select(u1).options(undefer(u1.name_upper))
self.assert_compile(
q,
"SELECT upper(anon_1.name) AS upper_1, anon_1.id "
"FROM (SELECT users.id AS id, users.name AS name "
"FROM users) AS anon_1",
)
def test_non_deferred_subq_one(self, non_deferred_fixture):
"""test for #6661
cols that aren't deferred go into subqueries. 1.3 did this also.
"""
User = non_deferred_fixture
subq = select(User).subquery()
u1 = aliased(User, subq)
q = select(u1)
self.assert_compile(
q,
"SELECT upper(anon_1.name) AS upper_1, anon_1.id, anon_1.name "
"FROM (SELECT upper(users.name) AS upper_2, users.id AS id, "
"users.name AS name FROM users) AS anon_1",
)
def test_deferred_subq_two(self, deferred_fixture):
"""test for #6661
in this test, we are only confirming the current contract of ORM
subqueries which is that deferred + derived column_property's don't
export themselves into the .c. collection of a subquery.
We might want to revisit this in some way.
"""
User = deferred_fixture
subq = select(User).subquery()
assert not hasattr(subq.c, "name_upper")
# "undefer" it by including it
subq = select(User, User.name_upper).subquery()
assert hasattr(subq.c, "name_upper")
def test_non_deferred_col_prop_targetable_in_subq(
self, non_deferred_fixture
):
"""test for #6661"""
User = non_deferred_fixture
subq = select(User).subquery()
assert hasattr(subq.c, "name_upper")
def test_recursive_cte_render_on_deferred(self, deferred_fixture):
"""test for #6661.
this test is most directly the bug reported in #6661,
as the CTE uses stmt._exported_columns_iterator() ahead of compiling
the SELECT in order to get the list of columns that will be selected,
this has to match what the subquery is going to render.
This is also pretty fundamental to why deferred() as an option
can't be honored in a subquery; the subquery needs to export the
correct columns and it needs to do so without having to process
all the loader options. 1.3 OTOH when you got a subquery from
Query, it did a full compile_context. 1.4/2.0 we don't do that
anymore.
"""
User = deferred_fixture
cte = select(User).cte(recursive=True)
# nonsensical, but we are just testing form
cte = cte.union_all(select(User).join(cte, cte.c.id == User.id))
stmt = select(User).join(cte, User.id == cte.c.id)
self.assert_compile(
stmt,
"WITH RECURSIVE anon_1(id, name) AS "
"(SELECT users.id AS id, users.name AS name FROM users "
"UNION ALL SELECT users.id AS id, users.name AS name "
"FROM users JOIN anon_1 ON anon_1.id = users.id) "
"SELECT users.id FROM users JOIN anon_1 ON users.id = anon_1.id",
)
# testing deferred opts separately for deterministic SQL generation
self.assert_compile(
stmt.options(undefer(User.name_upper)),
"WITH RECURSIVE anon_1(id, name) AS "
"(SELECT users.id AS id, users.name AS name FROM users "
"UNION ALL SELECT users.id AS id, users.name AS name "
"FROM users JOIN anon_1 ON anon_1.id = users.id) "
"SELECT upper(users.name) AS upper_1, users.id "
"FROM users JOIN anon_1 ON users.id = anon_1.id",
)
self.assert_compile(
stmt.options(undefer(User.name)),
"WITH RECURSIVE anon_1(id, name) AS "
"(SELECT users.id AS id, users.name AS name FROM users "
"UNION ALL SELECT users.id AS id, users.name AS name "
"FROM users JOIN anon_1 ON anon_1.id = users.id) "
"SELECT users.id, users.name "
"FROM users JOIN anon_1 ON users.id = anon_1.id",
)
def test_nested_union_deferred(self, deferred_fixture):
"""test #6678"""
User = deferred_fixture
s1 = select(User).where(User.id == 5)
s2 = select(User).where(User.id == 6)
s3 = select(User).where(User.id == 7)
stmt = union(s1.union(s2), s3)
u_alias = aliased(User, stmt.subquery())
self.assert_compile(
select(u_alias),
"SELECT anon_1.id FROM ((SELECT users.id AS id, "
"users.name AS name "
"FROM users "
"WHERE users.id = :id_1 UNION SELECT users.id AS id, "
"users.name AS name "
"FROM users WHERE users.id = :id_2) "
"UNION SELECT users.id AS id, users.name AS name "
"FROM users WHERE users.id = :id_3) AS anon_1",
)
def test_nested_union_undefer_option(self, deferred_fixture):
"""test #6678
in this case we want to see that the unions include the deferred
columns so that if we undefer on the outside we can get the
column.
"""
User = deferred_fixture
s1 = select(User).where(User.id == 5)
s2 = select(User).where(User.id == 6)
s3 = select(User).where(User.id == 7)
stmt = union(s1.union(s2), s3)
u_alias = aliased(User, stmt.subquery())
self.assert_compile(
select(u_alias).options(undefer(u_alias.name)),
"SELECT anon_1.id, anon_1.name FROM "
"((SELECT users.id AS id, users.name AS name FROM users "
"WHERE users.id = :id_1 UNION SELECT users.id AS id, "
"users.name AS name "
"FROM users WHERE users.id = :id_2) "
"UNION SELECT users.id AS id, users.name AS name "
"FROM users WHERE users.id = :id_3) AS anon_1",
)
class ExtraColsTest(QueryTest, AssertsCompiledSQL):
__dialect__ = "default"
run_setup_mappers = None
@testing.fixture
def query_expression_fixture(self):
users, User = (
self.tables.users,
self.classes.User,
)
addresses, Address = (self.tables.addresses, self.classes.Address)
self.mapper_registry.map_imperatively(
User,
users,
properties=util.OrderedDict(
[
("value", query_expression()),
(
"value_w_default",
query_expression(default_expr=literal(15)),
),
]
),
)
self.mapper_registry.map_imperatively(Address, addresses)
return User
@testing.fixture
def deferred_fixture(self):
User = self.classes.User
users = self.tables.users
self.mapper_registry.map_imperatively(
User,
users,
properties={
"name": deferred(users.c.name),
"name_upper": column_property(
func.upper(users.c.name), deferred=True
),
},
)
return User
@testing.fixture
def query_expression_w_joinedload_fixture(self):
users, User = (
self.tables.users,
self.classes.User,
)
addresses, Address = (self.tables.addresses, self.classes.Address)
self.mapper_registry.map_imperatively(
User,
users,
properties=util.OrderedDict(
[
("value", query_expression()),
(
"addresses",
relationship(
Address,
primaryjoin=and_(
addresses.c.user_id == users.c.id,
addresses.c.email_address != None,
),
),
),
]
),
)
self.mapper_registry.map_imperatively(Address, addresses)
return User
@testing.fixture
def column_property_fixture(self):
users, Address, addresses, User = (
self.tables.users,
self.classes.Address,
self.tables.addresses,
self.classes.User,
)
self.mapper_registry.map_imperatively(
User,
users,
properties=util.OrderedDict(
[
("concat", column_property(users.c.id * 2)),
(
"count",
column_property(
select(func.count(addresses.c.id))
.where(
users.c.id == addresses.c.user_id,
)
.correlate(users)
.scalar_subquery()
),
),
]
),
)
self.mapper_registry.map_imperatively(
Address,
addresses,
properties={
"user": relationship(
User,
)
},
)
return User, Address
@testing.fixture
def plain_fixture(self):
users, Address, addresses, User = (
self.tables.users,
self.classes.Address,
self.tables.addresses,
self.classes.User,
)
self.mapper_registry.map_imperatively(
User,
users,
properties={
"addresses": relationship(Address, back_populates="user")
},
)
self.mapper_registry.map_imperatively(
Address,
addresses,
properties={
"user": relationship(User, back_populates="addresses")
},
)
return User, Address
@testing.fixture
def hard_labeled_self_ref_fixture(self, decl_base):
class A(decl_base):
__tablename__ = "a"
id = Column(Integer, primary_key=True)
a_id = Column(ForeignKey("a.id"))
data = Column(String)
data_lower = column_property(func.lower(data).label("hardcoded"))
as_ = relationship("A")
return A
def test_no_joinedload_embedded(self, plain_fixture):
User, Address = plain_fixture
stmt = select(Address).options(joinedload(Address.user))
subq = stmt.subquery()
s2 = select(subq)
self.assert_compile(
s2,
"SELECT anon_1.id, anon_1.user_id, anon_1.email_address "
"FROM (SELECT addresses.id AS id, addresses.user_id AS "
"user_id, addresses.email_address AS email_address "
"FROM addresses) AS anon_1",
)
def test_with_expr_one(self, query_expression_fixture):
User = query_expression_fixture
stmt = select(User).options(
with_expression(User.value, User.name + "foo")
)
self.assert_compile(
stmt,
"SELECT users.name || :name_1 AS anon_1, :param_1 AS anon_2, "
"users.id, "
"users.name FROM users",
)
def test_exported_columns_query_expression(self, query_expression_fixture):
"""test behaviors related to #8881"""
User = query_expression_fixture
stmt = select(User)
eq_(
stmt.selected_columns.keys(),
["value_w_default", "id", "name"],
)
stmt = select(User).options(
with_expression(User.value, User.name + "foo")
)
# bigger problem. we still don't include 'value', because we dont
# run query options here. not "correct", but is at least consistent
# with deferred
eq_(
stmt.selected_columns.keys(),
["value_w_default", "id", "name"],
)
def test_exported_columns_colprop(self, column_property_fixture):
"""test behaviors related to #8881"""
User, _ = column_property_fixture
stmt = select(User)
# we get all the cols because they are not deferred and have a value
eq_(
stmt.selected_columns.keys(),
["concat", "count", "id", "name"],
)
def test_exported_columns_deferred(self, deferred_fixture):
"""test behaviors related to #8881"""
User = deferred_fixture
stmt = select(User)
# don't include 'name_upper' as it's deferred and readonly.
# "name" however is a column on the table, so even though it is
# deferred, it gets special treatment (related to #6661)
eq_(
stmt.selected_columns.keys(),
["id", "name"],
)
stmt = select(User).options(
undefer(User.name), undefer(User.name_upper)
)
# undefer doesn't affect the readonly col because we dont look
# at options when we do selected_columns
eq_(
stmt.selected_columns.keys(),
["id", "name"],
)
def test_with_expr_two(self, query_expression_fixture):
User = query_expression_fixture
stmt = select(User.id, User.name, (User.name + "foo").label("foo"))
subq = stmt.subquery()
u1 = aliased(User, subq)
stmt = select(u1).options(with_expression(u1.value, subq.c.foo))
self.assert_compile(
stmt,
"SELECT anon_1.foo, :param_1 AS anon_2, anon_1.id, "
"anon_1.name FROM "
"(SELECT users.id AS id, users.name AS name, "
"users.name || :name_1 AS foo FROM users) AS anon_1",
)
def test_with_expr_three(self, query_expression_w_joinedload_fixture):
"""test :ticket:`6259`"""
User = query_expression_w_joinedload_fixture
stmt = select(User).options(joinedload(User.addresses)).limit(1)
# test that the outer IS NULL is rendered
# test that the inner query does not include a NULL default
self.assert_compile(
stmt,
"SELECT anon_1.id, anon_1.name, addresses_1.id AS id_1, "
"addresses_1.user_id, addresses_1.email_address FROM "
"(SELECT users.id AS id, users.name AS name FROM users "
"LIMIT :param_1) AS anon_1 LEFT OUTER "
"JOIN addresses AS addresses_1 ON addresses_1.user_id = anon_1.id "
"AND addresses_1.email_address IS NOT NULL",
)
def test_with_expr_four(self, query_expression_w_joinedload_fixture):
"""test :ticket:`6259`"""
User = query_expression_w_joinedload_fixture
stmt = (
select(User)
.options(
with_expression(User.value, null()), joinedload(User.addresses)
)
.limit(1)
)
# test that the outer IS NULL is rendered, not adapted
# test that the inner query includes the NULL we asked for
# ironically, this statement would not actually fetch due to the NULL
# not allowing adaption and therefore failing on the result set
# matching, this was addressed in #7154.
self.assert_compile(
stmt,
"SELECT anon_2.anon_1, anon_2.id, anon_2.name, "
"addresses_1.id AS id_1, addresses_1.user_id, "
"addresses_1.email_address FROM (SELECT NULL AS anon_1, "
"users.id AS id, users.name AS name FROM users LIMIT :param_1) "
"AS anon_2 LEFT OUTER JOIN addresses AS addresses_1 "
"ON addresses_1.user_id = anon_2.id "
"AND addresses_1.email_address IS NOT NULL",
)
def test_joinedload_outermost(self, plain_fixture):
User, Address = plain_fixture
stmt = select(Address).options(joinedload(Address.user))
# render joined eager loads with stringify
self.assert_compile(
stmt,
"SELECT addresses.id, addresses.user_id, addresses.email_address, "
"users_1.id AS id_1, users_1.name FROM addresses "
"LEFT OUTER JOIN users AS users_1 "
"ON users_1.id = addresses.user_id",
)
def test_joinedload_outermost_w_wrapping_elements(self, plain_fixture):
User, Address = plain_fixture
stmt = (
select(User)
.options(joinedload(User.addresses))
.limit(10)
.distinct()
)
self.assert_compile(
stmt,
"SELECT anon_1.id, anon_1.name, addresses_1.id AS id_1, "
"addresses_1.user_id, addresses_1.email_address FROM "
"(SELECT DISTINCT users.id AS id, users.name AS name FROM users "
"LIMIT :param_1) "
"AS anon_1 LEFT OUTER JOIN addresses AS addresses_1 "
"ON anon_1.id = addresses_1.user_id",
)
def test_contains_eager_outermost_w_wrapping_elements(self, plain_fixture):
"""test #8569"""
User, Address = plain_fixture
stmt = (
select(User)
.join(User.addresses)
.options(contains_eager(User.addresses))
.limit(10)
.distinct()
)
self.assert_compile(
stmt,
"SELECT DISTINCT addresses.id, addresses.user_id, "
"addresses.email_address, users.id AS id_1, users.name "
"FROM users JOIN addresses ON users.id = addresses.user_id "
"LIMIT :param_1",
)
def test_joinedload_hard_labeled_selfref(
self, hard_labeled_self_ref_fixture
):
"""test #8569"""
A = hard_labeled_self_ref_fixture
stmt = select(A).options(joinedload(A.as_)).distinct()
self.assert_compile(
stmt,
"SELECT anon_1.hardcoded, anon_1.id, anon_1.a_id, anon_1.data, "
"lower(a_1.data) AS lower_1, a_1.id AS id_1, a_1.a_id AS a_id_1, "
"a_1.data AS data_1 FROM (SELECT DISTINCT lower(a.data) AS "
"hardcoded, a.id AS id, a.a_id AS a_id, a.data AS data FROM a) "
"AS anon_1 LEFT OUTER JOIN a AS a_1 ON anon_1.id = a_1.a_id",
)
def test_contains_eager_hard_labeled_selfref(
self, hard_labeled_self_ref_fixture
):
"""test #8569"""
A = hard_labeled_self_ref_fixture
a1 = aliased(A)
stmt = (
select(A)
.join(A.as_.of_type(a1))
.options(contains_eager(A.as_.of_type(a1)))
.distinct()
)
self.assert_compile(
stmt,
"SELECT DISTINCT lower(a.data) AS hardcoded, "
"lower(a_1.data) AS hardcoded, a_1.id, a_1.a_id, a_1.data, "
"a.id AS id_1, a.a_id AS a_id_1, a.data AS data_1 "
"FROM a JOIN a AS a_1 ON a.id = a_1.a_id",
)
def test_column_properties(self, column_property_fixture):
"""test querying mappings that reference external columns or
selectables."""
User, Address = column_property_fixture
stmt = select(User)
self.assert_compile(
stmt,
"SELECT users.id * :id_1 AS anon_1, "
"(SELECT count(addresses.id) AS count_1 FROM addresses "
"WHERE users.id = addresses.user_id) AS anon_2, users.id, "
"users.name FROM users",
checkparams={"id_1": 2},
)
def test_column_properties_can_we_use(self, column_property_fixture):
"""test querying mappings that reference external columns or
selectables."""
# User, Address = column_property_fixture
# stmt = select(User)
# TODO: shouldn't we be able to get at count ?
# stmt = stmt.where(stmt.selected_columns.count > 5)
# self.assert_compile(stmt, "")
def test_column_properties_subquery(self, column_property_fixture):
"""test querying mappings that reference external columns or
selectables."""
User, Address = column_property_fixture
stmt = select(User)
# here, the subquery needs to export the columns that include
# the column properties
stmt = select(stmt.subquery())
# TODO: shouldn't we be able to get to stmt.subquery().c.count ?
self.assert_compile(
stmt,
"SELECT anon_2.anon_1, anon_2.anon_3, anon_2.id, anon_2.name "
"FROM (SELECT users.id * :id_1 AS anon_1, "
"(SELECT count(addresses.id) AS count_1 FROM addresses "
"WHERE users.id = addresses.user_id) AS anon_3, users.id AS id, "
"users.name AS name FROM users) AS anon_2",
checkparams={"id_1": 2},
)
def test_column_properties_subquery_two(self, column_property_fixture):
"""test querying mappings that reference external columns or
selectables."""
User, Address = column_property_fixture
# col properties will retain anonymous labels, however will
# adopt the .key within the subquery collection so they can
# be addressed.
stmt = select(
User.id,
User.name,
User.concat,
User.count,
)
subq = stmt.subquery()
# here, the subquery needs to export the columns that include
# the column properties
stmt = select(subq).where(subq.c.concat == "foo")
self.assert_compile(
stmt,
"SELECT anon_1.id, anon_1.name, anon_1.anon_2, anon_1.anon_3 "
"FROM (SELECT users.id AS id, users.name AS name, "
"users.id * :id_1 AS anon_2, "
"(SELECT count(addresses.id) AS count_1 "
"FROM addresses WHERE users.id = addresses.user_id) AS anon_3 "
"FROM users) AS anon_1 WHERE anon_1.anon_2 = :param_1",
checkparams={"id_1": 2, "param_1": "foo"},
)
def test_column_properties_aliased_subquery(self, column_property_fixture):
"""test querying mappings that reference external columns or
selectables."""
User, Address = column_property_fixture
u1 = aliased(User)
stmt = select(u1)
# here, the subquery needs to export the columns that include
# the column properties
stmt = select(stmt.subquery())
self.assert_compile(
stmt,
"SELECT anon_2.anon_1, anon_2.anon_3, anon_2.id, anon_2.name "
"FROM (SELECT users_1.id * :id_1 AS anon_1, "
"(SELECT count(addresses.id) AS count_1 FROM addresses "
"WHERE users_1.id = addresses.user_id) AS anon_3, "
"users_1.id AS id, users_1.name AS name "
"FROM users AS users_1) AS anon_2",
checkparams={"id_1": 2},
)
class RelationshipNaturalCompileTest(QueryTest, AssertsCompiledSQL):
"""test using core join() with relationship attributes.
as __clause_element__() produces a workable SQL expression, this should
be generally possible.
However, it can't work for many-to-many relationships, as these
require two joins. Only the ORM can look at the entities and decide
that there's a separate "secondary" table to be rendered as a separate
join.
"""
__dialect__ = "default"
def test_of_type_implicit_join(self):
User, Address = self.classes("User", "Address")
u1 = aliased(User)
a1 = aliased(Address)
stmt1 = select(u1).where(u1.addresses.of_type(a1))
stmt2 = (
fixture_session()
.query(u1)
.filter(u1.addresses.of_type(a1))
._final_statement(legacy_query_style=False)
)
expected = (
"SELECT users_1.id, users_1.name FROM users AS users_1, "
"addresses AS addresses_1 WHERE users_1.id = addresses_1.user_id"
)
self.assert_compile(stmt1, expected)
self.assert_compile(stmt2, expected)
def test_of_type_explicit_join(self):
User, Address = self.classes("User", "Address")
u1 = aliased(User)
a1 = aliased(Address)
stmt = select(u1).join(u1.addresses.of_type(a1))
self.assert_compile(
stmt,
"SELECT users_1.id, users_1.name FROM users AS users_1 "
"JOIN addresses AS addresses_1 "
"ON users_1.id = addresses_1.user_id",
)
def test_many_to_many_explicit_join(self):
Item, Keyword = self.classes("Item", "Keyword")
stmt = select(Item).join(Keyword, Item.keywords)
self.assert_compile(
stmt,
"SELECT items.id, items.description FROM items "
"JOIN item_keywords AS item_keywords_1 "
"ON items.id = item_keywords_1.item_id "
"JOIN keywords ON keywords.id = item_keywords_1.keyword_id",
)
def test_many_to_many_implicit_join(self):
Item, Keyword = self.classes("Item", "Keyword")
stmt = select(Item).where(Item.keywords)
# this was the intent of the primary + secondary clauseelement.
# it can do enough of the right thing in an implicit join
# context.
self.assert_compile(
stmt,
"SELECT items.id, items.description FROM items, "
"item_keywords AS item_keywords_1, keywords "
"WHERE items.id = item_keywords_1.item_id "
"AND keywords.id = item_keywords_1.keyword_id",
)
class InheritedTest(_poly_fixtures._Polymorphic):
run_setup_mappers = "once"
class ExplicitWithPolymorhpicTest(
_poly_fixtures._PolymorphicUnions, AssertsCompiledSQL
):
__dialect__ = "default"
default_punion = (
"(SELECT pjoin.person_id AS person_id, "
"pjoin.company_id AS company_id, "
"pjoin.name AS name, pjoin.type AS type, "
"pjoin.status AS status, pjoin.engineer_name AS engineer_name, "
"pjoin.primary_language AS primary_language, "
"pjoin.manager_name AS manager_name "
"FROM (SELECT engineers.person_id AS person_id, "
"people.company_id AS company_id, people.name AS name, "
"people.type AS type, engineers.status AS status, "
"engineers.engineer_name AS engineer_name, "
"engineers.primary_language AS primary_language, "
"CAST(NULL AS VARCHAR(50)) AS manager_name "
"FROM people JOIN engineers ON people.person_id = engineers.person_id "
"UNION ALL SELECT managers.person_id AS person_id, "
"people.company_id AS company_id, people.name AS name, "
"people.type AS type, managers.status AS status, "
"CAST(NULL AS VARCHAR(50)) AS engineer_name, "
"CAST(NULL AS VARCHAR(50)) AS primary_language, "
"managers.manager_name AS manager_name FROM people "
"JOIN managers ON people.person_id = managers.person_id) AS pjoin) "
"AS anon_1"
)
def test_subquery_col_expressions_wpoly_one(self):
Person, Manager, Engineer = self.classes(
"Person", "Manager", "Engineer"
)
wp1 = with_polymorphic(Person, [Manager, Engineer])
subq1 = select(wp1).subquery()
wp2 = with_polymorphic(Person, [Engineer, Manager])
subq2 = select(wp2).subquery()
# first thing we see, is that when we go through with_polymorphic,
# the entities that get placed into the aliased class go through
# Mapper._mappers_from_spec(), which matches them up to the
# existing Mapper.self_and_descendants collection, meaning,
# the order is the same every time. Assert here that's still
# happening. If a future internal change modifies this assumption,
# that's not necessarily bad, but it would change things.
eq_(
subq1.c.keys(),
[
"person_id",
"company_id",
"name",
"type",
"person_id_1",
"status",
"engineer_name",
"primary_language",
"person_id_1",
"status_1",
"manager_name",
],
)
eq_(
subq2.c.keys(),
[
"person_id",
"company_id",
"name",
"type",
"person_id_1",
"status",
"engineer_name",
"primary_language",
"person_id_1",
"status_1",
"manager_name",
],
)
def test_subquery_col_expressions_wpoly_two(self):
Person, Manager, Engineer = self.classes(
"Person", "Manager", "Engineer"
)
wp1 = with_polymorphic(Person, [Manager, Engineer])
subq1 = select(wp1).subquery()
stmt = select(subq1).where(
or_(
subq1.c.engineer_name == "dilbert",
subq1.c.manager_name == "dogbert",
)
)
self.assert_compile(
stmt,
"SELECT anon_1.person_id, anon_1.company_id, anon_1.name, "
"anon_1.type, anon_1.person_id AS person_id_1, anon_1.status, "
"anon_1.engineer_name, anon_1.primary_language, "
"anon_1.person_id AS person_id_2, anon_1.status AS status_1, "
"anon_1.manager_name FROM "
"%s WHERE "
"anon_1.engineer_name = :engineer_name_1 "
"OR anon_1.manager_name = :manager_name_1" % (self.default_punion),
)
class ImplicitWithPolymorphicTest(
_poly_fixtures._PolymorphicUnions, AssertsCompiledSQL
):
"""Test a series of mappers with a very awkward with_polymorphic setting,
that tables and columns are rendered using the selectable in the correct
contexts. PolymorphicUnions represent the most awkward and verbose
polymorphic fixtures you can have. expressions need to be maximally
accurate in terms of the mapped selectable in order to produce correct
queries, which also will be really wrong if that mapped selectable is not
in use.
"""
__dialect__ = "default"
def test_select_columns_where_baseclass(self):
Person = self.classes.Person
stmt = (
select(Person.person_id, Person.name)
.where(Person.name == "some name")
.order_by(Person.person_id)
)
sess = fixture_session()
q = (
sess.query(Person.person_id, Person.name)
.filter(Person.name == "some name")
.order_by(Person.person_id)
)
expected = (
"SELECT pjoin.person_id, pjoin.name FROM "
"(SELECT engineers.person_id AS person_id, people.company_id AS "
"company_id, people.name AS name, people.type AS type, "
"engineers.status AS status, engineers.engineer_name AS "
"engineer_name, engineers.primary_language AS primary_language, "
"CAST(NULL AS VARCHAR(50)) AS manager_name FROM people "
"JOIN engineers ON people.person_id = engineers.person_id "
"UNION ALL SELECT managers.person_id AS person_id, "
"people.company_id AS company_id, people.name AS name, "
"people.type AS type, managers.status AS status, "
"CAST(NULL AS VARCHAR(50)) AS engineer_name, "
"CAST(NULL AS VARCHAR(50)) AS primary_language, "
"managers.manager_name AS manager_name FROM people "
"JOIN managers ON people.person_id = managers.person_id) AS "
"pjoin WHERE pjoin.name = :name_1 ORDER BY pjoin.person_id"
)
self.assert_compile(stmt, expected)
self.assert_compile(
q._final_statement(legacy_query_style=False),
expected,
)
def test_select_where_baseclass(self):
Person = self.classes.Person
stmt = (
select(Person)
.where(Person.name == "some name")
.order_by(Person.person_id)
)
sess = fixture_session()
q = (
sess.query(Person)
.filter(Person.name == "some name")
.order_by(Person.person_id)
)
expected = (
"SELECT pjoin.person_id, pjoin.company_id, pjoin.name, "
"pjoin.type, pjoin.status, pjoin.engineer_name, "
"pjoin.primary_language, pjoin.manager_name FROM "
"(SELECT engineers.person_id AS person_id, people.company_id "
"AS company_id, people.name AS name, people.type AS type, "
"engineers.status AS status, engineers.engineer_name AS "
"engineer_name, engineers.primary_language AS primary_language, "
"CAST(NULL AS VARCHAR(50)) AS manager_name FROM people "
"JOIN engineers ON people.person_id = engineers.person_id "
"UNION ALL SELECT managers.person_id AS person_id, "
"people.company_id AS company_id, people.name AS name, "
"people.type AS type, managers.status AS status, "
"CAST(NULL AS VARCHAR(50)) AS engineer_name, "
"CAST(NULL AS VARCHAR(50)) AS primary_language, "
"managers.manager_name AS manager_name FROM people "
"JOIN managers ON people.person_id = managers.person_id) AS "
"pjoin WHERE pjoin.name = :name_1 ORDER BY pjoin.person_id"
)
self.assert_compile(stmt, expected)
self.assert_compile(
q._final_statement(legacy_query_style=False),
expected,
)
def test_select_where_subclass(self):
Engineer = self.classes.Engineer
# what will *not* work with Core, that the ORM does for now,
# is that if you do where/orderby Person.column, it will de-adapt
# the Person columns from the polymorphic union
stmt = (
select(Engineer)
.where(Engineer.name == "some name")
.order_by(Engineer.person_id)
)
sess = fixture_session()
q = (
sess.query(Engineer)
.filter(Engineer.name == "some name")
.order_by(Engineer.person_id)
)
plain_expected = ( # noqa
"SELECT engineers.person_id, people.person_id, people.company_id, "
"people.name, "
"people.type, engineers.status, "
"engineers.engineer_name, engineers.primary_language "
"FROM people JOIN engineers "
"ON people.person_id = engineers.person_id "
"WHERE people.name = :name_1 ORDER BY engineers.person_id"
)
# when we have disambiguating labels turned on
disambiguate_expected = ( # noqa
"SELECT engineers.person_id, people.person_id AS person_id_1, "
"people.company_id, "
"people.name, "
"people.type, engineers.status, "
"engineers.engineer_name, engineers.primary_language "
"FROM people JOIN engineers "
"ON people.person_id = engineers.person_id "
"WHERE people.name = :name_1 ORDER BY engineers.person_id"
)
# these change based on how we decide to apply labels
# in context.py
self.assert_compile(stmt, disambiguate_expected)
self.assert_compile(
q._final_statement(legacy_query_style=False),
disambiguate_expected,
)
def test_select_where_columns_subclass(self):
Engineer = self.classes.Engineer
# what will *not* work with Core, that the ORM does for now,
# is that if you do where/orderby Person.column, it will de-adapt
# the Person columns from the polymorphic union
# After many attempts to get the JOIN to render, by annotating
# the columns with the "join" that they come from and trying to
# get Select() to render out that join, there's no approach
# that really works without stepping on other assumptions, so
# add select_from(Engineer) explicitly. It's still puzzling why the
# ORM seems to know how to make this decision more effectively
# when the select() has the same amount of information.
stmt = (
select(Engineer.person_id, Engineer.name)
.where(Engineer.name == "some name")
.select_from(Engineer)
.order_by(Engineer.person_id)
)
sess = fixture_session()
q = (
sess.query(Engineer.person_id, Engineer.name)
.filter(Engineer.name == "some name")
.order_by(Engineer.person_id)
)
expected = (
"SELECT engineers.person_id, people.name "
"FROM people JOIN engineers "
"ON people.person_id = engineers.person_id "
"WHERE people.name = :name_1 ORDER BY engineers.person_id"
)
self.assert_compile(stmt, expected)
self.assert_compile(
q._final_statement(legacy_query_style=False),
expected,
)
class RelationshipNaturalInheritedTest(InheritedTest, AssertsCompiledSQL):
__dialect__ = "default"
straight_company_to_person_expected = (
"SELECT companies.company_id, companies.name FROM companies "
"JOIN people ON companies.company_id = people.company_id"
)
default_pjoin = (
"(people LEFT OUTER "
"JOIN engineers ON people.person_id = engineers.person_id "
"LEFT OUTER JOIN managers "
"ON people.person_id = managers.person_id "
"LEFT OUTER JOIN boss ON managers.person_id = boss.boss_id) "
"ON companies.company_id = people.company_id"
)
flat_aliased_pjoin = (
"(people AS people_1 LEFT OUTER JOIN engineers AS "
"engineers_1 ON people_1.person_id = engineers_1.person_id "
"LEFT OUTER JOIN managers AS managers_1 "
"ON people_1.person_id = managers_1.person_id "
"LEFT OUTER JOIN boss AS boss_1 ON "
"managers_1.person_id = boss_1.boss_id) "
"ON companies.company_id = people_1.company_id"
)
aliased_pjoin = (
"(SELECT people.person_id AS people_person_id, people.company_id "
"AS people_company_id, people.name AS people_name, people.type "
"AS people_type, engineers.person_id AS engineers_person_id, "
"engineers.status AS engineers_status, engineers.engineer_name "
"AS engineers_engineer_name, engineers.primary_language "
"AS engineers_primary_language, managers.person_id "
"AS managers_person_id, managers.status AS managers_status, "
"managers.manager_name AS managers_manager_name, "
"boss.boss_id AS boss_boss_id, boss.golf_swing AS boss_golf_swing "
"FROM people LEFT OUTER JOIN engineers ON people.person_id = "
"engineers.person_id LEFT OUTER JOIN managers ON "
"people.person_id = managers.person_id LEFT OUTER JOIN boss "
"ON managers.person_id = boss.boss_id) AS anon_1 "
"ON companies.company_id = anon_1.people_company_id"
)
person_paperwork_expected = (
"SELECT companies.company_id, companies.name FROM companies "
"JOIN people ON companies.company_id = people.company_id "
"JOIN paperwork ON people.person_id = paperwork.person_id"
)
c_to_p_whereclause = (
"SELECT companies.company_id, companies.name FROM companies "
"JOIN people ON companies.company_id = people.company_id "
"WHERE people.name = :name_1"
)
poly_columns = "SELECT people.person_id FROM people"
def test_straight(self):
Company, Person, Manager, Engineer = self.classes(
"Company", "Person", "Manager", "Engineer"
)
stmt1 = select(Company).select_from(
orm_join(Company, Person, Company.employees)
)
stmt2 = select(Company).join(Company.employees)
stmt3 = (
fixture_session()
.query(Company)
.join(Company.employees)
._final_statement(legacy_query_style=False)
)
self.assert_compile(stmt1, self.straight_company_to_person_expected)
self.assert_compile(stmt2, self.straight_company_to_person_expected)
self.assert_compile(stmt3, self.straight_company_to_person_expected)
def test_columns(self):
Company, Person, Manager, Engineer = self.classes(
"Company", "Person", "Manager", "Engineer"
)
stmt = select(Person.person_id)
self.assert_compile(stmt, self.poly_columns)
def test_straight_whereclause(self):
Company, Person, Manager, Engineer = self.classes(
"Company", "Person", "Manager", "Engineer"
)
stmt1 = (
select(Company)
.select_from(orm_join(Company, Person, Company.employees))
.where(Person.name == "ed")
)
stmt2 = (
select(Company).join(Company.employees).where(Person.name == "ed")
)
stmt3 = (
fixture_session()
.query(Company)
.join(Company.employees)
.filter(Person.name == "ed")
._final_statement(legacy_query_style=False)
)
self.assert_compile(stmt1, self.c_to_p_whereclause)
self.assert_compile(stmt2, self.c_to_p_whereclause)
self.assert_compile(stmt3, self.c_to_p_whereclause)
def test_two_level(self):
Company, Person, Paperwork = self.classes(
"Company", "Person", "Paperwork"
)
stmt1 = select(Company).select_from(
orm_join(Company, Person, Company.employees).join(
Paperwork, Person.paperwork
)
)
stmt2 = select(Company).join(Company.employees).join(Person.paperwork)
stmt3 = (
fixture_session()
.query(Company)
.join(Company.employees)
.join(Person.paperwork)
._final_statement(legacy_query_style=False)
)
self.assert_compile(stmt1, self.person_paperwork_expected)
self.assert_compile(stmt2, self.person_paperwork_expected)
self.assert_compile(stmt3, self.person_paperwork_expected)
def test_wpoly_of_type(self):
Company, Person, Manager, Engineer = self.classes(
"Company", "Person", "Manager", "Engineer"
)
p1 = with_polymorphic(Person, "*")
stmt1 = select(Company).select_from(
orm_join(Company, p1, Company.employees.of_type(p1))
)
stmt2 = select(Company).join(Company.employees.of_type(p1))
stmt3 = (
fixture_session()
.query(Company)
.join(Company.employees.of_type(p1))
._final_statement(legacy_query_style=False)
)
expected = (
"SELECT companies.company_id, companies.name "
"FROM companies JOIN %s" % self.default_pjoin
)
self.assert_compile(stmt1, expected)
self.assert_compile(stmt2, expected)
self.assert_compile(stmt3, expected)
def test_wpoly_aliased_of_type(self):
Company, Person, Manager, Engineer = self.classes(
"Company", "Person", "Manager", "Engineer"
)
s = fixture_session()
p1 = with_polymorphic(Person, "*", aliased=True)
stmt1 = select(Company).select_from(
orm_join(Company, p1, Company.employees.of_type(p1))
)
stmt2 = select(Company).join(p1, Company.employees.of_type(p1))
stmt3 = (
s.query(Company)
.join(Company.employees.of_type(p1))
._final_statement(legacy_query_style=False)
)
expected = (
"SELECT companies.company_id, companies.name FROM companies "
"JOIN %s" % self.aliased_pjoin
)
self.assert_compile(stmt1, expected)
self.assert_compile(stmt2, expected)
self.assert_compile(stmt3, expected)
def test_wpoly_aliased_flat_of_type(self):
Company, Person, Manager, Engineer = self.classes(
"Company", "Person", "Manager", "Engineer"
)
p1 = with_polymorphic(Person, "*", aliased=True, flat=True)
stmt1 = select(Company).select_from(
orm_join(Company, p1, Company.employees.of_type(p1))
)
stmt2 = select(Company).join(p1, Company.employees.of_type(p1))
stmt3 = (
fixture_session()
.query(Company)
.join(Company.employees.of_type(p1))
._final_statement(legacy_query_style=False)
)
expected = (
"SELECT companies.company_id, companies.name FROM companies "
"JOIN %s" % self.flat_aliased_pjoin
)
self.assert_compile(stmt1, expected)
self.assert_compile(stmt2, expected)
self.assert_compile(stmt3, expected)
class RelNaturalAliasedJoinsTest(
_poly_fixtures._PolymorphicAliasedJoins, RelationshipNaturalInheritedTest
):
# this is the label style for the polymorphic selectable, not the
# outside query
label_style = LABEL_STYLE_TABLENAME_PLUS_COL
straight_company_to_person_expected = (
"SELECT companies.company_id, companies.name FROM companies "
"JOIN (SELECT people.person_id AS people_person_id, people.company_id "
"AS people_company_id, people.name AS people_name, people.type "
"AS people_type, engineers.person_id AS engineers_person_id, "
"engineers.status AS engineers_status, engineers.engineer_name "
"AS engineers_engineer_name, engineers.primary_language AS "
"engineers_primary_language, managers.person_id AS "
"managers_person_id, managers.status AS managers_status, "
"managers.manager_name AS managers_manager_name FROM people "
"LEFT OUTER JOIN engineers ON people.person_id = "
"engineers.person_id LEFT OUTER JOIN managers ON people.person_id = "
"managers.person_id) AS pjoin ON companies.company_id = "
"pjoin.people_company_id"
)
person_paperwork_expected = (
"SELECT companies.company_id, companies.name FROM companies JOIN "
"(SELECT people.person_id AS people_person_id, people.company_id "
"AS people_company_id, people.name AS people_name, people.type "
"AS people_type, engineers.person_id AS engineers_person_id, "
"engineers.status AS engineers_status, engineers.engineer_name "
"AS engineers_engineer_name, engineers.primary_language AS "
"engineers_primary_language, managers.person_id AS "
"managers_person_id, managers.status AS managers_status, "
"managers.manager_name AS managers_manager_name FROM people "
"LEFT OUTER JOIN engineers ON people.person_id = engineers.person_id "
"LEFT OUTER JOIN managers ON people.person_id = managers.person_id) "
"AS pjoin ON companies.company_id = pjoin.people_company_id "
"JOIN paperwork ON pjoin.people_person_id = paperwork.person_id"
)
default_pjoin = (
"(SELECT people.person_id AS people_person_id, "
"people.company_id AS people_company_id, people.name AS people_name, "
"people.type AS people_type, engineers.person_id AS "
"engineers_person_id, engineers.status AS engineers_status, "
"engineers.engineer_name AS engineers_engineer_name, "
"engineers.primary_language AS engineers_primary_language, "
"managers.person_id AS managers_person_id, managers.status "
"AS managers_status, managers.manager_name AS managers_manager_name "
"FROM people LEFT OUTER JOIN engineers ON people.person_id = "
"engineers.person_id LEFT OUTER JOIN managers "
"ON people.person_id = managers.person_id) AS pjoin "
"ON companies.company_id = pjoin.people_company_id"
)
flat_aliased_pjoin = (
"(SELECT people.person_id AS people_person_id, "
"people.company_id AS people_company_id, people.name AS people_name, "
"people.type AS people_type, engineers.person_id "
"AS engineers_person_id, engineers.status AS engineers_status, "
"engineers.engineer_name AS engineers_engineer_name, "
"engineers.primary_language AS engineers_primary_language, "
"managers.person_id AS managers_person_id, "
"managers.status AS managers_status, managers.manager_name "
"AS managers_manager_name FROM people "
"LEFT OUTER JOIN engineers ON people.person_id = engineers.person_id "
"LEFT OUTER JOIN managers ON people.person_id = managers.person_id) "
"AS pjoin_1 ON companies.company_id = pjoin_1.people_company_id"
)
aliased_pjoin = (
"(SELECT people.person_id AS people_person_id, people.company_id "
"AS people_company_id, people.name AS people_name, "
"people.type AS people_type, engineers.person_id AS "
"engineers_person_id, engineers.status AS engineers_status, "
"engineers.engineer_name AS engineers_engineer_name, "
"engineers.primary_language AS engineers_primary_language, "
"managers.person_id AS managers_person_id, managers.status "
"AS managers_status, managers.manager_name AS managers_manager_name "
"FROM people LEFT OUTER JOIN engineers ON people.person_id = "
"engineers.person_id LEFT OUTER JOIN managers "
"ON people.person_id = managers.person_id) AS pjoin_1 "
"ON companies.company_id = pjoin_1.people_company_id"
)
c_to_p_whereclause = (
"SELECT companies.company_id, companies.name FROM companies "
"JOIN (SELECT people.person_id AS people_person_id, "
"people.company_id AS people_company_id, people.name AS people_name, "
"people.type AS people_type, engineers.person_id AS "
"engineers_person_id, engineers.status AS engineers_status, "
"engineers.engineer_name AS engineers_engineer_name, "
"engineers.primary_language AS engineers_primary_language, "
"managers.person_id AS managers_person_id, managers.status "
"AS managers_status, managers.manager_name AS managers_manager_name "
"FROM people LEFT OUTER JOIN engineers "
"ON people.person_id = engineers.person_id "
"LEFT OUTER JOIN managers ON people.person_id = managers.person_id) "
"AS pjoin ON companies.company_id = pjoin.people_company_id "
"WHERE pjoin.people_name = :people_name_1"
)
poly_columns = (
"SELECT pjoin.people_person_id FROM (SELECT people.person_id AS "
"people_person_id, people.company_id AS people_company_id, "
"people.name AS people_name, people.type AS people_type, "
"engineers.person_id AS engineers_person_id, engineers.status "
"AS engineers_status, engineers.engineer_name AS "
"engineers_engineer_name, engineers.primary_language AS "
"engineers_primary_language, managers.person_id AS "
"managers_person_id, managers.status AS managers_status, "
"managers.manager_name AS managers_manager_name FROM people "
"LEFT OUTER JOIN engineers ON people.person_id = engineers.person_id "
"LEFT OUTER JOIN managers ON people.person_id = managers.person_id) "
"AS pjoin"
)
class RelNaturalAliasedJoinsDisamTest(
_poly_fixtures._PolymorphicAliasedJoins, RelationshipNaturalInheritedTest
):
# this is the label style for the polymorphic selectable, not the
# outside query
label_style = LABEL_STYLE_DISAMBIGUATE_ONLY
straight_company_to_person_expected = (
"SELECT companies.company_id, companies.name FROM companies JOIN "
"(SELECT people.person_id AS person_id, "
"people.company_id AS company_id, people.name AS name, "
"people.type AS type, engineers.person_id AS person_id_1, "
"engineers.status AS status, "
"engineers.engineer_name AS engineer_name, "
"engineers.primary_language AS primary_language, "
"managers.person_id AS person_id_2, managers.status AS status_1, "
"managers.manager_name AS manager_name FROM people "
"LEFT OUTER JOIN engineers ON people.person_id = engineers.person_id "
"LEFT OUTER JOIN managers ON people.person_id = managers.person_id) "
"AS pjoin ON companies.company_id = pjoin.company_id"
)
person_paperwork_expected = (
"SELECT companies.company_id, companies.name FROM companies "
"JOIN (SELECT people.person_id AS person_id, people.company_id "
"AS company_id, people.name AS name, people.type AS type, "
"engineers.person_id AS person_id_1, engineers.status AS status, "
"engineers.engineer_name AS engineer_name, "
"engineers.primary_language AS primary_language, managers.person_id "
"AS person_id_2, managers.status AS status_1, managers.manager_name "
"AS manager_name FROM people LEFT OUTER JOIN engineers "
"ON people.person_id = engineers.person_id "
"LEFT OUTER JOIN managers ON people.person_id = managers.person_id) "
"AS pjoin ON companies.company_id = pjoin.company_id "
"JOIN paperwork ON pjoin.person_id = paperwork.person_id"
)
default_pjoin = (
"(SELECT people.person_id AS person_id, people.company_id AS "
"company_id, people.name AS name, people.type AS type, "
"engineers.person_id AS person_id_1, engineers.status AS status, "
"engineers.engineer_name AS engineer_name, engineers.primary_language "
"AS primary_language, managers.person_id AS person_id_2, "
"managers.status AS status_1, managers.manager_name AS manager_name "
"FROM people LEFT OUTER JOIN engineers ON people.person_id = "
"engineers.person_id LEFT OUTER JOIN managers ON people.person_id = "
"managers.person_id) AS pjoin "
"ON companies.company_id = pjoin.company_id"
)
flat_aliased_pjoin = (
"(SELECT people.person_id AS person_id, people.company_id AS "
"company_id, people.name AS name, people.type AS type, "
"engineers.person_id AS person_id_1, engineers.status AS status, "
"engineers.engineer_name AS engineer_name, "
"engineers.primary_language AS primary_language, "
"managers.person_id AS person_id_2, managers.status AS status_1, "
"managers.manager_name AS manager_name FROM people "
"LEFT OUTER JOIN engineers ON people.person_id = engineers.person_id "
"LEFT OUTER JOIN managers ON people.person_id = managers.person_id) "
"AS pjoin_1 ON companies.company_id = pjoin_1.company_id"
)
aliased_pjoin = (
"(SELECT people.person_id AS person_id, people.company_id AS "
"company_id, people.name AS name, people.type AS type, "
"engineers.person_id AS person_id_1, engineers.status AS status, "
"engineers.engineer_name AS engineer_name, engineers.primary_language "
"AS primary_language, managers.person_id AS person_id_2, "
"managers.status AS status_1, managers.manager_name AS manager_name "
"FROM people LEFT OUTER JOIN engineers ON people.person_id = "
"engineers.person_id LEFT OUTER JOIN managers ON people.person_id = "
"managers.person_id) AS pjoin_1 "
"ON companies.company_id = pjoin_1.company_id"
)
c_to_p_whereclause = (
"SELECT companies.company_id, companies.name FROM companies JOIN "
"(SELECT people.person_id AS person_id, "
"people.company_id AS company_id, people.name AS name, "
"people.type AS type, engineers.person_id AS person_id_1, "
"engineers.status AS status, "
"engineers.engineer_name AS engineer_name, "
"engineers.primary_language AS primary_language, "
"managers.person_id AS person_id_2, managers.status AS status_1, "
"managers.manager_name AS manager_name FROM people "
"LEFT OUTER JOIN engineers ON people.person_id = engineers.person_id "
"LEFT OUTER JOIN managers ON people.person_id = managers.person_id) "
"AS pjoin ON companies.company_id = pjoin.company_id "
"WHERE pjoin.name = :name_1"
)
poly_columns = (
"SELECT pjoin.person_id FROM (SELECT people.person_id AS "
"person_id, people.company_id AS company_id, people.name AS name, "
"people.type AS type, engineers.person_id AS person_id_1, "
"engineers.status AS status, "
"engineers.engineer_name AS engineer_name, "
"engineers.primary_language AS primary_language, "
"managers.person_id AS person_id_2, "
"managers.status AS status_1, managers.manager_name AS manager_name "
"FROM people LEFT OUTER JOIN engineers "
"ON people.person_id = engineers.person_id "
"LEFT OUTER JOIN managers "
"ON people.person_id = managers.person_id) AS pjoin"
)
class RawSelectTest(QueryTest, AssertsCompiledSQL):
"""older tests from test_query. Here, they are converted to use
future selects with ORM compilation.
"""
__dialect__ = "default"
def test_select_from_entity(self):
User = self.classes.User
self.assert_compile(
select(literal_column("*")).select_from(User),
"SELECT * FROM users",
)
def test_where_relationship(self):
User = self.classes.User
stmt1 = select(User).where(User.addresses)
stmt2 = (
fixture_session()
.query(User)
.filter(User.addresses)
._final_statement(legacy_query_style=False)
)
expected = (
"SELECT users.id, users.name FROM users, addresses "
"WHERE users.id = addresses.user_id"
)
self.assert_compile(stmt1, expected)
self.assert_compile(stmt2, expected)
def test_where_m2m_relationship(self):
Item = self.classes.Item
expected = (
"SELECT items.id, items.description FROM items, "
"item_keywords AS item_keywords_1, keywords "
"WHERE items.id = item_keywords_1.item_id "
"AND keywords.id = item_keywords_1.keyword_id"
)
stmt1 = select(Item).where(Item.keywords)
stmt2 = (
fixture_session()
.query(Item)
.filter(Item.keywords)
._final_statement(legacy_query_style=False)
)
self.assert_compile(stmt1, expected)
self.assert_compile(stmt2, expected)
def test_inline_select_from_entity(self):
User = self.classes.User
expected = "SELECT * FROM users"
stmt1 = select(literal_column("*")).select_from(User)
stmt2 = (
fixture_session()
.query(literal_column("*"))
.select_from(User)
._final_statement(legacy_query_style=False)
)
self.assert_compile(stmt1, expected)
self.assert_compile(stmt2, expected)
def test_select_from_aliased_entity(self):
User = self.classes.User
ua = aliased(User, name="ua")
stmt1 = select(literal_column("*")).select_from(ua)
stmt2 = (
fixture_session()
.query(literal_column("*"))
.select_from(ua)
._final_statement(legacy_query_style=False)
)
expected = "SELECT * FROM users AS ua"
self.assert_compile(stmt1, expected)
self.assert_compile(stmt2, expected)
def test_correlate_entity(self):
User = self.classes.User
Address = self.classes.Address
expected = (
"SELECT users.name, addresses.id, "
"(SELECT count(addresses.id) AS count_1 "
"FROM addresses WHERE users.id = addresses.user_id) AS anon_1 "
"FROM users, addresses"
)
stmt1 = select(
User.name,
Address.id,
select(func.count(Address.id))
.where(User.id == Address.user_id)
.correlate(User)
.scalar_subquery(),
)
stmt2 = (
fixture_session()
.query(
User.name,
Address.id,
select(func.count(Address.id))
.where(User.id == Address.user_id)
.correlate(User)
.scalar_subquery(),
)
._final_statement(legacy_query_style=False)
)
self.assert_compile(stmt1, expected)
self.assert_compile(stmt2, expected)
def test_correlate_aliased_entity(self):
User = self.classes.User
Address = self.classes.Address
uu = aliased(User, name="uu")
stmt1 = select(
uu.name,
Address.id,
select(func.count(Address.id))
.where(uu.id == Address.user_id)
.correlate(uu)
.scalar_subquery(),
)
stmt2 = (
fixture_session()
.query(
uu.name,
Address.id,
select(func.count(Address.id))
.where(uu.id == Address.user_id)
.correlate(uu)
.scalar_subquery(),
)
._final_statement(legacy_query_style=False)
)
expected = (
"SELECT uu.name, addresses.id, "
"(SELECT count(addresses.id) AS count_1 "
"FROM addresses WHERE uu.id = addresses.user_id) AS anon_1 "
"FROM users AS uu, addresses"
)
self.assert_compile(stmt1, expected)
self.assert_compile(stmt2, expected)
def test_columns_clause_entity(self):
User = self.classes.User
expected = "SELECT users.id, users.name FROM users"
stmt1 = select(User)
stmt2 = (
fixture_session()
.query(User)
._final_statement(legacy_query_style=False)
)
self.assert_compile(stmt1, expected)
self.assert_compile(stmt2, expected)
def test_columns_clause_columns(self):
User = self.classes.User
expected = "SELECT users.id, users.name FROM users"
stmt1 = select(User.id, User.name)
stmt2 = (
fixture_session()
.query(User.id, User.name)
._final_statement(legacy_query_style=False)
)
self.assert_compile(stmt1, expected)
self.assert_compile(stmt2, expected)
def test_columns_clause_aliased_columns(self):
User = self.classes.User
ua = aliased(User, name="ua")
stmt1 = select(ua.id, ua.name)
stmt2 = (
fixture_session()
.query(ua.id, ua.name)
._final_statement(legacy_query_style=False)
)
expected = "SELECT ua.id, ua.name FROM users AS ua"
self.assert_compile(stmt1, expected)
self.assert_compile(stmt2, expected)
def test_columns_clause_aliased_entity(self):
User = self.classes.User
ua = aliased(User, name="ua")
stmt1 = select(ua)
stmt2 = (
fixture_session()
.query(ua)
._final_statement(legacy_query_style=False)
)
expected = "SELECT ua.id, ua.name FROM users AS ua"
self.assert_compile(stmt1, expected)
self.assert_compile(stmt2, expected)
def test_core_join_in_select_from_no_onclause(self):
User = self.classes.User
Address = self.classes.Address
self.assert_compile(
select(User).select_from(core_join(User, Address)),
"SELECT users.id, users.name FROM users "
"JOIN addresses ON users.id = addresses.user_id",
)
def test_join_to_entity_no_onclause(self):
User = self.classes.User
Address = self.classes.Address
self.assert_compile(
select(User).join(Address),
"SELECT users.id, users.name FROM users "
"JOIN addresses ON users.id = addresses.user_id",
)
def test_insert_from_query(self):
User = self.classes.User
Address = self.classes.Address
s = fixture_session()
q = s.query(User.id, User.name).filter_by(name="ed")
self.assert_compile(
insert(Address).from_select(("id", "email_address"), q),
"INSERT INTO addresses (id, email_address) "
"SELECT users.id AS users_id, users.name AS users_name "
"FROM users WHERE users.name = :name_1",
)
def test_insert_from_query_col_attr(self):
User = self.classes.User
Address = self.classes.Address
s = fixture_session()
q = s.query(User.id, User.name).filter_by(name="ed")
self.assert_compile(
insert(Address).from_select(
(Address.id, Address.email_address), q
),
"INSERT INTO addresses (id, email_address) "
"SELECT users.id AS users_id, users.name AS users_name "
"FROM users WHERE users.name = :name_1",
)
def test_update_from_entity(self):
from sqlalchemy.sql import update
User = self.classes.User
self.assert_compile(
update(User), "UPDATE users SET id=:id, name=:name"
)
self.assert_compile(
update(User).values(name="ed").where(User.id == 5),
"UPDATE users SET name=:name WHERE users.id = :id_1",
checkparams={"id_1": 5, "name": "ed"},
)
self.assert_compile(
update(User).values({User.name: "ed"}).where(User.id == 5),
"UPDATE users SET name=:name WHERE users.id = :id_1",
checkparams={"id_1": 5, "name": "ed"},
)
def test_delete_from_entity(self):
from sqlalchemy.sql import delete
User = self.classes.User
self.assert_compile(delete(User), "DELETE FROM users")
self.assert_compile(
delete(User).where(User.id == 5),
"DELETE FROM users WHERE users.id = :id_1",
checkparams={"id_1": 5},
)
def test_insert_from_entity(self):
from sqlalchemy.sql import insert
User = self.classes.User
self.assert_compile(
insert(User), "INSERT INTO users (id, name) VALUES (:id, :name)"
)
self.assert_compile(
insert(User).values(name="ed"),
"INSERT INTO users (name) VALUES (:name)",
checkparams={"name": "ed"},
)
def test_col_prop_builtin_function(self):
class Foo:
pass
self.mapper_registry.map_imperatively(
Foo,
self.tables.users,
properties={
"foob": column_property(
func.coalesce(self.tables.users.c.name)
)
},
)
stmt1 = select(Foo).where(Foo.foob == "somename").order_by(Foo.foob)
stmt2 = (
fixture_session()
.query(Foo)
.filter(Foo.foob == "somename")
.order_by(Foo.foob)
._final_statement(legacy_query_style=False)
)
expected = (
"SELECT coalesce(users.name) AS coalesce_1, "
"users.id, users.name FROM users "
"WHERE coalesce(users.name) = :param_1 "
"ORDER BY coalesce_1"
)
self.assert_compile(stmt1, expected)
self.assert_compile(stmt2, expected)
class CorrelateTest(fixtures.DeclarativeMappedTest, _CoreCorrelateTest):
@classmethod
def setup_classes(cls):
Base = cls.DeclarativeBasic
class T1(Base):
__tablename__ = "t1"
a = Column(Integer, primary_key=True)
@hybridproperty
def c(self):
return self
class T2(Base):
__tablename__ = "t2"
a = Column(Integer, primary_key=True)
@hybridproperty
def c(self):
return self
def _fixture(self):
t1, t2 = self.classes("T1", "T2")
return t1, t2, select(t1).where(t1.c.a == t2.c.a)
class CrudParamOverlapTest(test_compiler.CrudParamOverlapTest):
@testing.fixture(
params=Variation.generate_cases("type_", ["orm"]),
ids=["orm"],
)
def crud_table_fixture(self, request):
type_ = request.param
if type_.orm:
from sqlalchemy.orm import declarative_base
Base = declarative_base()
class Foo(Base):
__tablename__ = "mytable"
myid = Column(Integer, primary_key=True)
name = Column(String)
description = Column(String)
table1 = Foo
else:
type_.fail()
yield table1
|