1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
|
"""Test various algorithmic properties of selectables."""
from itertools import zip_longest
from sqlalchemy import and_
from sqlalchemy import bindparam
from sqlalchemy import Boolean
from sqlalchemy import cast
from sqlalchemy import Column
from sqlalchemy import delete
from sqlalchemy import exc
from sqlalchemy import exists
from sqlalchemy import false
from sqlalchemy import ForeignKey
from sqlalchemy import func
from sqlalchemy import insert
from sqlalchemy import Integer
from sqlalchemy import join
from sqlalchemy import literal_column
from sqlalchemy import MetaData
from sqlalchemy import not_
from sqlalchemy import null
from sqlalchemy import or_
from sqlalchemy import outerjoin
from sqlalchemy import select
from sqlalchemy import Sequence
from sqlalchemy import String
from sqlalchemy import Table
from sqlalchemy import testing
from sqlalchemy import text
from sqlalchemy import true
from sqlalchemy import type_coerce
from sqlalchemy import TypeDecorator
from sqlalchemy import union
from sqlalchemy import update
from sqlalchemy import util
from sqlalchemy.sql import Alias
from sqlalchemy.sql import annotation
from sqlalchemy.sql import base
from sqlalchemy.sql import column
from sqlalchemy.sql import elements
from sqlalchemy.sql import LABEL_STYLE_DISAMBIGUATE_ONLY
from sqlalchemy.sql import LABEL_STYLE_TABLENAME_PLUS_COL
from sqlalchemy.sql import operators
from sqlalchemy.sql import table
from sqlalchemy.sql import util as sql_util
from sqlalchemy.sql import visitors
from sqlalchemy.sql.dml import Insert
from sqlalchemy.sql.selectable import LABEL_STYLE_NONE
from sqlalchemy.testing import assert_raises
from sqlalchemy.testing import assert_raises_message
from sqlalchemy.testing import AssertsCompiledSQL
from sqlalchemy.testing import AssertsExecutionResults
from sqlalchemy.testing import config
from sqlalchemy.testing import eq_
from sqlalchemy.testing import fixtures
from sqlalchemy.testing import in_
from sqlalchemy.testing import is_
from sqlalchemy.testing import is_not
from sqlalchemy.testing import ne_
from sqlalchemy.testing.assertions import expect_raises_message
from sqlalchemy.testing.provision import normalize_sequence
metadata = MetaData()
table1 = Table(
"table1",
metadata,
Column("col1", Integer, primary_key=True),
Column("col2", String(20)),
Column("col3", Integer),
Column("colx", Integer),
)
table2 = Table(
"table2",
metadata,
Column("col1", Integer, primary_key=True),
Column("col2", Integer, ForeignKey("table1.col1")),
Column("col3", String(20)),
Column("coly", Integer),
)
keyed = Table(
"keyed",
metadata,
Column("x", Integer, key="colx"),
Column("y", Integer, key="coly"),
Column("z", Integer),
)
class SelectableTest(
fixtures.TestBase, AssertsExecutionResults, AssertsCompiledSQL
):
__dialect__ = "default"
@testing.combinations(
(
(table1.c.col1, table1.c.col2),
[
{
"name": "col1",
"type": table1.c.col1.type,
"expr": table1.c.col1,
},
{
"name": "col2",
"type": table1.c.col2.type,
"expr": table1.c.col2,
},
],
),
(
(table1,),
[
{
"name": "col1",
"type": table1.c.col1.type,
"expr": table1.c.col1,
},
{
"name": "col2",
"type": table1.c.col2.type,
"expr": table1.c.col2,
},
{
"name": "col3",
"type": table1.c.col3.type,
"expr": table1.c.col3,
},
{
"name": "colx",
"type": table1.c.colx.type,
"expr": table1.c.colx,
},
],
),
(
(func.count(table1.c.col1),),
[
{
"name": "count",
"type": testing.eq_type_affinity(Integer),
"expr": testing.eq_clause_element(
func.count(table1.c.col1)
),
}
],
),
(
(func.count(table1.c.col1), func.count(table1.c.col2)),
[
{
"name": "count",
"type": testing.eq_type_affinity(Integer),
"expr": testing.eq_clause_element(
func.count(table1.c.col1)
),
},
{
"name": "count_1",
"type": testing.eq_type_affinity(Integer),
"expr": testing.eq_clause_element(
func.count(table1.c.col2)
),
},
],
),
)
def test_core_column_descriptions(self, cols, expected):
stmt = select(*cols)
# reverse eq_ is so eq_clause_element works
eq_(expected, stmt.column_descriptions)
@testing.combinations(insert, update, delete, argnames="dml_construct")
@testing.combinations(
(
table1,
(table1.c.col1, table1.c.col2),
{"name": "table1", "table": table1},
[
{
"name": "col1",
"type": table1.c.col1.type,
"expr": table1.c.col1,
},
{
"name": "col2",
"type": table1.c.col2.type,
"expr": table1.c.col2,
},
],
),
(
table1,
(func.count(table1.c.col1),),
{"name": "table1", "table": table1},
[
{
"name": None,
"type": testing.eq_type_affinity(Integer),
"expr": testing.eq_clause_element(
func.count(table1.c.col1)
),
},
],
),
(
table1,
None,
{"name": "table1", "table": table1},
[],
),
(
table1.alias("some_alias"),
None,
{
"name": "some_alias",
"table": testing.eq_clause_element(table1.alias("some_alias")),
},
[],
),
(
table1.join(table2),
None,
{
"name": None,
"table": testing.eq_clause_element(table1.join(table2)),
},
[],
),
argnames="entity, cols, expected_entity, expected_returning",
)
def test_dml_descriptions(
self, dml_construct, entity, cols, expected_entity, expected_returning
):
stmt = dml_construct(entity)
if cols:
stmt = stmt.returning(*cols)
eq_(stmt.entity_description, expected_entity)
eq_(expected_returning, stmt.returning_column_descriptions)
def test_indirect_correspondence_on_labels(self):
# this test depends upon 'distance' to
# get the right result
# same column three times
s = select(
table1.c.col1.label("c2"),
table1.c.col1,
table1.c.col1.label("c1"),
).subquery()
# this tests the same thing as
# test_direct_correspondence_on_labels below -
# that the presence of label() affects the 'distance'
assert s.corresponding_column(table1.c.col1) is s.c.col1
assert s.corresponding_column(s.c.col1) is s.c.col1
assert s.corresponding_column(s.c.c1) is s.c.c1
def test_labeled_select_twice(self):
scalar_select = select(table1.c.col1).label("foo")
s1 = select(scalar_select)
s2 = select(scalar_select, scalar_select)
eq_(
s1.selected_columns.foo.proxy_set,
{s1.selected_columns.foo, scalar_select, scalar_select.element},
)
eq_(
s2.selected_columns.foo.proxy_set,
{s2.selected_columns.foo, scalar_select, scalar_select.element},
)
assert (
s1.corresponding_column(scalar_select) is s1.selected_columns.foo
)
assert (
s2.corresponding_column(scalar_select) is s2.selected_columns.foo
)
def test_labeled_subquery_twice(self):
scalar_select = select(table1.c.col1).label("foo")
s1 = select(scalar_select).subquery()
s2 = select(scalar_select, scalar_select).subquery()
eq_(
s1.c.foo.proxy_set,
{s1.c.foo, scalar_select, scalar_select.element},
)
eq_(
s2.c.foo.proxy_set,
{s2.c.foo, scalar_select, scalar_select.element},
)
assert s1.corresponding_column(scalar_select) is s1.c.foo
assert s2.corresponding_column(scalar_select) is s2.c.foo
def test_labels_name_w_separate_key(self):
label = select(table1.c.col1).label("foo")
label.key = "bar"
s1 = select(label)
assert s1.corresponding_column(label) is s1.selected_columns.bar
# renders as foo
self.assert_compile(
s1, "SELECT (SELECT table1.col1 FROM table1) AS foo"
)
@testing.combinations(("cte",), ("subquery",), argnames="type_")
@testing.combinations(
("onelevel",), ("twolevel",), ("middle",), argnames="path"
)
@testing.combinations((True,), (False,), argnames="require_embedded")
def test_subquery_cte_correspondence(self, type_, require_embedded, path):
stmt = select(table1)
if type_ == "cte":
cte1 = stmt.cte()
elif type_ == "subquery":
cte1 = stmt.subquery()
if path == "onelevel":
is_(
cte1.corresponding_column(
table1.c.col1, require_embedded=require_embedded
),
cte1.c.col1,
)
elif path == "twolevel":
cte2 = cte1.alias()
is_(
cte2.corresponding_column(
table1.c.col1, require_embedded=require_embedded
),
cte2.c.col1,
)
elif path == "middle":
cte2 = cte1.alias()
is_(
cte2.corresponding_column(
cte1.c.col1, require_embedded=require_embedded
),
cte2.c.col1,
)
def test_labels_anon_w_separate_key(self):
label = select(table1.c.col1).label(None)
label.key = "bar"
s1 = select(label)
# .bar is there
assert s1.corresponding_column(label) is s1.selected_columns.bar
# renders as anon_1
self.assert_compile(
s1, "SELECT (SELECT table1.col1 FROM table1) AS anon_1"
)
def test_labels_anon_w_separate_key_subquery(self):
label = select(table1.c.col1).label(None)
label.key = label._tq_key_label = "bar"
s1 = select(label)
subq = s1.subquery()
s2 = select(subq).where(subq.c.bar > 5)
self.assert_compile(
s2,
"SELECT anon_2.anon_1 FROM (SELECT (SELECT table1.col1 "
"FROM table1) AS anon_1) AS anon_2 "
"WHERE anon_2.anon_1 > :param_1",
checkparams={"param_1": 5},
)
def test_labels_anon_generate_binds_subquery(self):
label = select(table1.c.col1).label(None)
label.key = label._tq_key_label = "bar"
s1 = select(label)
subq = s1.subquery()
s2 = select(subq).where(subq.c[0] > 5)
self.assert_compile(
s2,
"SELECT anon_2.anon_1 FROM (SELECT (SELECT table1.col1 "
"FROM table1) AS anon_1) AS anon_2 "
"WHERE anon_2.anon_1 > :param_1",
checkparams={"param_1": 5},
)
@testing.combinations((True,), (False,))
def test_broken_select_same_named_explicit_cols(self, use_anon):
"""test for #6090. the query is "wrong" and we dont know how
# to render this right now.
"""
stmt = select(
table1.c.col1,
table1.c.col2,
literal_column("col2").label(None if use_anon else "col2"),
).select_from(table1)
if use_anon:
self.assert_compile(
select(stmt.subquery()),
"SELECT anon_1.col1, anon_1.col2, anon_1.col2_1 FROM "
"(SELECT table1.col1 AS col1, table1.col2 AS col2, "
"col2 AS col2_1 FROM table1) AS anon_1",
)
else:
# the keys here are not critical as they are not what was
# requested anyway, maybe should raise here also.
eq_(stmt.selected_columns.keys(), ["col1", "col2", "col2_1"])
with expect_raises_message(
exc.InvalidRequestError,
"Label name col2 is being renamed to an anonymous "
"label due to "
"disambiguation which is not supported right now. Please use "
"unique names for explicit labels.",
):
select(stmt.subquery()).compile()
def test_same_anon_named_explicit_cols(self):
"""test for #8569. This adjusts the change in #6090 to not apply
to anonymous labels.
"""
lc = literal_column("col2").label(None)
subq1 = select(lc).subquery()
stmt2 = select(subq1, lc).subquery()
self.assert_compile(
select(stmt2),
"SELECT anon_1.col2_1, anon_1.col2_1_1 FROM "
"(SELECT anon_2.col2_1 AS col2_1, col2 AS col2_1 FROM "
"(SELECT col2 AS col2_1) AS anon_2) AS anon_1",
)
def test_correlate_none_arg_error(self):
stmt = select(table1)
with expect_raises_message(
exc.ArgumentError,
"additional FROM objects not accepted when passing "
"None/False to correlate",
):
stmt.correlate(None, table2)
def test_correlate_except_none_arg_error(self):
stmt = select(table1)
with expect_raises_message(
exc.ArgumentError,
"additional FROM objects not accepted when passing "
"None/False to correlate_except",
):
stmt.correlate_except(None, table2)
def test_select_label_grouped_still_corresponds(self):
label = select(table1.c.col1).label("foo")
label2 = label.self_group()
s1 = select(label)
s2 = select(label2)
assert s1.corresponding_column(label) is s1.selected_columns.foo
assert s2.corresponding_column(label) is s2.selected_columns.foo
def test_subquery_label_grouped_still_corresponds(self):
label = select(table1.c.col1).label("foo")
label2 = label.self_group()
s1 = select(label).subquery()
s2 = select(label2).subquery()
assert s1.corresponding_column(label) is s1.c.foo
assert s2.corresponding_column(label) is s2.c.foo
def test_direct_correspondence_on_labels(self):
# this test depends on labels being part
# of the proxy set to get the right result
l1, l2 = table1.c.col1.label("foo"), table1.c.col1.label("bar")
sel = select(l1, l2)
sel2 = sel.alias()
assert sel2.corresponding_column(l1) is sel2.c.foo
assert sel2.corresponding_column(l2) is sel2.c.bar
sel2 = select(table1.c.col1.label("foo"), table1.c.col2.label("bar"))
sel3 = sel.union(sel2).alias()
assert sel3.corresponding_column(l1) is sel3.c.foo
assert sel3.corresponding_column(l2) is sel3.c.bar
def test_keyed_gen(self):
s = select(keyed)
eq_(s.selected_columns.colx.key, "colx")
eq_(s.selected_columns.colx.name, "x")
assert (
s.selected_columns.corresponding_column(keyed.c.colx)
is s.selected_columns.colx
)
assert (
s.selected_columns.corresponding_column(keyed.c.coly)
is s.selected_columns.coly
)
assert (
s.selected_columns.corresponding_column(keyed.c.z)
is s.selected_columns.z
)
sel2 = s.alias()
assert sel2.corresponding_column(keyed.c.colx) is sel2.c.colx
assert sel2.corresponding_column(keyed.c.coly) is sel2.c.coly
assert sel2.corresponding_column(keyed.c.z) is sel2.c.z
def test_keyed_label_gen(self):
s = select(keyed).set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
assert (
s.selected_columns.corresponding_column(keyed.c.colx)
is s.selected_columns.keyed_colx
)
assert (
s.selected_columns.corresponding_column(keyed.c.coly)
is s.selected_columns.keyed_coly
)
assert (
s.selected_columns.corresponding_column(keyed.c.z)
is s.selected_columns.keyed_z
)
sel2 = s.alias()
assert sel2.corresponding_column(keyed.c.colx) is sel2.c.keyed_colx
assert sel2.corresponding_column(keyed.c.coly) is sel2.c.keyed_coly
assert sel2.corresponding_column(keyed.c.z) is sel2.c.keyed_z
def test_keyed_c_collection_upper(self):
c = Column("foo", Integer, key="bar")
t = Table("t", MetaData(), c)
is_(t.c.bar, c)
def test_keyed_c_collection_lower(self):
c = column("foo")
c.key = "bar"
t = table("t", c)
is_(t.c.bar, c)
def test_clone_c_proxy_key_upper(self):
c = Column("foo", Integer, key="bar")
t = Table("t", MetaData(), c)
s = select(t)._clone()
assert c in s.selected_columns.bar.proxy_set
s = select(t).subquery()._clone()
assert c in s.c.bar.proxy_set
def test_clone_c_proxy_key_lower(self):
c = column("foo")
c.key = "bar"
t = table("t", c)
s = select(t)._clone()
assert c in s.selected_columns.bar.proxy_set
s = select(t).subquery()._clone()
assert c in s.c.bar.proxy_set
def test_no_error_on_unsupported_expr_key(self):
from sqlalchemy.sql.expression import BinaryExpression
def myop(x, y):
pass
t = table("t", column("x"), column("y"))
expr = BinaryExpression(t.c.x, t.c.y, myop)
s = select(t, expr)
# anon_label, e.g. a truncated_label, is used here because
# the expr has no name, no key, and myop() can't create a
# string, so this is the last resort
eq_(s.selected_columns.keys(), ["x", "y", "_no_label"])
s = select(t, expr).subquery()
eq_(s.c.keys(), ["x", "y", "_no_label"])
def test_cloned_intersection(self):
t1 = table("t1", column("x"))
t2 = table("t2", column("x"))
s1 = t1.select()
s2 = t2.select()
s3 = t1.select()
s1c1 = s1._clone()
s1c2 = s1._clone()
s2c1 = s2._clone()
s3c1 = s3._clone()
eq_(base._cloned_intersection([s1c1, s3c1], [s2c1, s1c2]), {s1c1})
def test_cloned_difference(self):
t1 = table("t1", column("x"))
t2 = table("t2", column("x"))
s1 = t1.select()
s2 = t2.select()
s3 = t1.select()
s1c1 = s1._clone()
s1c2 = s1._clone()
s2c1 = s2._clone()
s3c1 = s3._clone()
eq_(
base._cloned_difference([s1c1, s2c1, s3c1], [s2c1, s1c2]),
{s3c1},
)
def test_distance_on_aliases(self):
a1 = table1.alias("a1")
for s in (
select(a1, table1)
.set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
.subquery(),
select(table1, a1)
.set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
.subquery(),
):
assert s.corresponding_column(table1.c.col1) is s.c.table1_col1
assert s.corresponding_column(a1.c.col1) is s.c.a1_col1
def test_join_against_self(self):
jj = select(table1.c.col1.label("bar_col1")).subquery()
jjj = join(table1, jj, table1.c.col1 == jj.c.bar_col1)
# test column directly against itself
# joins necessarily have to prefix column names with the name
# of the selectable, else the same-named columns will overwrite
# one another. In this case, we unfortunately have this
# unfriendly "anonymous" name, whereas before when select() could
# be a FROM the "bar_col1" label would be directly in the join()
# object. However this was a useless join() object because PG and
# MySQL don't accept unnamed subqueries in joins in any case.
name = "%s_bar_col1" % (jj.name,)
assert jjj.corresponding_column(jjj.c.table1_col1) is jjj.c.table1_col1
assert jjj.corresponding_column(jj.c.bar_col1) is jjj.c[name]
# test alias of the join
j2 = (
jjj.select()
.set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
.subquery("foo")
)
assert j2.corresponding_column(table1.c.col1) is j2.c.table1_col1
def test_clone_append_column(self):
sel = select(literal_column("1").label("a"))
eq_(list(sel.selected_columns.keys()), ["a"])
cloned = visitors.ReplacingCloningVisitor().traverse(sel)
cloned.add_columns.non_generative(
cloned, literal_column("2").label("b")
)
cloned.add_columns.non_generative(cloned, func.foo())
eq_(list(cloned.selected_columns.keys()), ["a", "b", "foo"])
def test_clone_col_list_changes_then_proxy(self):
t = table("t", column("q"), column("p"))
stmt = select(t.c.q).subquery()
def add_column(stmt):
stmt.add_columns.non_generative(stmt, t.c.p)
stmt2 = visitors.cloned_traverse(stmt, {}, {"select": add_column})
eq_(list(stmt.c.keys()), ["q"])
eq_(list(stmt2.c.keys()), ["q", "p"])
def test_clone_col_list_changes_then_schema_proxy(self):
t = Table("t", MetaData(), Column("q", Integer), Column("p", Integer))
stmt = select(t.c.q).subquery()
def add_column(stmt):
stmt.add_columns.non_generative(stmt, t.c.p)
stmt2 = visitors.cloned_traverse(stmt, {}, {"select": add_column})
eq_(list(stmt.c.keys()), ["q"])
eq_(list(stmt2.c.keys()), ["q", "p"])
@testing.combinations(
func.now(), null(), true(), false(), literal_column("10"), column("x")
)
def test_const_object_correspondence(self, c):
"""test #7154"""
stmt = select(c).subquery()
stmt2 = select(stmt)
is_(
stmt2.selected_columns.corresponding_column(c),
stmt2.selected_columns[0],
)
def test_append_column_after_visitor_replace(self):
# test for a supported idiom that matches the deprecated / removed
# replace_selectable method
basesel = select(literal_column("1").label("a"))
tojoin = select(
literal_column("1").label("a"), literal_column("2").label("b")
)
basefrom = basesel.alias("basefrom")
joinfrom = tojoin.alias("joinfrom")
sel = select(basefrom.c.a)
replace_from = basefrom.join(joinfrom, basefrom.c.a == joinfrom.c.a)
def replace(elem):
if elem is basefrom:
return replace_from
replaced = visitors.replacement_traverse(sel, {}, replace)
self.assert_compile(
replaced,
"SELECT basefrom.a FROM (SELECT 1 AS a) AS basefrom "
"JOIN (SELECT 1 AS a, 2 AS b) AS joinfrom "
"ON basefrom.a = joinfrom.a",
)
replaced.selected_columns
replaced.add_columns.non_generative(replaced, joinfrom.c.b)
self.assert_compile(
replaced,
"SELECT basefrom.a, joinfrom.b FROM (SELECT 1 AS a) AS basefrom "
"JOIN (SELECT 1 AS a, 2 AS b) AS joinfrom "
"ON basefrom.a = joinfrom.a",
)
@testing.combinations(
("_internal_subquery",),
("selected_columns",),
("_all_selected_columns"),
)
def test_append_column_after_legacy_subq(self, attr):
"""test :ticket:`6261`"""
t1 = table("t1", column("a"), column("b"))
s1 = select(t1.c.a)
if attr == "selected_columns":
s1.selected_columns
elif attr == "_internal_subuqery":
with testing.expect_deprecated("The SelectBase.c"):
s1.c
elif attr == "_all_selected_columns":
s1._all_selected_columns
s1.add_columns.non_generative(s1, t1.c.b)
self.assert_compile(s1, "SELECT t1.a, t1.b FROM t1")
def test_against_cloned_non_table(self):
# test that corresponding column digs across
# clone boundaries with anonymous labeled elements
col = func.count().label("foo")
sel = select(col).subquery()
sel2 = visitors.ReplacingCloningVisitor().traverse(sel)
assert sel2.corresponding_column(col) is sel2.c.foo
sel3 = visitors.ReplacingCloningVisitor().traverse(sel2)
assert sel3.corresponding_column(col) is sel3.c.foo
def test_with_only_generative(self):
s1 = table1.select().scalar_subquery()
self.assert_compile(
s1.with_only_columns(s1),
"SELECT (SELECT table1.col1, table1.col2, "
"table1.col3, table1.colx FROM table1) AS anon_1",
)
def test_reduce_cols_odd_expressions(self):
"""test util.reduce_columns() works with text, non-col expressions
in a SELECT.
found_during_type_annotation
"""
stmt = select(
table1.c.col1,
table1.c.col3 * 5,
text("some_expr"),
table2.c.col2,
func.foo(),
).join(table2)
self.assert_compile(
stmt.reduce_columns(only_synonyms=False),
"SELECT table1.col1, table1.col3 * :col3_1 AS anon_1, "
"some_expr, foo() AS foo_1 FROM table1 JOIN table2 "
"ON table1.col1 = table2.col2",
)
def test_with_only_generative_no_list(self):
s1 = table1.select().scalar_subquery()
with testing.expect_raises_message(
exc.ArgumentError,
r"The \"entities\" argument to "
r"Select.with_only_columns\(\), when referring "
"to a sequence of items, is now passed",
):
s1.with_only_columns([s1])
@testing.combinations(
(
[table1.c.col1],
[table1.join(table2)],
[table1.join(table2)],
[table1],
),
([table1], [table2], [table2, table1], [table1]),
(
[table1.c.col1, table2.c.col1],
[],
[table1, table2],
[table1, table2],
),
)
def test_froms_accessors(
self, cols_expr, select_from, exp_final_froms, exp_cc_froms
):
"""tests for #6808"""
s1 = select(*cols_expr).select_from(*select_from)
for ff, efp in zip_longest(s1.get_final_froms(), exp_final_froms):
assert ff.compare(efp)
eq_(s1.columns_clause_froms, exp_cc_froms)
def test_scalar_subquery_from_subq_same_source(self):
s1 = select(table1.c.col1)
for i in range(2):
stmt = s1.subquery().select().scalar_subquery()
self.assert_compile(
stmt,
"(SELECT anon_1.col1 FROM "
"(SELECT table1.col1 AS col1 FROM table1) AS anon_1)",
)
def test_type_coerce_preserve_subq(self):
class MyType(TypeDecorator):
impl = Integer
cache_ok = True
stmt = select(type_coerce(column("x"), MyType).label("foo"))
subq = stmt.subquery()
stmt2 = subq.select()
subq2 = stmt2.subquery()
assert isinstance(stmt._raw_columns[0].type, MyType)
assert isinstance(subq.c.foo.type, MyType)
assert isinstance(stmt2.selected_columns.foo.type, MyType)
assert isinstance(subq2.c.foo.type, MyType)
def test_type_coerce_selfgroup(self):
no_group = column("a") // type_coerce(column("x"), Integer)
group = column("b") // type_coerce(column("y") * column("w"), Integer)
self.assert_compile(no_group, "a / x")
self.assert_compile(group, "b / (y * w)")
def test_subquery_on_table(self):
sel = (
select(table1, table2)
.set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
.subquery()
)
assert sel.corresponding_column(table1.c.col1) is sel.c.table1_col1
assert (
sel.corresponding_column(table1.c.col1, require_embedded=True)
is sel.c.table1_col1
)
assert table1.corresponding_column(sel.c.table1_col1) is table1.c.col1
assert (
table1.corresponding_column(
sel.c.table1_col1, require_embedded=True
)
is None
)
def test_join_against_join(self):
j = outerjoin(table1, table2, table1.c.col1 == table2.c.col2)
jj = (
select(table1.c.col1.label("bar_col1"))
.select_from(j)
.alias(name="foo")
)
jjj = join(table1, jj, table1.c.col1 == jj.c.bar_col1)
assert jjj.corresponding_column(jjj.c.table1_col1) is jjj.c.table1_col1
j2 = jjj._anonymous_fromclause("foo")
assert j2.corresponding_column(jjj.c.table1_col1) is j2.c.table1_col1
assert jjj.corresponding_column(jj.c.bar_col1) is jj.c.bar_col1
def test_table_alias(self):
a = table1.alias("a")
j = join(a, table2)
criterion = a.c.col1 == table2.c.col2
self.assert_(criterion.compare(j.onclause))
def test_join_doesnt_derive_from_onclause(self):
# test issue #4621. the hide froms from the join comes from
# Join._from_obj(), which should not include tables in the ON clause
t1 = table("t1", column("a"))
t2 = table("t2", column("b"))
t3 = table("t3", column("c"))
t4 = table("t4", column("d"))
j = t1.join(t2, onclause=t1.c.a == t3.c.c)
j2 = t4.join(j, onclause=t4.c.d == t2.c.b)
stmt = select(t1, t2, t3, t4).select_from(j2)
self.assert_compile(
stmt,
"SELECT t1.a, t2.b, t3.c, t4.d FROM "
"t4 JOIN (t1 JOIN t2 ON t1.a = t3.c) ON t4.d = t2.b, t3",
)
stmt = select(t1).select_from(t3).select_from(j2)
self.assert_compile(
stmt,
"SELECT t1.a FROM t3, t4 JOIN (t1 JOIN t2 ON t1.a = t3.c) "
"ON t4.d = t2.b",
)
@testing.fails("not supported with rework, need a new approach")
def test_alias_handles_column_context(self):
# not quite a use case yet but this is expected to become
# prominent w/ PostgreSQL's tuple functions
stmt = select(table1.c.col1, table1.c.col2)
a = stmt.alias("a")
# TODO: this case is crazy, sending SELECT or FROMCLAUSE has to
# be figured out - is it a scalar row query? what kinds of
# statements go into functions in PG. seems likely select statement,
# but not alias, subquery or other FROM object
self.assert_compile(
select(func.foo(a)),
"SELECT foo(SELECT table1.col1, table1.col2 FROM table1) "
"AS foo_1 FROM "
"(SELECT table1.col1 AS col1, table1.col2 AS col2 FROM table1) "
"AS a",
)
def test_union_correspondence(self):
# tests that we can correspond a column in a Select statement
# with a certain Table, against a column in a Union where one of
# its underlying Selects matches to that same Table
u = select(
table1.c.col1,
table1.c.col2,
table1.c.col3,
table1.c.colx,
null().label("coly"),
).union(
select(
table2.c.col1,
table2.c.col2,
table2.c.col3,
null().label("colx"),
table2.c.coly,
)
)
s1 = table1.select().set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
s2 = table2.select().set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
assert (
u.corresponding_column(s1.selected_columns.table1_col2)
is u.selected_columns.col2
)
# right now, the "selected_columns" of a union are those of the
# first selectable. so without using a subquery that represents
# all the SELECTs in the union, we can't do corresponding column
# like this. perhaps compoundselect shouldn't even implement
# .corresponding_column directly
assert (
u.corresponding_column(s2.selected_columns.table2_col2) is None
) # really? u.selected_columns.col2
usub = u.subquery()
assert (
usub.corresponding_column(s1.selected_columns.table1_col2)
is usub.c.col2
)
assert (
usub.corresponding_column(s2.selected_columns.table2_col2)
is usub.c.col2
)
s1sub = s1.subquery()
s2sub = s2.subquery()
assert usub.corresponding_column(s1sub.c.table1_col2) is usub.c.col2
assert usub.corresponding_column(s2sub.c.table2_col2) is usub.c.col2
def test_union_precedence(self):
# conflicting column correspondence should be resolved based on
# the order of the select()s in the union
s1 = select(table1.c.col1, table1.c.col2)
s2 = select(table1.c.col2, table1.c.col1)
s3 = select(table1.c.col3, table1.c.colx)
s4 = select(table1.c.colx, table1.c.col3)
u1 = union(s1, s2).subquery()
assert u1.corresponding_column(table1.c.col1) is u1.c.col1
assert u1.corresponding_column(table1.c.col2) is u1.c.col2
u1 = union(s1, s2, s3, s4).subquery()
assert u1.corresponding_column(table1.c.col1) is u1.c.col1
assert u1.corresponding_column(table1.c.col2) is u1.c.col2
assert u1.corresponding_column(table1.c.colx) is u1.c.col2
assert u1.corresponding_column(table1.c.col3) is u1.c.col1
def test_proxy_set_pollution(self):
s1 = select(table1.c.col1, table1.c.col2)
s2 = select(table1.c.col2, table1.c.col1)
for c in s1.selected_columns:
c.proxy_set
for c in s2.selected_columns:
c.proxy_set
u1 = union(s1, s2).subquery()
assert u1.corresponding_column(table1.c.col2) is u1.c.col2
def test_singular_union(self):
u = union(
select(table1.c.col1, table1.c.col2, table1.c.col3),
select(table1.c.col1, table1.c.col2, table1.c.col3),
)
u = union(select(table1.c.col1, table1.c.col2, table1.c.col3))
assert u.selected_columns.col1 is not None
assert u.selected_columns.col2 is not None
assert u.selected_columns.col3 is not None
def test_alias_union(self):
# same as testunion, except its an alias of the union
u = (
select(
table1.c.col1,
table1.c.col2,
table1.c.col3,
table1.c.colx,
null().label("coly"),
)
.union(
select(
table2.c.col1,
table2.c.col2,
table2.c.col3,
null().label("colx"),
table2.c.coly,
)
)
.alias("analias")
)
s1 = (
table1.select()
.set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
.subquery()
)
s2 = (
table2.select()
.set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
.subquery()
)
assert u.corresponding_column(s1.c.table1_col2) is u.c.col2
assert u.corresponding_column(s2.c.table2_col2) is u.c.col2
assert u.corresponding_column(s2.c.table2_coly) is u.c.coly
assert s2.corresponding_column(u.c.coly) is s2.c.table2_coly
def test_union_of_alias(self):
s1 = select(table1.c.col1, table1.c.col2)
s2 = select(table1.c.col1, table1.c.col2).alias()
# previously this worked
assert_raises_message(
exc.ArgumentError,
"SELECT construct for inclusion in a UNION or "
"other set construct expected",
union,
s1,
s2,
)
def test_union_of_text(self):
s1 = select(table1.c.col1, table1.c.col2)
s2 = text("select col1, col2 from foo").columns(
column("col1"), column("col2")
)
u1 = union(s1, s2).subquery()
assert u1.corresponding_column(s1.selected_columns.col1) is u1.c.col1
assert u1.corresponding_column(s2.selected_columns.col1) is u1.c.col1
u2 = union(s2, s1).subquery()
assert u2.corresponding_column(s1.selected_columns.col1) is u2.c.col1
assert u2.corresponding_column(s2.selected_columns.col1) is u2.c.col1
def test_union_alias_misc(self):
s1 = select(table1.c.col1, table1.c.col2)
s2 = select(table1.c.col2, table1.c.col1)
u1 = union(s1, s2).subquery()
assert u1.corresponding_column(table1.c.col2) is u1.c.col2
metadata = MetaData()
table1_new = Table(
"table1",
metadata,
Column("col1", Integer, primary_key=True),
Column("col2", String(20)),
Column("col3", Integer),
Column("colx", Integer),
)
# table1_new = table1
s1 = select(table1_new.c.col1, table1_new.c.col2)
s2 = select(table1_new.c.col2, table1_new.c.col1)
u1 = union(s1, s2).subquery()
# TODO: failing due to proxy_set not correct
assert u1.corresponding_column(table1_new.c.col2) is u1.c.col2
def test_unnamed_exprs_keys(self):
s1 = select(
table1.c.col1 == 5,
table1.c.col1 == 10,
func.count(table1.c.col1),
literal_column("x"),
)
# the reason we return "_no_label" is because we dont have a system
# right now that is guaranteed to use the identical label in
# selected_columns as will be used when we compile the statement, and
# this includes the creation of _result_map right now which gets loaded
# with lots of unprocessed anon symbols for these kinds of cases,
# and we don't have a fully comprehensive approach for this to always
# do the right thing; as it is *vastly* simpler for the user to please
# use a label(), "_no_label" is meant to encourage this rather than
# relying on a system that we don't fully have on this end.
eq_(s1.subquery().c.keys(), ["_no_label", "_no_label_1", "count", "x"])
self.assert_compile(
s1,
"SELECT table1.col1 = :col1_1 AS anon_1, "
"table1.col1 = :col1_2 AS anon_2, count(table1.col1) AS count_1, "
"x FROM table1",
)
eq_(
s1.selected_columns.keys(),
["_no_label", "_no_label_1", "count", "x"],
)
eq_(
select(s1.subquery()).selected_columns.keys(),
["_no_label", "_no_label_1", "_no_label_2", "x"],
)
self.assert_compile(
select(s1.subquery()),
"SELECT anon_2.anon_1, anon_2.anon_3, anon_2.count_1, anon_2.x "
"FROM (SELECT table1.col1 = :col1_1 AS anon_1, "
"table1.col1 = :col1_2 AS anon_3, "
"count(table1.col1) AS count_1, x FROM table1) AS anon_2",
)
def test_union_alias_dupe_keys(self):
s1 = select(table1.c.col1, table1.c.col2, table2.c.col1)
s2 = select(table2.c.col1, table2.c.col2, table2.c.col3)
u1 = union(s1, s2).subquery()
assert (
u1.corresponding_column(s1.selected_columns._all_columns[0])
is u1.c._all_columns[0]
)
# col1 is taken by the first "col1" in the list
assert u1.c.col1 is u1.c._all_columns[0]
# table2.c.col1 is in two positions in this union, so...currently
# it is the replaced one at position 2.
assert u1.corresponding_column(table2.c.col1) is u1.c._all_columns[2]
# this is table2.c.col1, which in the first selectable is in position 2
assert u1.corresponding_column(s2.selected_columns.col1) is u1.c[2]
# same
assert u1.corresponding_column(s2.subquery().c.col1) is u1.c[2]
# col2 is working OK
assert u1.corresponding_column(s1.selected_columns.col2) is u1.c.col2
assert (
u1.corresponding_column(s1.selected_columns.col2)
is u1.c._all_columns[1]
)
assert u1.corresponding_column(s2.selected_columns.col2) is u1.c.col2
assert (
u1.corresponding_column(s2.selected_columns.col2)
is u1.c._all_columns[1]
)
assert u1.corresponding_column(s2.subquery().c.col2) is u1.c.col2
# col3 is also "correct"
assert u1.corresponding_column(s2.selected_columns.col3) is u1.c[2]
assert u1.corresponding_column(table1.c.col1) is u1.c._all_columns[0]
assert u1.corresponding_column(table1.c.col2) is u1.c._all_columns[1]
assert u1.corresponding_column(table2.c.col1) is u1.c._all_columns[2]
assert u1.corresponding_column(table2.c.col2) is u1.c._all_columns[1]
assert u1.corresponding_column(table2.c.col3) is u1.c._all_columns[2]
def test_union_alias_dupe_keys_disambiguates_in_subq_compile_one(self):
s1 = select(table1.c.col1, table1.c.col2, table2.c.col1).limit(1)
s2 = select(table2.c.col1, table2.c.col2, table2.c.col3).limit(1)
u1 = union(s1, s2).subquery()
eq_(u1.c.keys(), ["col1", "col2", "col1_1"])
stmt = select(u1)
eq_(stmt.selected_columns.keys(), ["col1", "col2", "col1_1"])
# the union() sets a new labeling form in the first SELECT
self.assert_compile(
stmt,
"SELECT anon_1.col1, anon_1.col2, anon_1.col1_1 FROM "
"((SELECT table1.col1 AS col1, table1.col2 AS col2, table2.col1 "
"AS col1_1 "
"FROM table1, table2 LIMIT :param_1) UNION "
"(SELECT table2.col1 AS col1, table2.col2 AS col2, "
"table2.col3 AS col3 FROM table2 "
"LIMIT :param_2)) AS anon_1",
)
def test_union_alias_dupe_keys_disambiguates_in_subq_compile_two(self):
a = table("a", column("id"))
b = table("b", column("id"), column("aid"))
d = table("d", column("id"), column("aid"))
u1 = union(
a.join(b, a.c.id == b.c.aid)
.select()
.set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL),
a.join(d, a.c.id == d.c.aid)
.select()
.set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL),
).alias()
eq_(u1.c.keys(), ["a_id", "b_id", "b_aid"])
stmt = select(u1)
eq_(stmt.selected_columns.keys(), ["a_id", "b_id", "b_aid"])
# the union() detects that the first SELECT already has a labeling
# style and uses that
self.assert_compile(
stmt,
"SELECT anon_1.a_id, anon_1.b_id, anon_1.b_aid FROM "
"(SELECT a.id AS a_id, b.id AS b_id, b.aid AS b_aid "
"FROM a JOIN b ON a.id = b.aid "
"UNION SELECT a.id AS a_id, d.id AS d_id, d.aid AS d_aid "
"FROM a JOIN d ON a.id = d.aid) AS anon_1",
)
def test_union_alias_dupe_keys_grouped(self):
s1 = select(table1.c.col1, table1.c.col2, table2.c.col1).limit(1)
s2 = select(table2.c.col1, table2.c.col2, table2.c.col3).limit(1)
u1 = union(s1, s2).subquery()
assert (
u1.corresponding_column(s1.selected_columns._all_columns[0])
is u1.c._all_columns[0]
)
# col1 is taken by the first "col1" in the list
assert u1.c.col1 is u1.c._all_columns[0]
# table2.c.col1 is in two positions in this union, so...currently
# it is the replaced one at position 2.
assert u1.corresponding_column(table2.c.col1) is u1.c._all_columns[2]
# this is table2.c.col1, which in the first selectable is in position 2
assert u1.corresponding_column(s2.selected_columns.col1) is u1.c[2]
# same
assert u1.corresponding_column(s2.subquery().c.col1) is u1.c[2]
# col2 is working OK
assert u1.corresponding_column(s1.selected_columns.col2) is u1.c.col2
assert (
u1.corresponding_column(s1.selected_columns.col2)
is u1.c._all_columns[1]
)
assert u1.corresponding_column(s2.selected_columns.col2) is u1.c.col2
assert (
u1.corresponding_column(s2.selected_columns.col2)
is u1.c._all_columns[1]
)
assert u1.corresponding_column(s2.subquery().c.col2) is u1.c.col2
# col3 is also "correct"
assert u1.corresponding_column(s2.selected_columns.col3) is u1.c[2]
assert u1.corresponding_column(table1.c.col1) is u1.c._all_columns[0]
assert u1.corresponding_column(table1.c.col2) is u1.c._all_columns[1]
assert u1.corresponding_column(table2.c.col1) is u1.c._all_columns[2]
assert u1.corresponding_column(table2.c.col2) is u1.c._all_columns[1]
assert u1.corresponding_column(table2.c.col3) is u1.c._all_columns[2]
def test_select_union(self):
# like testaliasunion, but off a Select off the union.
u = (
select(
table1.c.col1,
table1.c.col2,
table1.c.col3,
table1.c.colx,
null().label("coly"),
)
.union(
select(
table2.c.col1,
table2.c.col2,
table2.c.col3,
null().label("colx"),
table2.c.coly,
)
)
.alias("analias")
)
s = select(u).subquery()
s1 = (
table1.select()
.set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
.subquery()
)
s2 = (
table2.select()
.set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
.subquery()
)
assert s.corresponding_column(s1.c.table1_col2) is s.c.col2
assert s.corresponding_column(s2.c.table2_col2) is s.c.col2
def test_union_against_join(self):
# same as testunion, except its an alias of the union
u = (
select(
table1.c.col1,
table1.c.col2,
table1.c.col3,
table1.c.colx,
null().label("coly"),
)
.union(
select(
table2.c.col1,
table2.c.col2,
table2.c.col3,
null().label("colx"),
table2.c.coly,
)
)
.alias("analias")
)
j1 = table1.join(table2)
assert u.corresponding_column(j1.c.table1_colx) is u.c.colx
assert j1.corresponding_column(u.c.colx) is j1.c.table1_colx
def test_join(self):
a = join(table1, table2)
print(str(a.select().set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)))
b = table2.alias("b")
j = join(a, b)
print(str(j))
criterion = a.c.table1_col1 == b.c.col2
self.assert_(criterion.compare(j.onclause))
def test_select_subquery_join(self):
a = table1.select().alias("a")
j = join(a, table2)
criterion = a.c.col1 == table2.c.col2
self.assert_(criterion.compare(j.onclause))
def test_subquery_labels_join(self):
a = (
table1.select()
.set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
.subquery()
)
j = join(a, table2)
criterion = a.c.table1_col1 == table2.c.col2
self.assert_(criterion.compare(j.onclause))
def test_scalar_cloned_comparator(self):
sel = select(table1.c.col1).scalar_subquery()
sel == table1.c.col1
sel2 = visitors.ReplacingCloningVisitor().traverse(sel)
expr2 = sel2 == table1.c.col1
is_(expr2.left, sel2)
def test_column_labels(self):
a = select(
table1.c.col1.label("acol1"),
table1.c.col2.label("acol2"),
table1.c.col3.label("acol3"),
).subquery()
j = join(a, table2)
criterion = a.c.acol1 == table2.c.col2
self.assert_(criterion.compare(j.onclause))
def test_labeled_select_corresponding(self):
l1 = select(func.max(table1.c.col1)).label("foo")
s = select(l1)
eq_(s.corresponding_column(l1), s.selected_columns.foo)
s = select(table1.c.col1, l1)
eq_(s.corresponding_column(l1), s.selected_columns.foo)
def test_labeled_subquery_corresponding(self):
l1 = select(func.max(table1.c.col1)).label("foo")
s = select(l1).subquery()
eq_(s.corresponding_column(l1), s.c.foo)
s = select(table1.c.col1, l1).subquery()
eq_(s.corresponding_column(l1), s.c.foo)
def test_select_alias_labels(self):
a = (
table2.select()
.set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
.alias("a")
)
j = join(a, table1)
criterion = table1.c.col1 == a.c.table2_col2
self.assert_(criterion.compare(j.onclause))
def test_table_joined_to_select_of_table(self):
metadata = MetaData()
a = Table("a", metadata, Column("id", Integer, primary_key=True))
j2 = select(a.c.id.label("aid")).alias("bar")
j3 = a.join(j2, j2.c.aid == a.c.id)
j4 = select(j3).alias("foo")
assert j4.corresponding_column(j2.c.aid) is j4.c.aid
assert j4.corresponding_column(a.c.id) is j4.c.id
@testing.combinations(True, False)
def test_two_metadata_join_raises(self, include_a_joining_table):
"""test case from 2008 enhanced as of #8101, more specific failure
modes for non-resolvable FKs
"""
m = MetaData()
m2 = MetaData()
t1 = Table("t1", m, Column("id", Integer), Column("id2", Integer))
if include_a_joining_table:
t2 = Table("t2", m, Column("id", Integer, ForeignKey("t1.id")))
t3 = Table("t3", m2, Column("id", Integer, ForeignKey("t1.id2")))
with expect_raises_message(
exc.NoReferencedTableError,
"Foreign key associated with column 't3.id'",
):
t3.join(t1)
if include_a_joining_table:
s = (
select(t2, t3)
.set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
.subquery()
)
else:
s = (
select(t3)
.set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
.subquery()
)
with expect_raises_message(
exc.NoReferencedTableError,
"Foreign key associated with column 'anon_1.t3_id' could not "
"find table 't1' with which to generate a foreign key to target "
"column 'id2'",
):
select(s.join(t1)),
# manual join is OK. using select().join() here is also exercising
# that join() does not need to resolve FKs if we provided the
# ON clause
if include_a_joining_table:
self.assert_compile(
select(s).join(
t1, and_(s.c.t2_id == t1.c.id, s.c.t3_id == t1.c.id)
),
"SELECT anon_1.t2_id, anon_1.t3_id FROM (SELECT "
"t2.id AS t2_id, t3.id AS t3_id FROM t2, t3) AS anon_1 "
"JOIN t1 ON anon_1.t2_id = t1.id AND anon_1.t3_id = t1.id",
)
else:
self.assert_compile(
select(s).join(t1, s.c.t3_id == t1.c.id),
"SELECT anon_1.t3_id FROM (SELECT t3.id AS t3_id FROM t3) "
"AS anon_1 JOIN t1 ON anon_1.t3_id = t1.id",
)
def test_multi_label_chain_naming_col(self):
# See [ticket:2167] for this one.
l1 = table1.c.col1.label("a")
l2 = select(l1).label("b")
s = select(l2).subquery()
assert s.c.b is not None
self.assert_compile(
s.select(),
"SELECT anon_1.b FROM "
"(SELECT (SELECT table1.col1 AS a FROM table1) AS b) AS anon_1",
)
s2 = select(s.element.label("c")).subquery()
self.assert_compile(
s2.select(),
"SELECT anon_1.c FROM (SELECT (SELECT ("
"SELECT table1.col1 AS a FROM table1) AS b) AS c) AS anon_1",
)
def test_self_referential_select_raises(self):
t = table("t", column("x"))
# this issue is much less likely as subquery() applies a labeling
# style to the select, eliminating the self-referential call unless
# the select already had labeling applied
s = select(t).set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
with testing.expect_deprecated("The SelectBase.c"):
s.where.non_generative(s, s.c.t_x > 5)
assert_raises_message(
exc.InvalidRequestError,
r"select\(\) construct refers to itself as a FROM",
s.compile,
)
def test_unusual_column_elements_text(self):
"""test that .c excludes text()."""
s = select(table1.c.col1, text("foo")).subquery()
eq_(list(s.c), [s.c.col1])
def test_unusual_column_elements_clauselist(self):
"""Test that raw ClauseList is expanded into .c."""
from sqlalchemy.sql.expression import ClauseList
s = select(
table1.c.col1, ClauseList(table1.c.col2, table1.c.col3)
).subquery()
eq_(list(s.c), [s.c.col1, s.c.col2, s.c.col3])
def test_unusual_column_elements_boolean_clauselist(self):
"""test that BooleanClauseList is placed as single element in .c."""
c2 = and_(table1.c.col2 == 5, table1.c.col3 == 4)
s = select(table1.c.col1, c2).subquery()
eq_(list(s.c), [s.c.col1, s.corresponding_column(c2)])
def test_from_list_deferred_constructor(self):
c1 = Column("c1", Integer)
c2 = Column("c2", Integer)
select(c1)
t = Table("t", MetaData(), c1, c2)
eq_(c1._from_objects, [t])
eq_(c2._from_objects, [t])
self.assert_compile(select(c1), "SELECT t.c1 FROM t")
self.assert_compile(select(c2), "SELECT t.c2 FROM t")
def test_from_list_deferred_whereclause(self):
c1 = Column("c1", Integer)
c2 = Column("c2", Integer)
select(c1).where(c1 == 5)
t = Table("t", MetaData(), c1, c2)
eq_(c1._from_objects, [t])
eq_(c2._from_objects, [t])
self.assert_compile(select(c1), "SELECT t.c1 FROM t")
self.assert_compile(select(c2), "SELECT t.c2 FROM t")
def test_from_list_deferred_fromlist(self):
m = MetaData()
t1 = Table("t1", m, Column("x", Integer))
c1 = Column("c1", Integer)
select(c1).where(c1 == 5).select_from(t1)
t2 = Table("t2", MetaData(), c1)
eq_(c1._from_objects, [t2])
self.assert_compile(select(c1), "SELECT t2.c1 FROM t2")
def test_from_list_deferred_cloning(self):
c1 = Column("c1", Integer)
c2 = Column("c2", Integer)
s = select(c1)
s2 = select(c2)
s3 = sql_util.ClauseAdapter(s).traverse(s2)
Table("t", MetaData(), c1, c2)
self.assert_compile(s3, "SELECT t.c2 FROM t")
def test_from_list_with_columns(self):
table1 = table("t1", column("a"))
table2 = table("t2", column("b"))
s1 = select(table1.c.a, table2.c.b)
self.assert_compile(s1, "SELECT t1.a, t2.b FROM t1, t2")
s2 = s1.with_only_columns(table2.c.b)
self.assert_compile(s2, "SELECT t2.b FROM t2")
s3 = sql_util.ClauseAdapter(table1).traverse(s1)
self.assert_compile(s3, "SELECT t1.a, t2.b FROM t1, t2")
s4 = s3.with_only_columns(table2.c.b)
self.assert_compile(s4, "SELECT t2.b FROM t2")
def test_from_list_against_existing_one(self):
c1 = Column("c1", Integer)
s = select(c1)
# force a compile.
self.assert_compile(s, "SELECT c1")
Table("t", MetaData(), c1)
self.assert_compile(s, "SELECT t.c1 FROM t")
def test_from_list_against_existing_two(self):
c1 = Column("c1", Integer)
c2 = Column("c2", Integer)
s = select(c1)
# force a compile.
eq_(str(s), "SELECT c1")
t = Table("t", MetaData(), c1, c2)
eq_(c1._from_objects, [t])
eq_(c2._from_objects, [t])
self.assert_compile(s, "SELECT t.c1 FROM t")
self.assert_compile(select(c1), "SELECT t.c1 FROM t")
self.assert_compile(select(c2), "SELECT t.c2 FROM t")
def test_label_gen_resets_on_table(self):
c1 = Column("c1", Integer)
eq_(c1._label, "c1")
Table("t1", MetaData(), c1)
eq_(c1._label, "t1_c1")
def test_no_alias_construct(self):
a = table("a", column("x"))
assert_raises_message(
NotImplementedError,
"The Alias class is not intended to be constructed directly. "
r"Please use the alias\(\) standalone function",
Alias,
a,
"foo",
)
def test_whereclause_adapted(self):
table1 = table("t1", column("a"))
s1 = select(table1).subquery()
s2 = select(s1).where(s1.c.a == 5)
assert s2._whereclause.left.table is s1
ta = select(table1).subquery()
s3 = sql_util.ClauseAdapter(ta).traverse(s2)
froms = list(s3._iterate_from_elements())
assert s1 not in froms
# these are new assumptions with the newer approach that
# actively swaps out whereclause and others
assert s3._whereclause.left.table is not s1
assert s3._whereclause.left.table in froms
def test_table_schema(self):
t = table("foo")
eq_(t.name, "foo")
eq_(t.fullname, "foo")
t = table("foo", schema="bar")
eq_(t.name, "foo")
eq_(t.fullname, "bar.foo")
class RefreshForNewColTest(fixtures.TestBase):
def test_join_uninit(self):
a = table("a", column("x"))
b = table("b", column("y"))
j = a.join(b, a.c.x == b.c.y)
q = column("q")
b.append_column(q)
j._refresh_for_new_column(q)
assert j.c.b_q is q
def test_join_init(self):
a = table("a", column("x"))
b = table("b", column("y"))
j = a.join(b, a.c.x == b.c.y)
j.c
q = column("q")
b.append_column(q)
j._refresh_for_new_column(q)
assert j.c.b_q is q
def test_join_samename_init(self):
a = table("a", column("x"))
b = table("b", column("y"))
j = a.join(b, a.c.x == b.c.y)
j.c
q = column("x")
b.append_column(q)
j._refresh_for_new_column(q)
assert j.c.b_x is q
def test_select_samename_init(self):
a = table("a", column("x"))
b = table("b", column("y"))
s = select(a, b).set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
s.selected_columns
q = column("x")
b.append_column(q)
s._refresh_for_new_column(q)
assert q in s.selected_columns.b_x.proxy_set
def test_alias_alias_samename_init(self):
a = table("a", column("x"))
b = table("b", column("y"))
s1 = (
select(a, b)
.set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
.alias()
)
s2 = s1.alias()
s1.c
s2.c
q = column("x")
b.append_column(q)
assert "_columns" in s2.__dict__
s2._refresh_for_new_column(q)
assert "_columns" not in s2.__dict__
is_(s1.corresponding_column(s2.c.b_x), s1.c.b_x)
def test_aliased_select_samename_uninit(self):
a = table("a", column("x"))
b = table("b", column("y"))
s = (
select(a, b)
.set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
.alias()
)
q = column("x")
b.append_column(q)
s._refresh_for_new_column(q)
assert q in s.c.b_x.proxy_set
def test_aliased_select_samename_init(self):
a = table("a", column("x"))
b = table("b", column("y"))
s = (
select(a, b)
.set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
.alias()
)
s.c
q = column("x")
b.append_column(q)
s._refresh_for_new_column(q)
assert q in s.c.b_x.proxy_set
def test_aliased_select_irrelevant(self):
a = table("a", column("x"))
b = table("b", column("y"))
c = table("c", column("z"))
s = (
select(a, b)
.set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
.alias()
)
s.c
q = column("x")
c.append_column(q)
s._refresh_for_new_column(q)
assert "c_x" not in s.c
def test_aliased_select_no_cols_clause(self):
a = table("a", column("x"))
s = (
select(a.c.x)
.set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
.alias()
)
s.c
q = column("q")
a.append_column(q)
s._refresh_for_new_column(q)
assert "a_q" not in s.c
def test_union_uninit(self):
a = table("a", column("x"))
s1 = select(a)
s2 = select(a)
s3 = s1.union(s2)
q = column("q")
a.append_column(q)
s3._refresh_for_new_column(q)
assert a.c.q in s3.selected_columns.q.proxy_set
def test_union_init(self):
a = table("a", column("x"))
s1 = select(a)
s2 = select(a)
s3 = s1.union(s2)
s3.selected_columns
q = column("q")
a.append_column(q)
s3._refresh_for_new_column(q)
assert a.c.q in s3.selected_columns.q.proxy_set
def test_nested_join_uninit(self):
a = table("a", column("x"))
b = table("b", column("y"))
c = table("c", column("z"))
j = a.join(b, a.c.x == b.c.y).join(c, b.c.y == c.c.z)
q = column("q")
b.append_column(q)
j._refresh_for_new_column(q)
assert j.c.b_q is q
def test_nested_join_init(self):
a = table("a", column("x"))
b = table("b", column("y"))
c = table("c", column("z"))
j = a.join(b, a.c.x == b.c.y).join(c, b.c.y == c.c.z)
j.c
q = column("q")
b.append_column(q)
j._refresh_for_new_column(q)
assert j.c.b_q is q
def test_fk_table(self):
m = MetaData()
fk = ForeignKey("x.id")
Table("x", m, Column("id", Integer))
a = Table("a", m, Column("x", Integer, fk))
a.c
q = Column("q", Integer)
a.append_column(q)
a._refresh_for_new_column(q)
eq_(a.foreign_keys, {fk})
fk2 = ForeignKey("g.id")
p = Column("p", Integer, fk2)
a.append_column(p)
a._refresh_for_new_column(p)
eq_(a.foreign_keys, {fk, fk2})
def test_fk_join(self):
m = MetaData()
fk = ForeignKey("x.id")
Table("x", m, Column("id", Integer))
a = Table("a", m, Column("x", Integer, fk))
b = Table("b", m, Column("y", Integer))
j = a.join(b, a.c.x == b.c.y)
j.c
q = Column("q", Integer)
b.append_column(q)
j._refresh_for_new_column(q)
eq_(j.foreign_keys, {fk})
fk2 = ForeignKey("g.id")
p = Column("p", Integer, fk2)
b.append_column(p)
j._refresh_for_new_column(p)
eq_(j.foreign_keys, {fk, fk2})
class AnonLabelTest(fixtures.TestBase):
"""Test behaviors fixed by [ticket:2168]."""
def test_anon_labels_named_column(self):
c1 = column("x")
assert c1.label(None) is not c1
eq_(str(select(c1.label(None))), "SELECT x AS x_1")
def test_anon_labels_literal_column(self):
c1 = literal_column("x")
assert c1.label(None) is not c1
eq_(str(select(c1.label(None))), "SELECT x AS x_1")
def test_anon_labels_func(self):
c1 = func.count("*")
assert c1.label(None) is not c1
eq_(str(select(c1)), "SELECT count(:count_2) AS count_1")
select(c1).compile()
eq_(str(select(c1.label(None))), "SELECT count(:count_2) AS count_1")
def test_named_labels_named_column(self):
c1 = column("x")
eq_(str(select(c1.label("y"))), "SELECT x AS y")
def test_named_labels_literal_column(self):
c1 = literal_column("x")
eq_(str(select(c1.label("y"))), "SELECT x AS y")
class JoinAnonymizingTest(fixtures.TestBase, AssertsCompiledSQL):
"""test anonymous_fromclause for aliases.
In 1.4 this function is only for ORM internal use. The public version
join.alias() is deprecated.
"""
__dialect__ = "default"
def test_flat_ok_on_non_join(self):
a = table("a", column("a"))
s = a.select()
self.assert_compile(
s.alias(flat=True).select(),
"SELECT anon_1.a FROM (SELECT a.a AS a FROM a) AS anon_1",
)
def test_join_alias(self):
a = table("a", column("a"))
b = table("b", column("b"))
self.assert_compile(
a.join(b, a.c.a == b.c.b)._anonymous_fromclause(),
"SELECT a.a AS a_a, b.b AS b_b FROM a JOIN b ON a.a = b.b",
)
def test_join_standalone_alias(self):
a = table("a", column("a"))
b = table("b", column("b"))
self.assert_compile(
a.join(b, a.c.a == b.c.b)._anonymous_fromclause(),
"SELECT a.a AS a_a, b.b AS b_b FROM a JOIN b ON a.a = b.b",
)
def test_join_alias_flat(self):
a = table("a", column("a"))
b = table("b", column("b"))
self.assert_compile(
a.join(b, a.c.a == b.c.b)._anonymous_fromclause(flat=True),
"a AS a_1 JOIN b AS b_1 ON a_1.a = b_1.b",
)
def test_join_standalone_alias_flat(self):
a = table("a", column("a"))
b = table("b", column("b"))
self.assert_compile(
a.join(b, a.c.a == b.c.b)._anonymous_fromclause(flat=True),
"a AS a_1 JOIN b AS b_1 ON a_1.a = b_1.b",
)
def test_composed_join_alias_flat(self):
a = table("a", column("a"))
b = table("b", column("b"))
c = table("c", column("c"))
d = table("d", column("d"))
j1 = a.join(b, a.c.a == b.c.b)
j2 = c.join(d, c.c.c == d.c.d)
# note in 1.4 the flat=True flag now descends into the whole join,
# as it should
self.assert_compile(
j1.join(j2, b.c.b == c.c.c)._anonymous_fromclause(flat=True),
"a AS a_1 JOIN b AS b_1 ON a_1.a = b_1.b JOIN "
"(c AS c_1 JOIN d AS d_1 ON c_1.c = d_1.d) "
"ON b_1.b = c_1.c",
)
def test_composed_join_alias(self):
a = table("a", column("a"))
b = table("b", column("b"))
c = table("c", column("c"))
d = table("d", column("d"))
j1 = a.join(b, a.c.a == b.c.b)
j2 = c.join(d, c.c.c == d.c.d)
self.assert_compile(
select(j1.join(j2, b.c.b == c.c.c)._anonymous_fromclause()),
"SELECT anon_1.a_a, anon_1.b_b, anon_1.c_c, anon_1.d_d "
"FROM (SELECT a.a AS a_a, b.b AS b_b, c.c AS c_c, d.d AS d_d "
"FROM a JOIN b ON a.a = b.b "
"JOIN (c JOIN d ON c.c = d.d) ON b.b = c.c) AS anon_1",
)
class JoinConditionTest(fixtures.TestBase, AssertsCompiledSQL):
__dialect__ = "default"
def test_join_condition_one(self):
m = MetaData()
t1 = Table("t1", m, Column("id", Integer))
t2 = Table(
"t2", m, Column("id", Integer), Column("t1id", ForeignKey("t1.id"))
)
t3 = Table(
"t3",
m,
Column("id", Integer),
Column("t1id", ForeignKey("t1.id")),
Column("t2id", ForeignKey("t2.id")),
)
t4 = Table(
"t4", m, Column("id", Integer), Column("t2id", ForeignKey("t2.id"))
)
t1t2 = t1.join(t2)
t2t3 = t2.join(t3)
for (left, right, a_subset, expected) in [
(t1, t2, None, t1.c.id == t2.c.t1id),
(t1t2, t3, t2, t1t2.c.t2_id == t3.c.t2id),
(t2t3, t1, t3, t1.c.id == t3.c.t1id),
(t2t3, t4, None, t2t3.c.t2_id == t4.c.t2id),
(t2t3, t4, t3, t2t3.c.t2_id == t4.c.t2id),
(t2t3.join(t1), t4, None, t2t3.c.t2_id == t4.c.t2id),
(t2t3.join(t1), t4, t1, t2t3.c.t2_id == t4.c.t2id),
(t1t2, t2t3, t2, t1t2.c.t2_id == t2t3.c.t3_t2id),
]:
assert expected.compare(
sql_util.join_condition(left, right, a_subset=a_subset)
)
def test_join_condition_two(self):
m = MetaData()
t1 = Table("t1", m, Column("id", Integer))
t2 = Table(
"t2", m, Column("id", Integer), Column("t1id", ForeignKey("t1.id"))
)
t3 = Table(
"t3",
m,
Column("id", Integer),
Column("t1id", ForeignKey("t1.id")),
Column("t2id", ForeignKey("t2.id")),
)
t4 = Table(
"t4", m, Column("id", Integer), Column("t2id", ForeignKey("t2.id"))
)
t5 = Table(
"t5",
m,
Column("t1id1", ForeignKey("t1.id")),
Column("t1id2", ForeignKey("t1.id")),
)
t1t2 = t1.join(t2)
t2t3 = t2.join(t3)
# these are ambiguous, or have no joins
for left, right, a_subset in [
(t1t2, t3, None),
(t2t3, t1, None),
(t1, t4, None),
(t1t2, t2t3, None),
(t5, t1, None),
(
t5.select()
.set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
.subquery(),
t1,
None,
),
]:
assert_raises(
exc.ArgumentError,
sql_util.join_condition,
left,
right,
a_subset=a_subset,
)
def test_join_condition_three(self):
m = MetaData()
t1 = Table("t1", m, Column("id", Integer))
t2 = Table(
"t2",
m,
Column("id", Integer),
Column("t1id", ForeignKey("t1.id")),
)
t3 = Table(
"t3",
m,
Column("id", Integer),
Column("t1id", ForeignKey("t1.id")),
Column("t2id", ForeignKey("t2.id")),
)
t4 = Table(
"t4",
m,
Column("id", Integer),
Column("t2id", ForeignKey("t2.id")),
)
t1t2 = t1.join(t2)
t2t3 = t2.join(t3)
als = t2t3._anonymous_fromclause()
# test join's behavior, including natural
for left, right, expected in [
(t1, t2, t1.c.id == t2.c.t1id),
(t1t2, t3, t1t2.c.t2_id == t3.c.t2id),
(t2t3, t1, t1.c.id == t3.c.t1id),
(t2t3, t4, t2t3.c.t2_id == t4.c.t2id),
(t2t3, t4, t2t3.c.t2_id == t4.c.t2id),
(t2t3.join(t1), t4, t2t3.c.t2_id == t4.c.t2id),
(t2t3.join(t1), t4, t2t3.c.t2_id == t4.c.t2id),
(t1t2, als, t1t2.c.t2_id == als.c.t3_t2id),
]:
assert expected.compare(left.join(right).onclause)
def test_join_condition_four(self):
m = MetaData()
t1 = Table("t1", m, Column("id", Integer))
t2 = Table(
"t2", m, Column("id", Integer), Column("t1id", ForeignKey("t1.id"))
)
t3 = Table(
"t3",
m,
Column("id", Integer),
Column("t1id", ForeignKey("t1.id")),
Column("t2id", ForeignKey("t2.id")),
)
t1t2 = t1.join(t2)
t2t3 = t2.join(t3)
# these are right-nested joins
j = t1t2.join(t2t3)
assert j.onclause.compare(t2.c.id == t3.c.t2id)
self.assert_compile(
j,
"t1 JOIN t2 ON t1.id = t2.t1id JOIN "
"(t2 JOIN t3 ON t2.id = t3.t2id) ON t2.id = t3.t2id",
)
def test_join_condition_five(self):
m = MetaData()
t1 = Table("t1", m, Column("id", Integer))
t2 = Table(
"t2", m, Column("id", Integer), Column("t1id", ForeignKey("t1.id"))
)
t3 = Table(
"t3",
m,
Column("id", Integer),
Column("t1id", ForeignKey("t1.id")),
Column("t2id", ForeignKey("t2.id")),
)
t1t2 = t1.join(t2)
t2t3 = t2.join(t3)
st2t3 = (
t2t3.select()
.set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
.subquery()
)
j = t1t2.join(st2t3)
assert j.onclause.compare(t2.c.id == st2t3.c.t3_t2id)
self.assert_compile(
j,
"t1 JOIN t2 ON t1.id = t2.t1id JOIN "
"(SELECT t2.id AS t2_id, t2.t1id AS t2_t1id, "
"t3.id AS t3_id, t3.t1id AS t3_t1id, t3.t2id AS t3_t2id "
"FROM t2 JOIN t3 ON t2.id = t3.t2id) AS anon_1 "
"ON t2.id = anon_1.t3_t2id",
)
def test_join_multiple_equiv_fks(self):
m = MetaData()
t1 = Table("t1", m, Column("id", Integer, primary_key=True))
t2 = Table(
"t2",
m,
Column("t1id", Integer, ForeignKey("t1.id"), ForeignKey("t1.id")),
)
assert sql_util.join_condition(t1, t2).compare(t1.c.id == t2.c.t1id)
def test_join_cond_no_such_unrelated_table(self):
m = MetaData()
# bounding the "good" column with two "bad" ones is so to
# try to get coverage to get the "continue" statements
# in the loop...
t1 = Table(
"t1",
m,
Column("y", Integer, ForeignKey("t22.id")),
Column("x", Integer, ForeignKey("t2.id")),
Column("q", Integer, ForeignKey("t22.id")),
)
t2 = Table("t2", m, Column("id", Integer))
assert sql_util.join_condition(t1, t2).compare(t1.c.x == t2.c.id)
assert sql_util.join_condition(t2, t1).compare(t1.c.x == t2.c.id)
def test_join_cond_no_such_unrelated_column(self):
m = MetaData()
t1 = Table(
"t1",
m,
Column("x", Integer, ForeignKey("t2.id")),
Column("y", Integer, ForeignKey("t3.q")),
)
t2 = Table("t2", m, Column("id", Integer))
Table("t3", m, Column("id", Integer))
assert sql_util.join_condition(t1, t2).compare(t1.c.x == t2.c.id)
assert sql_util.join_condition(t2, t1).compare(t1.c.x == t2.c.id)
def test_join_cond_no_such_unrelated_table_dont_compare_names(self):
m = MetaData()
t1 = Table(
"t1",
m,
Column("y", Integer, ForeignKey("t22.id")),
Column("x", Integer, ForeignKey("t2.id")),
Column("q", Integer, ForeignKey("t22.id")),
)
t2 = Table(
"t2",
m,
Column("id", Integer),
Column("t3id", ForeignKey("t3.id")),
Column("z", ForeignKey("t33.id")),
)
t3 = Table(
"t3", m, Column("id", Integer), Column("q", ForeignKey("t4.id"))
)
j1 = t1.join(t2)
assert sql_util.join_condition(j1, t3).compare(t2.c.t3id == t3.c.id)
def test_join_cond_no_such_unrelated_column_dont_compare_names(self):
m = MetaData()
t1 = Table(
"t1",
m,
Column("x", Integer, ForeignKey("t2.id")),
)
t2 = Table(
"t2",
m,
Column("id", Integer),
Column("t3id", ForeignKey("t3.id")),
Column("q", ForeignKey("t5.q")),
)
t3 = Table(
"t3", m, Column("id", Integer), Column("t4id", ForeignKey("t4.id"))
)
t4 = Table("t4", m, Column("id", Integer))
Table("t5", m, Column("id", Integer))
j1 = t1.join(t2)
j2 = t3.join(t4)
assert sql_util.join_condition(j1, j2).compare(t2.c.t3id == t3.c.id)
def test_join_cond_no_such_related_table(self):
m1 = MetaData()
m2 = MetaData()
t1 = Table("t1", m1, Column("x", Integer, ForeignKey("t2.id")))
t2 = Table("t2", m2, Column("id", Integer))
assert_raises_message(
exc.NoReferencedTableError,
"Foreign key associated with column 't1.x' could not find "
"table 't2' with which to generate a foreign key to "
"target column 'id'",
sql_util.join_condition,
t1,
t2,
)
assert_raises_message(
exc.NoReferencedTableError,
"Foreign key associated with column 't1.x' could not find "
"table 't2' with which to generate a foreign key to "
"target column 'id'",
sql_util.join_condition,
t2,
t1,
)
def test_join_cond_no_such_related_column(self):
m = MetaData()
t1 = Table("t1", m, Column("x", Integer, ForeignKey("t2.q")))
t2 = Table("t2", m, Column("id", Integer))
assert_raises_message(
exc.NoReferencedColumnError,
"Could not initialize target column for "
"ForeignKey 't2.q' on table 't1': "
"table 't2' has no column named 'q'",
sql_util.join_condition,
t1,
t2,
)
assert_raises_message(
exc.NoReferencedColumnError,
"Could not initialize target column for "
"ForeignKey 't2.q' on table 't1': "
"table 't2' has no column named 'q'",
sql_util.join_condition,
t2,
t1,
)
class PrimaryKeyTest(fixtures.TestBase, AssertsExecutionResults):
def test_join_pk_collapse_implicit(self):
"""test that redundant columns in a join get 'collapsed' into a
minimal primary key, which is the root column along a chain of
foreign key relationships."""
meta = MetaData()
a = Table("a", meta, Column("id", Integer, primary_key=True))
b = Table(
"b",
meta,
Column("id", Integer, ForeignKey("a.id"), primary_key=True),
)
c = Table(
"c",
meta,
Column("id", Integer, ForeignKey("b.id"), primary_key=True),
)
d = Table(
"d",
meta,
Column("id", Integer, ForeignKey("c.id"), primary_key=True),
)
assert c.c.id.references(b.c.id)
assert not d.c.id.references(a.c.id)
assert list(a.join(b).primary_key) == [a.c.id]
assert list(b.join(c).primary_key) == [b.c.id]
assert list(a.join(b).join(c).primary_key) == [a.c.id]
assert list(b.join(c).join(d).primary_key) == [b.c.id]
assert list(d.join(c).join(b).primary_key) == [b.c.id]
assert list(a.join(b).join(c).join(d).primary_key) == [a.c.id]
def test_join_pk_collapse_explicit(self):
"""test that redundant columns in a join get 'collapsed' into a
minimal primary key, which is the root column along a chain of
explicit join conditions."""
meta = MetaData()
a = Table(
"a",
meta,
Column("id", Integer, primary_key=True),
Column("x", Integer),
)
b = Table(
"b",
meta,
Column("id", Integer, ForeignKey("a.id"), primary_key=True),
Column("x", Integer),
)
c = Table(
"c",
meta,
Column("id", Integer, ForeignKey("b.id"), primary_key=True),
Column("x", Integer),
)
d = Table(
"d",
meta,
Column("id", Integer, ForeignKey("c.id"), primary_key=True),
Column("x", Integer),
)
print(list(a.join(b, a.c.x == b.c.id).primary_key))
assert list(a.join(b, a.c.x == b.c.id).primary_key) == [a.c.id]
assert list(b.join(c, b.c.x == c.c.id).primary_key) == [b.c.id]
assert list(a.join(b).join(c, c.c.id == b.c.x).primary_key) == [a.c.id]
assert list(b.join(c, c.c.x == b.c.id).join(d).primary_key) == [b.c.id]
assert list(b.join(c, c.c.id == b.c.x).join(d).primary_key) == [b.c.id]
assert list(
d.join(b, d.c.id == b.c.id).join(c, b.c.id == c.c.x).primary_key
) == [b.c.id]
assert list(
a.join(b).join(c, c.c.id == b.c.x).join(d).primary_key
) == [a.c.id]
assert list(
a.join(b, and_(a.c.id == b.c.id, a.c.x == b.c.id)).primary_key
) == [a.c.id]
def test_init_doesnt_blowitaway(self):
meta = MetaData()
a = Table(
"a",
meta,
Column("id", Integer, primary_key=True),
Column("x", Integer),
)
b = Table(
"b",
meta,
Column("id", Integer, ForeignKey("a.id"), primary_key=True),
Column("x", Integer),
)
j = a.join(b)
assert list(j.primary_key) == [a.c.id]
j.foreign_keys
assert list(j.primary_key) == [a.c.id]
def test_non_column_clause(self):
meta = MetaData()
a = Table(
"a",
meta,
Column("id", Integer, primary_key=True),
Column("x", Integer),
)
b = Table(
"b",
meta,
Column("id", Integer, ForeignKey("a.id"), primary_key=True),
Column("x", Integer, primary_key=True),
)
j = a.join(b, and_(a.c.id == b.c.id, b.c.x == 5))
assert str(j) == "a JOIN b ON a.id = b.id AND b.x = :x_1", str(j)
assert list(j.primary_key) == [a.c.id, b.c.x]
def test_onclause_direction(self):
metadata = MetaData()
employee = Table(
"Employee",
metadata,
Column("name", String(100)),
Column("id", Integer, primary_key=True),
)
engineer = Table(
"Engineer",
metadata,
Column("id", Integer, ForeignKey("Employee.id"), primary_key=True),
)
eq_(
util.column_set(
employee.join(
engineer, employee.c.id == engineer.c.id
).primary_key
),
util.column_set([employee.c.id]),
)
eq_(
util.column_set(
employee.join(
engineer, engineer.c.id == employee.c.id
).primary_key
),
util.column_set([employee.c.id]),
)
class ReduceTest(fixtures.TestBase, AssertsExecutionResults):
def test_reduce(self):
meta = MetaData()
t1 = Table(
"t1",
meta,
Column("t1id", Integer, primary_key=True),
Column("t1data", String(30)),
)
t2 = Table(
"t2",
meta,
Column("t2id", Integer, ForeignKey("t1.t1id"), primary_key=True),
Column("t2data", String(30)),
)
t3 = Table(
"t3",
meta,
Column("t3id", Integer, ForeignKey("t2.t2id"), primary_key=True),
Column("t3data", String(30)),
)
eq_(
util.column_set(
sql_util.reduce_columns(
[
t1.c.t1id,
t1.c.t1data,
t2.c.t2id,
t2.c.t2data,
t3.c.t3id,
t3.c.t3data,
]
)
),
util.column_set(
[t1.c.t1id, t1.c.t1data, t2.c.t2data, t3.c.t3data]
),
)
def test_reduce_selectable(self):
metadata = MetaData()
engineers = Table(
"engineers",
metadata,
Column("engineer_id", Integer, primary_key=True),
Column("engineer_name", String(50)),
)
managers = Table(
"managers",
metadata,
Column("manager_id", Integer, primary_key=True),
Column("manager_name", String(50)),
)
s = (
select(engineers, managers)
.where(engineers.c.engineer_name == managers.c.manager_name)
.subquery()
)
eq_(
util.column_set(sql_util.reduce_columns(list(s.c), s)),
util.column_set(
[s.c.engineer_id, s.c.engineer_name, s.c.manager_id]
),
)
def test_reduce_generation(self):
m = MetaData()
t1 = Table(
"t1",
m,
Column("x", Integer, primary_key=True),
Column("y", Integer),
)
t2 = Table(
"t2",
m,
Column("z", Integer, ForeignKey("t1.x")),
Column("q", Integer),
)
s1 = select(t1, t2)
s2 = s1.reduce_columns(only_synonyms=False)
eq_(set(s2.selected_columns), {t1.c.x, t1.c.y, t2.c.q})
s2 = s1.reduce_columns()
eq_(set(s2.selected_columns), {t1.c.x, t1.c.y, t2.c.z, t2.c.q})
def test_reduce_only_synonym_fk(self):
m = MetaData()
t1 = Table(
"t1",
m,
Column("x", Integer, primary_key=True),
Column("y", Integer),
)
t2 = Table(
"t2",
m,
Column("x", Integer, ForeignKey("t1.x")),
Column("q", Integer, ForeignKey("t1.y")),
)
s1 = select(t1, t2)
s1 = s1.reduce_columns(only_synonyms=True)
eq_(
set(s1.selected_columns),
{
s1.selected_columns.x,
s1.selected_columns.y,
s1.selected_columns.q,
},
)
def test_reduce_only_synonym_lineage(self):
m = MetaData()
t1 = Table(
"t1",
m,
Column("x", Integer, primary_key=True),
Column("y", Integer),
Column("z", Integer),
)
# test that the first appearance in the columns clause
# wins - t1 is first, t1.c.x wins
s1 = select(t1).subquery()
s2 = select(t1, s1).where(t1.c.x == s1.c.x).where(s1.c.y == t1.c.z)
eq_(
set(s2.reduce_columns().selected_columns),
{t1.c.x, t1.c.y, t1.c.z, s1.c.y, s1.c.z},
)
# reverse order, s1.c.x wins
s1 = select(t1).subquery()
s2 = select(s1, t1).where(t1.c.x == s1.c.x).where(s1.c.y == t1.c.z)
eq_(
set(s2.reduce_columns().selected_columns),
{s1.c.x, t1.c.y, t1.c.z, s1.c.y, s1.c.z},
)
def test_reduce_aliased_join(self):
metadata = MetaData()
people = Table(
"people",
metadata,
Column(
"person_id",
Integer,
normalize_sequence(
config, Sequence("person_id_seq", optional=True)
),
primary_key=True,
),
Column("name", String(50)),
Column("type", String(30)),
)
engineers = Table(
"engineers",
metadata,
Column(
"person_id",
Integer,
ForeignKey("people.person_id"),
primary_key=True,
),
Column("status", String(30)),
Column("engineer_name", String(50)),
Column("primary_language", String(50)),
)
managers = Table(
"managers",
metadata,
Column(
"person_id",
Integer,
ForeignKey("people.person_id"),
primary_key=True,
),
Column("status", String(30)),
Column("manager_name", String(50)),
)
pjoin = (
people.outerjoin(engineers)
.outerjoin(managers)
.select()
.set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
.alias("pjoin")
)
eq_(
util.column_set(
sql_util.reduce_columns(
[
pjoin.c.people_person_id,
pjoin.c.engineers_person_id,
pjoin.c.managers_person_id,
]
)
),
util.column_set([pjoin.c.people_person_id]),
)
def test_reduce_aliased_union(self):
metadata = MetaData()
item_table = Table(
"item",
metadata,
Column(
"id", Integer, ForeignKey("base_item.id"), primary_key=True
),
Column("dummy", Integer, default=0),
)
base_item_table = Table(
"base_item",
metadata,
Column("id", Integer, primary_key=True),
Column("child_name", String(255), default=None),
)
from sqlalchemy.orm.util import polymorphic_union
item_join = polymorphic_union(
{
"BaseItem": base_item_table.select()
.where(base_item_table.c.child_name == "BaseItem")
.subquery(),
"Item": base_item_table.join(item_table),
},
None,
"item_join",
)
eq_(
util.column_set(
sql_util.reduce_columns(
[item_join.c.id, item_join.c.dummy, item_join.c.child_name]
)
),
util.column_set(
[item_join.c.id, item_join.c.dummy, item_join.c.child_name]
),
)
def test_reduce_aliased_union_2(self):
metadata = MetaData()
page_table = Table(
"page", metadata, Column("id", Integer, primary_key=True)
)
magazine_page_table = Table(
"magazine_page",
metadata,
Column(
"page_id", Integer, ForeignKey("page.id"), primary_key=True
),
)
classified_page_table = Table(
"classified_page",
metadata,
Column(
"magazine_page_id",
Integer,
ForeignKey("magazine_page.page_id"),
primary_key=True,
),
)
# this is essentially the union formed by the ORM's
# polymorphic_union function. we define two versions with
# different ordering of selects.
#
# the first selectable has the "real" column
# classified_page.magazine_page_id
pjoin = union(
select(
page_table.c.id,
magazine_page_table.c.page_id,
classified_page_table.c.magazine_page_id,
).select_from(
page_table.join(magazine_page_table).join(
classified_page_table
)
),
select(
page_table.c.id,
magazine_page_table.c.page_id,
cast(null(), Integer).label("magazine_page_id"),
).select_from(page_table.join(magazine_page_table)),
).alias("pjoin")
eq_(
util.column_set(
sql_util.reduce_columns(
[pjoin.c.id, pjoin.c.page_id, pjoin.c.magazine_page_id]
)
),
util.column_set([pjoin.c.id]),
)
# the first selectable has a CAST, which is a placeholder for
# classified_page.magazine_page_id in the second selectable.
# reduce_columns needs to take into account all foreign keys
# derived from pjoin.c.magazine_page_id. the UNION construct
# currently makes the external column look like that of the
# first selectable only.
pjoin = union(
select(
page_table.c.id,
magazine_page_table.c.page_id,
cast(null(), Integer).label("magazine_page_id"),
).select_from(page_table.join(magazine_page_table)),
select(
page_table.c.id,
magazine_page_table.c.page_id,
classified_page_table.c.magazine_page_id,
).select_from(
page_table.join(magazine_page_table).join(
classified_page_table
)
),
).alias("pjoin")
eq_(
util.column_set(
sql_util.reduce_columns(
[pjoin.c.id, pjoin.c.page_id, pjoin.c.magazine_page_id]
)
),
util.column_set([pjoin.c.id]),
)
class DerivedTest(fixtures.TestBase, AssertsExecutionResults):
def test_table(self):
meta = MetaData()
t1 = Table(
"t1",
meta,
Column("c1", Integer, primary_key=True),
Column("c2", String(30)),
)
t2 = Table(
"t2",
meta,
Column("c1", Integer, primary_key=True),
Column("c2", String(30)),
)
assert t1.is_derived_from(t1)
assert not t2.is_derived_from(t1)
def test_alias(self):
meta = MetaData()
t1 = Table(
"t1",
meta,
Column("c1", Integer, primary_key=True),
Column("c2", String(30)),
)
t2 = Table(
"t2",
meta,
Column("c1", Integer, primary_key=True),
Column("c2", String(30)),
)
assert t1.alias().is_derived_from(t1)
assert not t2.alias().is_derived_from(t1)
assert not t1.is_derived_from(t1.alias())
assert not t1.is_derived_from(t2.alias())
def test_select(self):
meta = MetaData()
t1 = Table(
"t1",
meta,
Column("c1", Integer, primary_key=True),
Column("c2", String(30)),
)
t2 = Table(
"t2",
meta,
Column("c1", Integer, primary_key=True),
Column("c2", String(30)),
)
assert t1.select().is_derived_from(t1)
assert not t2.select().is_derived_from(t1)
assert select(t1, t2).is_derived_from(t1)
assert t1.select().alias("foo").is_derived_from(t1)
assert select(t1, t2).alias("foo").is_derived_from(t1)
assert not t2.select().alias("foo").is_derived_from(t1)
def test_join(self):
meta = MetaData()
t1 = Table(
"t1",
meta,
Column("c1", Integer, primary_key=True),
Column("c2", String(30)),
)
t2 = Table(
"t2",
meta,
Column("c1", Integer, primary_key=True),
Column("c2", String(30)),
)
t3 = Table(
"t3",
meta,
Column("c1", Integer, primary_key=True),
Column("c2", String(30)),
)
j1 = t1.join(t2, t1.c.c1 == t2.c.c1)
assert j1.is_derived_from(j1)
assert j1.is_derived_from(t1)
assert j1._annotate({"foo": "bar"}).is_derived_from(j1)
assert not j1.is_derived_from(t3)
class AnnotationsTest(fixtures.TestBase):
def test_hashing(self):
t = table("t", column("x"))
a = t.alias()
for obj in [t, t.c.x, a, t.c.x > 1, (t.c.x > 1).label(None)]:
annot = obj._annotate({})
eq_({obj}, {annot})
def test_clone_annotations_dont_hash(self):
t = table("t", column("x"))
s = t.select()
a = t.alias()
s2 = a.select()
for obj in [s, s2]:
annot = obj._annotate({})
ne_({obj}, {annot})
def test_replacement_traverse_preserve(self):
"""test that replacement traverse that hits an unannotated column
does not use it when replacing an annotated column.
this requires that replacement traverse store elements in the
"seen" hash based on id(), not hash.
"""
t = table("t", column("x"))
stmt = select(t.c.x)
whereclause = annotation._deep_annotate(t.c.x == 5, {"foo": "bar"})
eq_(whereclause._annotations, {"foo": "bar"})
eq_(whereclause.left._annotations, {"foo": "bar"})
eq_(whereclause.right._annotations, {"foo": "bar"})
stmt = stmt.where(whereclause)
s2 = visitors.replacement_traverse(stmt, {}, lambda elem: None)
whereclause = s2._where_criteria[0]
eq_(whereclause._annotations, {"foo": "bar"})
eq_(whereclause.left._annotations, {"foo": "bar"})
eq_(whereclause.right._annotations, {"foo": "bar"})
@testing.combinations(True, False, None)
def test_setup_inherit_cache(self, inherit_cache_value):
if inherit_cache_value is None:
class MyInsertThing(Insert):
pass
else:
class MyInsertThing(Insert):
inherit_cache = inherit_cache_value
t = table("t", column("x"))
anno = MyInsertThing(t)._annotate({"foo": "bar"})
if inherit_cache_value is not None:
is_(type(anno).__dict__["inherit_cache"], inherit_cache_value)
else:
assert "inherit_cache" not in type(anno).__dict__
def test_proxy_set_iteration_includes_annotated(self):
from sqlalchemy.schema import Column
c1 = Column("foo", Integer)
stmt = select(c1).alias()
proxy = stmt.c.foo
proxy.proxy_set
# create an annotated of the column
p2 = proxy._annotate({"weight": 10})
# now see if our annotated version is in that column's
# proxy_set, as corresponding_column iterates through proxy_set
# in this way
d = {}
for col in p2._uncached_proxy_list():
d.update(col._annotations)
eq_(d, {"weight": 10})
def test_proxy_set_iteration_includes_annotated_two(self):
from sqlalchemy.schema import Column
c1 = Column("foo", Integer)
stmt = select(c1).alias()
proxy = stmt.c.foo
c1.proxy_set
proxy._proxies = [c1._annotate({"weight": 10})]
d = {}
for col in proxy._uncached_proxy_list():
d.update(col._annotations)
eq_(d, {"weight": 10})
def test_late_name_add(self):
from sqlalchemy.schema import Column
c1 = Column(Integer)
c1_a = c1._annotate({"foo": "bar"})
c1.name = "somename"
eq_(c1_a.name, "somename")
def test_late_table_add(self):
c1 = Column("foo", Integer)
c1_a = c1._annotate({"foo": "bar"})
t = Table("t", MetaData(), c1)
is_(c1_a.table, t)
def test_basic_attrs(self):
t = Table(
"t",
MetaData(),
Column("x", Integer, info={"q": "p"}),
Column("y", Integer, key="q"),
)
x_a = t.c.x._annotate({})
y_a = t.c.q._annotate({})
t.c.x.info["z"] = "h"
eq_(y_a.key, "q")
is_(x_a.table, t)
eq_(x_a.info, {"q": "p", "z": "h"})
eq_(t.c.x._anon_name_label, x_a._anon_name_label)
def test_custom_constructions(self):
from sqlalchemy.schema import Column
class MyColumn(Column):
def __init__(self):
Column.__init__(self, "foo", Integer)
_constructor = Column
t1 = Table("t1", MetaData(), MyColumn())
s1 = t1.select().subquery()
assert isinstance(t1.c.foo, MyColumn)
assert isinstance(s1.c.foo, Column)
annot_1 = t1.c.foo._annotate({})
s2 = select(annot_1).subquery()
assert isinstance(s2.c.foo, Column)
annot_2 = s1._annotate({})
assert isinstance(annot_2.c.foo, Column)
def test_custom_construction_correct_anno_subclass(self):
# [ticket:2918]
from sqlalchemy.schema import Column
from sqlalchemy.sql.elements import AnnotatedColumnElement
class MyColumn(Column):
pass
assert isinstance(
MyColumn("x", Integer)._annotate({"foo": "bar"}),
AnnotatedColumnElement,
)
def test_custom_construction_correct_anno_expr(self):
# [ticket:2918]
from sqlalchemy.schema import Column
class MyColumn(Column):
pass
col = MyColumn("x", Integer)
col == 5
col_anno = MyColumn("x", Integer)._annotate({"foo": "bar"})
binary_2 = col_anno == 5
eq_(binary_2.left._annotations, {"foo": "bar"})
@testing.combinations(
("plain",),
("annotated",),
("deep_annotated",),
("deep_annotated_w_ind_col",),
argnames="testcase",
)
def test_annotated_corresponding_column(self, testcase):
"""ensures the require_embedded case remains when an inner statement
was copied out for annotations.
First implemented in 2008 in d3621ae961a, the implementation is
updated for #8796 as a performance improvement as well as to
establish a discovered implicit behavior where clone() would break
the contract of corresponding_column() into an explicit option,
fixing the implicit behavior.
"""
table1 = table("table1", column("col1"))
s1 = select(table1.c.col1).subquery()
expect_same = True
if testcase == "plain":
t1 = s1
elif testcase == "annotated":
t1 = s1._annotate({})
elif testcase == "deep_annotated":
# was failing prior to #8796
t1 = sql_util._deep_annotate(s1, {"foo": "bar"})
elif testcase == "deep_annotated_w_ind_col":
# was implicit behavior w/ annotate prior to #8796
t1 = sql_util._deep_annotate(
s1, {"foo": "bar"}, ind_cols_on_fromclause=True
)
expect_same = False
else:
assert False
# t1 needs to share the same _make_proxy() columns as t2, even
# though it's annotated. otherwise paths will diverge once they
# are corresponded against "inner" below.
if expect_same:
assert t1.c is s1.c
assert t1.c.col1 is s1.c.col1
else:
assert t1.c is not s1.c
assert t1.c.col1 is not s1.c.col1
inner = select(s1).subquery()
assert (
inner.corresponding_column(t1.c.col1, require_embedded=False)
is inner.c.col1
)
if expect_same:
assert (
inner.corresponding_column(t1.c.col1, require_embedded=True)
is inner.c.col1
)
else:
assert (
inner.corresponding_column(t1.c.col1, require_embedded=True)
is not inner.c.col1
)
def test_annotated_visit(self):
table1 = table("table1", column("col1"), column("col2"))
bin_ = table1.c.col1 == bindparam("foo", value=None)
assert str(bin_) == "table1.col1 = :foo"
def visit_binary(b):
b.right = table1.c.col2
b2 = visitors.cloned_traverse(bin_, {}, {"binary": visit_binary})
assert str(b2) == "table1.col1 = table1.col2"
b3 = visitors.cloned_traverse(
bin_._annotate({}), {}, {"binary": visit_binary}
)
assert str(b3) == "table1.col1 = table1.col2"
def visit_binary(b):
b.left = bindparam("bar")
b4 = visitors.cloned_traverse(b2, {}, {"binary": visit_binary})
assert str(b4) == ":bar = table1.col2"
b5 = visitors.cloned_traverse(b3, {}, {"binary": visit_binary})
assert str(b5) == ":bar = table1.col2"
def test_label_accessors(self):
t1 = table("t1", column("c1"))
l1 = t1.c.c1.label(None)
is_(l1._order_by_label_element, l1)
l1a = l1._annotate({"foo": "bar"})
is_(l1a._order_by_label_element, l1a)
def test_annotate_aliased(self):
t1 = table("t1", column("c1"))
s = select((t1.c.c1 + 3).label("bat"))
a = s.alias()
a = sql_util._deep_annotate(a, {"foo": "bar"})
eq_(a._annotations["foo"], "bar")
eq_(a.element._annotations["foo"], "bar")
def test_annotate_expressions(self):
table1 = table("table1", column("col1"), column("col2"))
for expr, expected in [
(table1.c.col1, "table1.col1"),
(table1.c.col1 == 5, "table1.col1 = :col1_1"),
(
table1.c.col1.in_([2, 3, 4]),
"table1.col1 IN (__[POSTCOMPILE_col1_1])",
),
]:
eq_(str(expr), expected)
eq_(str(expr._annotate({})), expected)
eq_(str(sql_util._deep_annotate(expr, {})), expected)
eq_(
str(
sql_util._deep_annotate(expr, {}, exclude=[table1.c.col1])
),
expected,
)
def test_deannotate_wrapping(self):
table1 = table("table1", column("col1"), column("col2"))
bin_ = table1.c.col1 == bindparam("foo", value=None)
b2 = sql_util._deep_annotate(bin_, {"_orm_adapt": True})
b3 = sql_util._deep_deannotate(b2)
b4 = sql_util._deep_deannotate(bin_)
for elem in (b2._annotations, b2.left._annotations):
in_("_orm_adapt", elem)
for elem in (
b3._annotations,
b3.left._annotations,
b4._annotations,
b4.left._annotations,
):
eq_(elem, {})
is_not(b2.left, bin_.left)
is_not(b3.left, b2.left)
is_not(b2.left, bin_.left)
is_(b4.left, bin_.left) # since column is immutable
# deannotate copies the element
is_not(bin_.right, b2.right)
is_not(b2.right, b3.right)
is_not(b3.right, b4.right)
def test_deannotate_clone(self):
table1 = table("table1", column("col1"), column("col2"))
subq = (
select(table1).where(table1.c.col1 == bindparam("foo")).subquery()
)
stmt = select(subq)
s2 = sql_util._deep_annotate(stmt, {"_orm_adapt": True})
s3 = sql_util._deep_deannotate(s2)
s4 = sql_util._deep_deannotate(s3)
eq_(stmt._annotations, {})
eq_(subq._annotations, {})
eq_(s2._annotations, {"_orm_adapt": True})
eq_(s3._annotations, {})
eq_(s4._annotations, {})
# select._raw_columns[0] is the subq object
eq_(s2._raw_columns[0]._annotations, {"_orm_adapt": True})
eq_(s3._raw_columns[0]._annotations, {})
eq_(s4._raw_columns[0]._annotations, {})
is_not(s3, s2)
is_not(s4, s3) # deep deannotate makes a clone unconditionally
is_(s3._deannotate(), s3) # regular deannotate returns same object
def test_annotate_unique_traversal(self):
"""test that items are copied only once during
annotate, deannotate traversal
#2453 - however note this was modified by
#1401, and it's likely that re49563072578
is helping us with the str() comparison
case now, as deannotate is making
clones again in some cases.
"""
table1 = table("table1", column("x"))
table2 = table("table2", column("y"))
a1 = table1.alias()
s = select(a1.c.x).select_from(a1.join(table2, a1.c.x == table2.c.y))
for sel in (
sql_util._deep_deannotate(s),
visitors.cloned_traverse(s, {}, {}),
visitors.replacement_traverse(s, {}, lambda x: None),
):
# the columns clause isn't changed at all
assert sel._raw_columns[0].table is a1
froms = list(sel._iterate_from_elements())
assert froms[0].element is froms[1].left.element
eq_(str(s), str(sel))
# when we are modifying annotations sets only
# partially, elements are copied uniquely based on id().
# this is new as of 1.4, previously they'd be copied every time
for sel in (
sql_util._deep_deannotate(s, {"foo": "bar"}),
sql_util._deep_annotate(s, {"foo": "bar"}),
):
froms = list(sel._iterate_from_elements())
assert froms[0] is not froms[1].left
# but things still work out due to
# re49563072578
eq_(str(s), str(sel))
def test_annotate_varied_annot_same_col(self):
"""test two instances of the same column with different annotations
preserving them when deep_annotate is run on them.
"""
t1 = table("table1", column("col1"), column("col2"))
s = select(t1.c.col1._annotate({"foo": "bar"}))
s2 = select(t1.c.col1._annotate({"bat": "hoho"}))
s3 = s.union(s2)
sel = sql_util._deep_annotate(s3, {"new": "thing"})
eq_(
sel.selects[0]._raw_columns[0]._annotations,
{"foo": "bar", "new": "thing"},
)
eq_(
sel.selects[1]._raw_columns[0]._annotations,
{"bat": "hoho", "new": "thing"},
)
def test_deannotate_2(self):
table1 = table("table1", column("col1"), column("col2"))
j = table1.c.col1._annotate(
{"remote": True}
) == table1.c.col2._annotate({"local": True})
j2 = sql_util._deep_deannotate(j)
eq_(j.left._annotations, {"remote": True})
eq_(j2.left._annotations, {})
def test_deannotate_3(self):
table1 = table(
"table1",
column("col1"),
column("col2"),
column("col3"),
column("col4"),
)
j = and_(
table1.c.col1._annotate({"remote": True})
== table1.c.col2._annotate({"local": True}),
table1.c.col3._annotate({"remote": True})
== table1.c.col4._annotate({"local": True}),
)
j2 = sql_util._deep_deannotate(j)
eq_(j.clauses[0].left._annotations, {"remote": True})
eq_(j2.clauses[0].left._annotations, {})
def test_annotate_fromlist_preservation(self):
"""test the FROM list in select still works
even when multiple annotate runs have created
copies of the same selectable
#2453, continued
"""
table1 = table("table1", column("x"))
table2 = table("table2", column("y"))
a1 = table1.alias()
s = select(a1.c.x).select_from(a1.join(table2, a1.c.x == table2.c.y))
assert_s = select(select(s.subquery()).subquery())
for fn in (
sql_util._deep_deannotate,
lambda s: sql_util._deep_annotate(s, {"foo": "bar"}),
lambda s: visitors.cloned_traverse(s, {}, {}),
lambda s: visitors.replacement_traverse(s, {}, lambda x: None),
):
sel = fn(select(fn(select(fn(s.subquery())).subquery())))
eq_(str(assert_s), str(sel))
def test_bind_unique_test(self):
table("t", column("a"), column("b"))
b = bindparam("bind", value="x", unique=True)
# the annotation of "b" should render the
# same. The "unique" test in compiler should
# also pass, [ticket:2425]
eq_(str(or_(b, b._annotate({"foo": "bar"}))), ":bind_1 OR :bind_1")
def test_comparators_cleaned_out_construction(self):
c = column("a")
comp1 = c.comparator
c1 = c._annotate({"foo": "bar"})
comp2 = c1.comparator
assert comp1 is not comp2
def test_comparators_cleaned_out_reannotate(self):
c = column("a")
c1 = c._annotate({"foo": "bar"})
comp1 = c1.comparator
c2 = c1._annotate({"bat": "hoho"})
comp2 = c2.comparator
assert comp1 is not comp2
def test_comparator_cleanout_integration(self):
c = column("a")
c1 = c._annotate({"foo": "bar"})
c1.comparator
c2 = c1._annotate({"bat": "hoho"})
c2.comparator
assert (c2 == 5).left._annotations == {"foo": "bar", "bat": "hoho"}
class ReprTest(fixtures.TestBase):
def test_ensure_repr_elements(self):
for obj in [
elements.Cast(1, Integer()),
elements.TypeClause(String()),
elements.ColumnClause("x"),
elements.BindParameter("q"),
elements.Null(),
elements.True_(),
elements.False_(),
elements.ClauseList(),
elements.BooleanClauseList._construct_raw(operators.and_),
elements.BooleanClauseList._construct_raw(operators.or_),
elements.Tuple(),
elements.Case(),
elements.Extract("foo", column("x")),
elements.UnaryExpression(column("x")),
elements.Grouping(column("x")),
elements.Over(func.foo()),
elements.Label("q", column("x")),
]:
repr(obj)
class WithLabelsTest(AssertsCompiledSQL, fixtures.TestBase):
def _assert_result_keys(self, s, keys):
compiled = s.compile()
eq_(set(compiled._create_result_map()), set(keys))
def _assert_subq_result_keys(self, s, keys):
compiled = s.subquery().select().compile()
eq_(set(compiled._create_result_map()), set(keys))
def _names_overlap(self):
m = MetaData()
t1 = Table("t1", m, Column("x", Integer))
t2 = Table("t2", m, Column("x", Integer))
return select(t1, t2).set_label_style(LABEL_STYLE_NONE)
def test_names_overlap_nolabel(self):
sel = self._names_overlap()
self._assert_result_keys(sel, ["x"])
self._assert_subq_result_keys(sel, ["x", "x_1"])
eq_(sel.selected_columns.keys(), ["x", "x"])
def test_names_overlap_label(self):
sel = self._names_overlap().set_label_style(
LABEL_STYLE_TABLENAME_PLUS_COL
)
eq_(sel.selected_columns.keys(), ["t1_x", "t2_x"])
eq_(list(sel.selected_columns.keys()), ["t1_x", "t2_x"])
eq_(list(sel.subquery().c.keys()), ["t1_x", "t2_x"])
self._assert_result_keys(sel, ["t1_x", "t2_x"])
def _names_overlap_keys_dont(self):
m = MetaData()
t1 = Table("t1", m, Column("x", Integer, key="a"))
t2 = Table("t2", m, Column("x", Integer, key="b"))
return select(t1, t2).set_label_style(LABEL_STYLE_NONE)
def test_names_overlap_keys_dont_nolabel(self):
sel = self._names_overlap_keys_dont()
eq_(sel.selected_columns.keys(), ["a", "b"])
eq_(list(sel.selected_columns.keys()), ["a", "b"])
eq_(list(sel.subquery().c.keys()), ["a", "b"])
self._assert_result_keys(sel, ["x"])
def test_names_overlap_keys_dont_label(self):
sel = self._names_overlap_keys_dont().set_label_style(
LABEL_STYLE_TABLENAME_PLUS_COL
)
eq_(sel.selected_columns.keys(), ["t1_a", "t2_b"])
eq_(list(sel.selected_columns.keys()), ["t1_a", "t2_b"])
eq_(list(sel.subquery().c.keys()), ["t1_a", "t2_b"])
self._assert_result_keys(sel, ["t1_x", "t2_x"])
def _columns_repeated(self):
m = MetaData()
t1 = Table("t1", m, Column("x", Integer), Column("y", Integer))
return select(t1.c.x, t1.c.y, t1.c.x).set_label_style(LABEL_STYLE_NONE)
def test_element_repeated_nolabels(self):
sel = self._columns_repeated().set_label_style(LABEL_STYLE_NONE)
eq_(sel.selected_columns.keys(), ["x", "y", "x"])
eq_(list(sel.selected_columns.keys()), ["x", "y", "x"])
eq_(list(sel.subquery().c.keys()), ["x", "y", "x_1"])
self._assert_result_keys(sel, ["x", "y"])
def test_element_repeated_disambiguate(self):
sel = self._columns_repeated().set_label_style(
LABEL_STYLE_DISAMBIGUATE_ONLY
)
eq_(sel.selected_columns.keys(), ["x", "y", "x_1"])
eq_(list(sel.selected_columns.keys()), ["x", "y", "x_1"])
eq_(list(sel.subquery().c.keys()), ["x", "y", "x_1"])
self._assert_result_keys(sel, ["x", "y", "x__1"])
def test_element_repeated_labels(self):
sel = self._columns_repeated().set_label_style(
LABEL_STYLE_TABLENAME_PLUS_COL
)
eq_(sel.selected_columns.keys(), ["t1_x", "t1_y", "t1_x_1"])
eq_(list(sel.selected_columns.keys()), ["t1_x", "t1_y", "t1_x_1"])
eq_(list(sel.subquery().c.keys()), ["t1_x", "t1_y", "t1_x_1"])
self._assert_result_keys(sel, ["t1_x__1", "t1_x", "t1_y"])
def _columns_repeated_identity(self):
m = MetaData()
t1 = Table("t1", m, Column("x", Integer), Column("y", Integer))
return select(t1.c.x, t1.c.y, t1.c.x, t1.c.x, t1.c.x).set_label_style(
LABEL_STYLE_NONE
)
def _anon_columns_repeated_identity_one(self):
m = MetaData()
t1 = Table("t1", m, Column("x", Integer), Column("y", Integer))
return select(t1.c.x, null(), null(), null()).set_label_style(
LABEL_STYLE_NONE
)
def _anon_columns_repeated_identity_two(self):
fn = func.now()
return select(fn, fn, fn, fn).set_label_style(LABEL_STYLE_NONE)
def test_columns_repeated_identity_disambiguate(self):
"""test #7153"""
sel = self._columns_repeated_identity().set_label_style(
LABEL_STYLE_DISAMBIGUATE_ONLY
)
self.assert_compile(
sel,
"SELECT t1.x, t1.y, t1.x AS x__1, t1.x AS x__2, "
"t1.x AS x__3 FROM t1",
)
def test_columns_repeated_identity_subquery_disambiguate(self):
"""test #7153"""
sel = self._columns_repeated_identity()
stmt = select(sel.subquery()).set_label_style(
LABEL_STYLE_DISAMBIGUATE_ONLY
)
# databases like MySQL won't allow the subquery to have repeated labels
# even if we don't try to access them
self.assert_compile(
stmt,
"SELECT anon_1.x, anon_1.y, anon_1.x AS x_1, anon_1.x AS x_2, "
"anon_1.x AS x_3 FROM "
"(SELECT t1.x AS x, t1.y AS y, t1.x AS x__1, t1.x AS x__2, "
"t1.x AS x__3 FROM t1) AS anon_1",
)
def _labels_overlap(self):
m = MetaData()
t1 = Table("t", m, Column("x_id", Integer))
t2 = Table("t_x", m, Column("id", Integer))
return select(t1, t2)
def test_labels_overlap_nolabel(self):
sel = self._labels_overlap()
eq_(sel.selected_columns.keys(), ["x_id", "id"])
eq_(list(sel.selected_columns.keys()), ["x_id", "id"])
eq_(list(sel.subquery().c.keys()), ["x_id", "id"])
self._assert_result_keys(sel, ["x_id", "id"])
def test_labels_overlap_label(self):
sel = self._labels_overlap().set_label_style(
LABEL_STYLE_TABLENAME_PLUS_COL
)
eq_(
list(sel.selected_columns.keys()),
["t_x_id", "t_x_id_1"],
)
eq_(
list(sel.subquery().c.keys()),
["t_x_id", "t_x_id_1"],
# ["t_x_id", "t_x_id"] # if we turn off deduping entirely,
)
self._assert_result_keys(sel, ["t_x_id", "t_x_id_1"])
self._assert_subq_result_keys(sel, ["t_x_id", "t_x_id_1"])
def _labels_overlap_keylabels_dont(self):
m = MetaData()
t1 = Table("t", m, Column("x_id", Integer, key="a"))
t2 = Table("t_x", m, Column("id", Integer, key="b"))
return select(t1, t2)
def test_labels_overlap_keylabels_dont_nolabel(self):
sel = self._labels_overlap_keylabels_dont()
eq_(list(sel.selected_columns.keys()), ["a", "b"])
eq_(list(sel.subquery().c.keys()), ["a", "b"])
self._assert_result_keys(sel, ["x_id", "id"])
def test_labels_overlap_keylabels_dont_label(self):
sel = self._labels_overlap_keylabels_dont().set_label_style(
LABEL_STYLE_TABLENAME_PLUS_COL
)
eq_(list(sel.selected_columns.keys()), ["t_a", "t_x_b"])
eq_(list(sel.subquery().c.keys()), ["t_a", "t_x_b"])
self._assert_result_keys(sel, ["t_x_id", "t_x_id_1"])
def _keylabels_overlap_labels_dont(self):
m = MetaData()
t1 = Table("t", m, Column("a", Integer, key="x_id"))
t2 = Table("t_x", m, Column("b", Integer, key="id"))
return select(t1, t2)
def test_keylabels_overlap_labels_dont_nolabel(self):
sel = self._keylabels_overlap_labels_dont()
eq_(list(sel.selected_columns.keys()), ["x_id", "id"])
eq_(list(sel.subquery().c.keys()), ["x_id", "id"])
self._assert_result_keys(sel, ["a", "b"])
def test_keylabels_overlap_labels_dont_label(self):
sel = self._keylabels_overlap_labels_dont().set_label_style(
LABEL_STYLE_TABLENAME_PLUS_COL
)
eq_(
list(sel.selected_columns.keys()),
["t_x_id", "t_x_id_1"],
)
eq_(
list(sel.subquery().c.keys()),
["t_x_id", "t_x_id_1"],
)
self._assert_result_keys(sel, ["t_a", "t_x_b"])
self._assert_subq_result_keys(sel, ["t_a", "t_x_b"])
def _keylabels_overlap_labels_overlap(self):
m = MetaData()
t1 = Table("t", m, Column("x_id", Integer, key="x_a"))
t2 = Table("t_x", m, Column("id", Integer, key="a"))
return select(t1, t2)
def test_keylabels_overlap_labels_overlap_nolabel(self):
sel = self._keylabels_overlap_labels_overlap()
eq_(list(sel.selected_columns.keys()), ["x_a", "a"])
eq_(list(sel.subquery().c.keys()), ["x_a", "a"])
self._assert_result_keys(sel, ["x_id", "id"])
self._assert_subq_result_keys(sel, ["x_id", "id"])
def test_keylabels_overlap_labels_overlap_label(self):
sel = self._keylabels_overlap_labels_overlap().set_label_style(
LABEL_STYLE_TABLENAME_PLUS_COL
)
eq_(
list(sel.selected_columns.keys()),
["t_x_a", "t_x_a_1"],
)
# deduping for different cols but same label
eq_(list(sel.subquery().c.keys()), ["t_x_a", "t_x_a_1"])
# if we turn off deduping entirely
# eq_(list(sel.subquery().c.keys()), ["t_x_a", "t_x_a"])
self._assert_result_keys(sel, ["t_x_id", "t_x_id_1"])
self._assert_subq_result_keys(sel, ["t_x_id", "t_x_id_1"])
def _keys_overlap_names_dont(self):
m = MetaData()
t1 = Table("t1", m, Column("a", Integer, key="x"))
t2 = Table("t2", m, Column("b", Integer, key="x"))
return select(t1, t2)
def test_keys_overlap_names_dont_nolabel(self):
sel = self._keys_overlap_names_dont()
eq_(sel.selected_columns.keys(), ["x", "x_1"])
self._assert_result_keys(sel, ["a", "b"])
def test_keys_overlap_names_dont_label(self):
sel = self._keys_overlap_names_dont().set_label_style(
LABEL_STYLE_TABLENAME_PLUS_COL
)
eq_(list(sel.selected_columns.keys()), ["t1_x", "t2_x"])
eq_(list(sel.subquery().c.keys()), ["t1_x", "t2_x"])
self._assert_result_keys(sel, ["t1_a", "t2_b"])
class ResultMapTest(fixtures.TestBase):
def _fixture(self):
m = MetaData()
t = Table("t", m, Column("x", Integer), Column("y", Integer))
return t
def _mapping(self, stmt):
compiled = stmt.compile()
return {
elem: key
for key, elements in compiled._create_result_map().items()
for elem in elements[1]
}
def test_select_label_alt_name(self):
t = self._fixture()
l1, l2 = t.c.x.label("a"), t.c.y.label("b")
s = select(l1, l2)
mapping = self._mapping(s)
assert l1 in mapping
assert t.c.x not in mapping
def test_select_alias_label_alt_name(self):
t = self._fixture()
l1, l2 = t.c.x.label("a"), t.c.y.label("b")
s = select(l1, l2).alias()
mapping = self._mapping(s)
assert l1 in mapping
assert t.c.x not in mapping
def test_select_alias_column(self):
t = self._fixture()
x, y = t.c.x, t.c.y
s = select(x, y).alias()
mapping = self._mapping(s)
assert t.c.x in mapping
def test_select_alias_column_apply_labels(self):
t = self._fixture()
x, y = t.c.x, t.c.y
s = (
select(x, y)
.set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
.alias()
)
mapping = self._mapping(s)
assert t.c.x in mapping
def test_select_table_alias_column(self):
t = self._fixture()
x = t.c.x
ta = t.alias()
s = select(ta.c.x, ta.c.y)
mapping = self._mapping(s)
assert x not in mapping
def test_select_label_alt_name_table_alias_column(self):
t = self._fixture()
x = t.c.x
ta = t.alias()
l1, l2 = ta.c.x.label("a"), ta.c.y.label("b")
s = select(l1, l2)
mapping = self._mapping(s)
assert x not in mapping
assert l1 in mapping
assert ta.c.x not in mapping
def test_column_subquery_exists(self):
t = self._fixture()
s = exists().where(t.c.x == 5).select()
mapping = self._mapping(s)
assert t.c.x not in mapping
eq_(
[type(entry[-1]) for entry in s.compile()._result_columns],
[Boolean],
)
def test_plain_exists(self):
expr = exists(text("1"))
eq_(type(expr.type), Boolean)
eq_(
[
type(entry[-1])
for entry in select(expr).compile()._result_columns
],
[Boolean],
)
def test_plain_exists_negate(self):
expr = ~exists(text("1"))
eq_(type(expr.type), Boolean)
eq_(
[
type(entry[-1])
for entry in select(expr).compile()._result_columns
],
[Boolean],
)
def test_plain_exists_double_negate(self):
expr = ~(~exists(text("1")))
eq_(type(expr.type), Boolean)
eq_(
[
type(entry[-1])
for entry in select(expr).compile()._result_columns
],
[Boolean],
)
def test_column_subquery_plain(self):
t = self._fixture()
s1 = select(t.c.x).where(t.c.x > 5).scalar_subquery()
s2 = select(s1)
mapping = self._mapping(s2)
assert t.c.x not in mapping
assert s1 in mapping
eq_(
[type(entry[-1]) for entry in s2.compile()._result_columns],
[Integer],
)
def test_unary_boolean(self):
s1 = select(not_(True)).set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
eq_(
[type(entry[-1]) for entry in s1.compile()._result_columns],
[Boolean],
)
class ForUpdateTest(fixtures.TestBase, AssertsCompiledSQL):
__dialect__ = "default"
def test_basic_clone(self):
t = table("t", column("c"))
s = select(t).with_for_update(read=True, of=t.c.c)
s2 = visitors.ReplacingCloningVisitor().traverse(s)
assert s2._for_update_arg is not s._for_update_arg
eq_(s2._for_update_arg.read, True)
eq_(s2._for_update_arg.of, [t.c.c])
self.assert_compile(
s2, "SELECT t.c FROM t FOR SHARE OF t", dialect="postgresql"
)
def test_adapt(self):
t = table("t", column("c"))
s = select(t).with_for_update(read=True, of=t.c.c)
a = t.alias()
s2 = sql_util.ClauseAdapter(a).traverse(s)
eq_(s2._for_update_arg.of, [a.c.c])
self.assert_compile(
s2,
"SELECT t_1.c FROM t AS t_1 FOR SHARE OF t_1",
dialect="postgresql",
)
class AliasTest(fixtures.TestBase, AssertsCompiledSQL):
__dialect__ = "default"
def test_direct_element_hierarchy(self):
t = table("t", column("c"))
a1 = t.alias()
a2 = a1.alias()
a3 = a2.alias()
is_(a1.element, t)
is_(a2.element, a1)
is_(a3.element, a2)
def test_get_children_preserves_multiple_nesting(self):
t = table("t", column("c"))
stmt = select(t)
a1 = stmt.alias()
a2 = a1.alias()
eq_(set(a2.get_children(column_collections=False)), {a1})
def test_correspondence_multiple_nesting(self):
t = table("t", column("c"))
stmt = select(t)
a1 = stmt.alias()
a2 = a1.alias()
is_(a1.corresponding_column(a2.c.c), a1.c.c)
def test_copy_internals_multiple_nesting(self):
t = table("t", column("c"))
stmt = select(t)
a1 = stmt.alias()
a2 = a1.alias()
a3 = a2._clone()
a3._copy_internals()
is_(a1.corresponding_column(a3.c.c), a1.c.c)
|