1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
|
from sqlalchemy import Boolean
from sqlalchemy import case
from sqlalchemy import column
from sqlalchemy import event
from sqlalchemy import exc as sa_exc
from sqlalchemy import ForeignKey
from sqlalchemy import ForeignKeyConstraint
from sqlalchemy import func
from sqlalchemy import inspect
from sqlalchemy import Integer
from sqlalchemy import MetaData
from sqlalchemy import select
from sqlalchemy import String
from sqlalchemy import table
from sqlalchemy import testing
from sqlalchemy import util
from sqlalchemy.orm import attributes
from sqlalchemy.orm import class_mapper
from sqlalchemy.orm import clear_mappers
from sqlalchemy.orm import column_property
from sqlalchemy.orm import composite
from sqlalchemy.orm import declarative_base
from sqlalchemy.orm import deferred
from sqlalchemy.orm import exc as orm_exc
from sqlalchemy.orm import joinedload
from sqlalchemy.orm import Mapped
from sqlalchemy.orm import mapped_column
from sqlalchemy.orm import object_mapper
from sqlalchemy.orm import polymorphic_union
from sqlalchemy.orm import relationship
from sqlalchemy.orm import Session
from sqlalchemy.orm import synonym
from sqlalchemy.orm.util import instance_str
from sqlalchemy.sql.selectable import LABEL_STYLE_TABLENAME_PLUS_COL
from sqlalchemy.testing import assert_raises
from sqlalchemy.testing import assert_raises_message
from sqlalchemy.testing import eq_
from sqlalchemy.testing import expect_raises_message
from sqlalchemy.testing import expect_warnings
from sqlalchemy.testing import fixtures
from sqlalchemy.testing import is_
from sqlalchemy.testing import mock
from sqlalchemy.testing.assertions import assert_warns_message
from sqlalchemy.testing.assertsql import AllOf
from sqlalchemy.testing.assertsql import CompiledSQL
from sqlalchemy.testing.assertsql import Conditional
from sqlalchemy.testing.assertsql import Or
from sqlalchemy.testing.assertsql import RegexSQL
from sqlalchemy.testing.fixtures import fixture_session
from sqlalchemy.testing.schema import Column
from sqlalchemy.testing.schema import Table
class O2MTest(fixtures.MappedTest):
"""deals with inheritance and one-to-many relationships"""
@classmethod
def define_tables(cls, metadata):
global foo, bar, blub
foo = Table(
"foo",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("data", String(20)),
)
bar = Table(
"bar",
metadata,
Column("id", Integer, ForeignKey("foo.id"), primary_key=True),
Column("bar_data", String(20)),
)
blub = Table(
"blub",
metadata,
Column("id", Integer, ForeignKey("bar.id"), primary_key=True),
Column("foo_id", Integer, ForeignKey("foo.id"), nullable=False),
Column("blub_data", String(20)),
)
def test_basic(self):
class Foo:
def __init__(self, data=None):
self.data = data
def __repr__(self):
return "Foo id %d, data %s" % (self.id, self.data)
self.mapper_registry.map_imperatively(Foo, foo)
class Bar(Foo):
def __repr__(self):
return "Bar id %d, data %s" % (self.id, self.data)
self.mapper_registry.map_imperatively(Bar, bar, inherits=Foo)
class Blub(Bar):
def __repr__(self):
return "Blub id %d, data %s" % (self.id, self.data)
self.mapper_registry.map_imperatively(
Blub,
blub,
inherits=Bar,
properties={"parent_foo": relationship(Foo)},
)
sess = fixture_session()
b1 = Blub("blub #1")
b2 = Blub("blub #2")
f = Foo("foo #1")
sess.add(b1)
sess.add(b2)
sess.add(f)
b1.parent_foo = f
b2.parent_foo = f
sess.flush()
compare = ",".join(
[repr(b1), repr(b2), repr(b1.parent_foo), repr(b2.parent_foo)]
)
sess.expunge_all()
result = sess.query(Blub).all()
result_str = ",".join(
[
repr(result[0]),
repr(result[1]),
repr(result[0].parent_foo),
repr(result[1].parent_foo),
]
)
eq_(compare, result_str)
eq_(result[0].parent_foo.data, "foo #1")
eq_(result[1].parent_foo.data, "foo #1")
class ColExpressionsTest(fixtures.DeclarativeMappedTest):
__backend__ = True
@classmethod
def setup_classes(cls):
Base = cls.DeclarativeBasic
class A(Base):
__tablename__ = "a"
id = Column(
Integer, primary_key=True, test_needs_autoincrement=True
)
type = Column(String(10))
__mapper_args__ = {
"polymorphic_on": type,
"polymorphic_identity": "a",
}
class B(A):
__tablename__ = "b"
id = Column(ForeignKey("a.id"), primary_key=True)
data = Column(Integer)
__mapper_args__ = {"polymorphic_identity": "b"}
@classmethod
def insert_data(cls, connection):
A, B = cls.classes("A", "B")
s = Session(connection)
s.add_all([B(data=5), B(data=7)])
s.commit()
def test_group_by(self):
B = self.classes.B
s = fixture_session()
rows = (
s.query(B.id.expressions[0], B.id.expressions[1], func.sum(B.data))
.group_by(*B.id.expressions)
.all()
)
eq_(rows, [(1, 1, 5), (2, 2, 7)])
class PolyExpressionEagerLoad(fixtures.DeclarativeMappedTest):
run_setup_mappers = "once"
__dialect__ = "default"
@classmethod
def setup_classes(cls):
Base = cls.DeclarativeBasic
class A(fixtures.ComparableEntity, Base):
__tablename__ = "a"
id = Column(
Integer, primary_key=True, test_needs_autoincrement=True
)
discriminator = Column(String(50), nullable=False)
child_id = Column(Integer, ForeignKey("a.id"))
child = relationship("A")
__mapper_args__ = {
"polymorphic_identity": "a",
"polymorphic_on": case((discriminator == "a", "a"), else_="b"),
}
class B(A):
__mapper_args__ = {"polymorphic_identity": "b"}
@classmethod
def insert_data(cls, connection):
A = cls.classes.A
session = Session(connection)
session.add_all(
[
A(id=1, discriminator="a"),
A(id=2, discriminator="b", child_id=1),
A(id=3, discriminator="c", child_id=1),
]
)
session.commit()
def test_joinedload(self):
A = self.classes.A
B = self.classes.B
session = fixture_session()
result = (
session.query(A)
.filter_by(child_id=None)
.options(joinedload(A.child))
.one()
)
eq_(result, A(id=1, discriminator="a", child=[B(id=2), B(id=3)]))
class PolymorphicResolutionMultiLevel(
fixtures.DeclarativeMappedTest, testing.AssertsCompiledSQL
):
run_setup_mappers = "once"
__dialect__ = "default"
@classmethod
def setup_classes(cls):
Base = cls.DeclarativeBasic
class A(Base):
__tablename__ = "a"
id = Column(Integer, primary_key=True)
class B(A):
__tablename__ = "b"
id = Column(Integer, ForeignKey("a.id"), primary_key=True)
class C(A):
__tablename__ = "c"
id = Column(Integer, ForeignKey("a.id"), primary_key=True)
class D(B):
__tablename__ = "d"
id = Column(Integer, ForeignKey("b.id"), primary_key=True)
def test_ordered_b_d(self):
a_mapper = inspect(self.classes.A)
eq_(
a_mapper._mappers_from_spec(
[self.classes.B, self.classes.D], None
),
[a_mapper, inspect(self.classes.B), inspect(self.classes.D)],
)
def test_a(self):
a_mapper = inspect(self.classes.A)
eq_(a_mapper._mappers_from_spec([self.classes.A], None), [a_mapper])
def test_b_d_selectable(self):
a_mapper = inspect(self.classes.A)
spec = [self.classes.D, self.classes.B]
eq_(
a_mapper._mappers_from_spec(
spec, self.classes.B.__table__.join(self.classes.D.__table__)
),
[inspect(self.classes.B), inspect(self.classes.D)],
)
def test_d_selectable(self):
a_mapper = inspect(self.classes.A)
spec = [self.classes.D]
eq_(
a_mapper._mappers_from_spec(
spec, self.classes.B.__table__.join(self.classes.D.__table__)
),
[inspect(self.classes.D)],
)
def test_reverse_d_b(self):
a_mapper = inspect(self.classes.A)
spec = [self.classes.D, self.classes.B]
eq_(
a_mapper._mappers_from_spec(spec, None),
[a_mapper, inspect(self.classes.B), inspect(self.classes.D)],
)
mappers, selectable = a_mapper._with_polymorphic_args(spec=spec)
self.assert_compile(
selectable,
"a LEFT OUTER JOIN b ON a.id = b.id "
"LEFT OUTER JOIN d ON b.id = d.id",
)
def test_d_b_missing(self):
a_mapper = inspect(self.classes.A)
spec = [self.classes.D]
eq_(
a_mapper._mappers_from_spec(spec, None),
[a_mapper, inspect(self.classes.B), inspect(self.classes.D)],
)
mappers, selectable = a_mapper._with_polymorphic_args(spec=spec)
self.assert_compile(
selectable,
"a LEFT OUTER JOIN b ON a.id = b.id "
"LEFT OUTER JOIN d ON b.id = d.id",
)
def test_d_c_b(self):
a_mapper = inspect(self.classes.A)
spec = [self.classes.D, self.classes.C, self.classes.B]
ms = a_mapper._mappers_from_spec(spec, None)
eq_(ms[-1], inspect(self.classes.D))
eq_(ms[0], a_mapper)
eq_(set(ms[1:3]), set(a_mapper._inheriting_mappers))
class PolymorphicOnNotLocalTest(fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
Table(
"t1",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("x", String(10)),
Column("q", String(10)),
)
Table(
"t2",
metadata,
Column(
"t2id",
Integer,
primary_key=True,
test_needs_autoincrement=True,
),
Column("y", String(10)),
Column("xid", ForeignKey("t1.id")),
)
@classmethod
def setup_classes(cls):
class Parent(cls.Comparable):
pass
class Child(Parent):
pass
def test_non_col_polymorphic_on(self):
Parent = self.classes.Parent
t2 = self.tables.t2
assert_raises_message(
sa_exc.ArgumentError,
"Can't determine polymorphic_on "
"value 'im not a column' - no "
"attribute is mapped to this name.",
self.mapper_registry.map_imperatively,
Parent,
t2,
polymorphic_on="im not a column",
)
def test_polymorphic_on_non_expr_prop(self):
t2 = self.tables.t2
Parent = self.classes.Parent
assert_raises_message(
sa_exc.ArgumentError,
r"Column expression or string key expected for argument "
r"'polymorphic_on'; got .*function",
self.mapper,
Parent,
t2,
polymorphic_on=lambda: "hi",
polymorphic_identity=0,
)
def test_polymorphic_on_not_present_col_partial_wpoly(self):
"""fix for partial with_polymorphic().
found_during_type_annotation
"""
t2, t1 = self.tables.t2, self.tables.t1
Parent = self.classes.Parent
t1t2_join = select(t1.c.x).select_from(t1.join(t2)).alias()
def go():
t1t2_join_2 = ( # noqa: F841
select(t1.c.q).select_from(t1.join(t2)).alias()
)
self.mapper_registry.map_imperatively(
Parent,
t2,
polymorphic_on=t1t2_join.c.x,
with_polymorphic=("*", None),
polymorphic_identity=0,
)
assert_raises_message(
sa_exc.InvalidRequestError,
"Could not map polymorphic_on column 'x' to the mapped table - "
"polymorphic loads will not function properly",
go,
)
def test_polymorphic_on_not_present_col(self):
t2, t1 = self.tables.t2, self.tables.t1
Parent = self.classes.Parent
t1t2_join = select(t1.c.x).select_from(t1.join(t2)).alias()
def go():
t1t2_join_2 = select(t1.c.q).select_from(t1.join(t2)).alias()
self.mapper_registry.map_imperatively(
Parent,
t2,
polymorphic_on=t1t2_join.c.x,
with_polymorphic=("*", t1t2_join_2),
polymorphic_identity=0,
)
assert_raises_message(
sa_exc.InvalidRequestError,
"Could not map polymorphic_on column 'x' to the mapped table - "
"polymorphic loads will not function properly",
go,
)
def test_polymorphic_on_only_in_with_poly(self):
t2, t1 = self.tables.t2, self.tables.t1
Parent = self.classes.Parent
t1t2_join = select(t1.c.x).select_from(t1.join(t2)).alias()
# if its in the with_polymorphic, then its OK
self.mapper_registry.map_imperatively(
Parent,
t2,
polymorphic_on=t1t2_join.c.x,
with_polymorphic=("*", t1t2_join),
polymorphic_identity=0,
)
def test_polymorphic_on_not_in_with_poly(self):
t2, t1 = self.tables.t2, self.tables.t1
Parent = self.classes.Parent
t1t2_join = select(t1.c.x).select_from(t1.join(t2)).alias()
# if with_polymorphic, but its not present, not OK
def go():
t1t2_join_2 = select(t1.c.q).select_from(t1.join(t2)).alias()
self.mapper_registry.map_imperatively(
Parent,
t2,
polymorphic_on=t1t2_join.c.x,
with_polymorphic=("*", t1t2_join_2),
polymorphic_identity=0,
)
assert_raises_message(
sa_exc.InvalidRequestError,
"Could not map polymorphic_on column 'x' "
"to the mapped table - "
"polymorphic loads will not function properly",
go,
)
def test_polymorphic_on_expr_explicit_map(self):
t2, t1 = self.tables.t2, self.tables.t1
Parent, Child = self.classes.Parent, self.classes.Child
expr = case((t1.c.x == "p", "parent"), (t1.c.x == "c", "child"))
self.mapper_registry.map_imperatively(
Parent,
t1,
properties={"discriminator": column_property(expr)},
polymorphic_identity="parent",
polymorphic_on=expr,
)
self.mapper_registry.map_imperatively(
Child, t2, inherits=Parent, polymorphic_identity="child"
)
self._roundtrip(parent_ident="p", child_ident="c")
def test_polymorphic_on_expr_implicit_map_no_label_joined(self):
t2, t1 = self.tables.t2, self.tables.t1
Parent, Child = self.classes.Parent, self.classes.Child
expr = case((t1.c.x == "p", "parent"), (t1.c.x == "c", "child"))
self.mapper_registry.map_imperatively(
Parent, t1, polymorphic_identity="parent", polymorphic_on=expr
)
self.mapper_registry.map_imperatively(
Child, t2, inherits=Parent, polymorphic_identity="child"
)
self._roundtrip(parent_ident="p", child_ident="c")
def test_polymorphic_on_expr_implicit_map_w_label_joined(self):
t2, t1 = self.tables.t2, self.tables.t1
Parent, Child = self.classes.Parent, self.classes.Child
expr = case((t1.c.x == "p", "parent"), (t1.c.x == "c", "child")).label(
None
)
self.mapper_registry.map_imperatively(
Parent, t1, polymorphic_identity="parent", polymorphic_on=expr
)
self.mapper_registry.map_imperatively(
Child, t2, inherits=Parent, polymorphic_identity="child"
)
self._roundtrip(parent_ident="p", child_ident="c")
def test_polymorphic_on_expr_implicit_map_no_label_single(self):
"""test that single_table_criterion is propagated
with a standalone expr"""
t1 = self.tables.t1
Parent, Child = self.classes.Parent, self.classes.Child
expr = case((t1.c.x == "p", "parent"), (t1.c.x == "c", "child"))
self.mapper_registry.map_imperatively(
Parent, t1, polymorphic_identity="parent", polymorphic_on=expr
)
self.mapper_registry.map_imperatively(
Child, inherits=Parent, polymorphic_identity="child"
)
self._roundtrip(parent_ident="p", child_ident="c")
def test_polymorphic_on_expr_implicit_map_w_label_single(self):
"""test that single_table_criterion is propagated
with a standalone expr"""
t1 = self.tables.t1
Parent, Child = self.classes.Parent, self.classes.Child
expr = case((t1.c.x == "p", "parent"), (t1.c.x == "c", "child")).label(
None
)
self.mapper_registry.map_imperatively(
Parent, t1, polymorphic_identity="parent", polymorphic_on=expr
)
self.mapper_registry.map_imperatively(
Child, inherits=Parent, polymorphic_identity="child"
)
self._roundtrip(parent_ident="p", child_ident="c")
def test_polymorphic_on_column_prop(self):
t2, t1 = self.tables.t2, self.tables.t1
Parent, Child = self.classes.Parent, self.classes.Child
expr = case((t1.c.x == "p", "parent"), (t1.c.x == "c", "child"))
cprop = column_property(expr)
self.mapper_registry.map_imperatively(
Parent,
t1,
properties={"discriminator": cprop},
polymorphic_identity="parent",
polymorphic_on=cprop,
)
self.mapper_registry.map_imperatively(
Child, t2, inherits=Parent, polymorphic_identity="child"
)
self._roundtrip(parent_ident="p", child_ident="c")
def test_polymorphic_on_column_str_prop(self):
t2, t1 = self.tables.t2, self.tables.t1
Parent, Child = self.classes.Parent, self.classes.Child
expr = case((t1.c.x == "p", "parent"), (t1.c.x == "c", "child"))
cprop = column_property(expr)
self.mapper_registry.map_imperatively(
Parent,
t1,
properties={"discriminator": cprop},
polymorphic_identity="parent",
polymorphic_on="discriminator",
)
self.mapper_registry.map_imperatively(
Child, t2, inherits=Parent, polymorphic_identity="child"
)
self._roundtrip(parent_ident="p", child_ident="c")
def test_polymorphic_on_synonym(self):
t1 = self.tables.t1
Parent = self.classes.Parent
cprop = column_property(t1.c.x)
assert_raises_message(
sa_exc.ArgumentError,
"Only direct column-mapped property or "
"SQL expression can be passed for polymorphic_on",
self.mapper_registry.map_imperatively,
Parent,
t1,
properties={"discriminator": cprop, "discrim_syn": synonym(cprop)},
polymorphic_identity="parent",
polymorphic_on="discrim_syn",
)
def _roundtrip(
self, set_event=True, parent_ident="parent", child_ident="child"
):
Parent, Child = self.classes.Parent, self.classes.Child
# locate the "polymorphic_on" ColumnProperty. This isn't
# "officially" stored at the moment so do some heuristics to find it.
parent_mapper = inspect(Parent)
for prop in parent_mapper.column_attrs:
if not prop.instrument:
break
else:
prop = parent_mapper._columntoproperty[
parent_mapper.polymorphic_on
]
# then make sure the column we will query on matches.
is_(parent_mapper.polymorphic_on, prop.columns[0])
if set_event:
@event.listens_for(Parent, "init", propagate=True)
def set_identity(instance, *arg, **kw):
ident = object_mapper(instance).polymorphic_identity
if ident == "parent":
instance.x = parent_ident
elif ident == "child":
instance.x = child_ident
else:
assert False, "Got unexpected identity %r" % ident
s = fixture_session()
s.add_all([Parent(q="p1"), Child(q="c1", y="c1"), Parent(q="p2")])
s.commit()
s.close()
eq_(
[type(t) for t in s.query(Parent).order_by(Parent.id)],
[Parent, Child, Parent],
)
eq_([type(t) for t in s.query(Child).all()], [Child])
class SortOnlyOnImportantFKsTest(fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
Table(
"a",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column(
"b_id",
Integer,
ForeignKey("b.id", use_alter=True, name="b_fk"),
),
)
Table(
"b",
metadata,
Column("id", Integer, ForeignKey("a.id"), primary_key=True),
)
@classmethod
def setup_classes(cls):
Base = declarative_base()
class A(Base):
__tablename__ = "a"
id = Column(
Integer, primary_key=True, test_needs_autoincrement=True
)
b_id = Column(Integer, ForeignKey("b.id"))
class B(A):
__tablename__ = "b"
id = Column(Integer, ForeignKey("a.id"), primary_key=True)
__mapper_args__ = {"inherit_condition": id == A.id}
cls.classes.A = A
cls.classes.B = B
def test_flush(self):
s = fixture_session()
s.add(self.classes.B())
s.flush()
class FalseDiscriminatorTest(fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
global t1
t1 = Table(
"t1",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("type", Boolean, nullable=False),
)
def test_false_on_sub(self):
class Foo:
pass
class Bar(Foo):
pass
self.mapper_registry.map_imperatively(
Foo, t1, polymorphic_on=t1.c.type, polymorphic_identity=True
)
self.mapper_registry.map_imperatively(
Bar, inherits=Foo, polymorphic_identity=False
)
sess = fixture_session()
b1 = Bar()
sess.add(b1)
sess.flush()
assert b1.type is False
sess.expunge_all()
assert isinstance(sess.query(Foo).one(), Bar)
def test_false_on_base(self):
class Ding:
pass
class Bat(Ding):
pass
self.mapper_registry.map_imperatively(
Ding, t1, polymorphic_on=t1.c.type, polymorphic_identity=False
)
self.mapper_registry.map_imperatively(
Bat, inherits=Ding, polymorphic_identity=True
)
sess = fixture_session()
d1 = Ding()
sess.add(d1)
sess.flush()
assert d1.type is False
sess.expunge_all()
assert sess.query(Ding).one() is not None
class PolymorphicSynonymTest(fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
global t1, t2
t1 = Table(
"t1",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("type", String(10), nullable=False),
Column("info", String(255)),
)
t2 = Table(
"t2",
metadata,
Column("id", Integer, ForeignKey("t1.id"), primary_key=True),
Column("data", String(10), nullable=False),
)
def test_polymorphic_synonym(self):
class T1(fixtures.ComparableEntity):
def info(self):
return "THE INFO IS:" + self._info
def _set_info(self, x):
self._info = x
info = property(info, _set_info)
class T2(T1):
pass
self.mapper_registry.map_imperatively(
T1,
t1,
polymorphic_on=t1.c.type,
polymorphic_identity="t1",
properties={"info": synonym("_info", map_column=True)},
)
self.mapper_registry.map_imperatively(
T2, t2, inherits=T1, polymorphic_identity="t2"
)
sess = fixture_session()
at1 = T1(info="at1")
at2 = T2(info="at2", data="t2 data")
sess.add(at1)
sess.add(at2)
sess.flush()
sess.expunge_all()
eq_(sess.query(T2).filter(T2.info == "at2").one(), at2)
eq_(at2.info, "THE INFO IS:at2")
class PolymorphicAttributeManagementTest(fixtures.MappedTest):
"""Test polymorphic_on can be assigned, can be mirrored, etc."""
run_setup_mappers = "once"
@classmethod
def define_tables(cls, metadata):
Table(
"table_a",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("class_name", String(50)),
)
Table(
"table_b",
metadata,
Column("id", Integer, ForeignKey("table_a.id"), primary_key=True),
Column("class_name", String(50)),
)
Table(
"table_c",
metadata,
Column("id", Integer, ForeignKey("table_b.id"), primary_key=True),
Column("data", String(10)),
)
@classmethod
def setup_classes(cls):
class A(cls.Basic):
pass
class B(A):
pass
class C(B):
pass
class D(B):
pass
@classmethod
def setup_mappers(cls):
A, B, C, D = cls.classes("A", "B", "C", "D")
table_b, table_c, table_a = (
cls.tables.table_b,
cls.tables.table_c,
cls.tables.table_a,
)
cls.mapper_registry.map_imperatively(
A,
table_a,
polymorphic_on=table_a.c.class_name,
polymorphic_identity="a",
)
cls.mapper_registry.map_imperatively(
B,
table_b,
inherits=A,
polymorphic_on=table_b.c.class_name,
polymorphic_identity="b",
properties=dict(
class_name=[table_a.c.class_name, table_b.c.class_name]
),
)
cls.mapper_registry.map_imperatively(
C, table_c, inherits=B, polymorphic_identity="c"
)
cls.mapper_registry.map_imperatively(
D, inherits=B, polymorphic_identity="d"
)
def test_poly_configured_immediate(self):
A, C, B = (self.classes.A, self.classes.C, self.classes.B)
a = A()
b = B()
c = C()
eq_(a.class_name, "a")
eq_(b.class_name, "b")
eq_(c.class_name, "c")
def test_base_class(self):
A, C, B = (self.classes.A, self.classes.C, self.classes.B)
sess = fixture_session()
c1 = C()
sess.add(c1)
sess.commit()
assert isinstance(sess.query(B).first(), C)
sess.close()
assert isinstance(sess.query(A).first(), C)
def test_valid_assignment_upwards(self):
"""test that we can assign 'd' to a B, since B/D
both involve the same set of tables.
"""
D, B = self.classes.D, self.classes.B
sess = fixture_session()
b1 = B()
b1.class_name = "d"
sess.add(b1)
sess.commit()
sess.close()
assert isinstance(sess.query(B).first(), D)
def test_invalid_assignment_downwards(self):
"""test that we warn on assign of 'b' to a C, since this adds
a row to the C table we'd never load.
"""
C = self.classes.C
sess = fixture_session()
c1 = C()
c1.class_name = "b"
sess.add(c1)
assert_warns_message(
sa_exc.SAWarning,
"Flushing object %s with incompatible "
"polymorphic identity 'b'; the object may not "
"refresh and/or load correctly" % instance_str(c1),
sess.flush,
)
def test_invalid_assignment_upwards(self):
"""test that we warn on assign of 'c' to a B, since we will have a
"C" row that has no joined row, which will cause object
deleted errors.
"""
B = self.classes.B
sess = fixture_session()
b1 = B()
b1.class_name = "c"
sess.add(b1)
assert_warns_message(
sa_exc.SAWarning,
"Flushing object %s with incompatible "
"polymorphic identity 'c'; the object may not "
"refresh and/or load correctly" % instance_str(b1),
sess.flush,
)
def test_entirely_oob_assignment(self):
"""test warn on an unknown polymorphic identity."""
B = self.classes.B
sess = fixture_session()
b1 = B()
b1.class_name = "xyz"
sess.add(b1)
assert_warns_message(
sa_exc.SAWarning,
"Flushing object %s with incompatible "
"polymorphic identity 'xyz'; the object may not "
"refresh and/or load correctly" % instance_str(b1),
sess.flush,
)
def test_not_set_on_upate(self):
C = self.classes.C
sess = fixture_session()
c1 = C()
sess.add(c1)
sess.commit()
sess.expire(c1)
c1.data = "foo"
sess.flush()
def test_validate_on_upate(self):
C = self.classes.C
sess = fixture_session()
c1 = C()
sess.add(c1)
sess.commit()
sess.expire(c1)
c1.class_name = "b"
assert_warns_message(
sa_exc.SAWarning,
"Flushing object %s with incompatible "
"polymorphic identity 'b'; the object may not "
"refresh and/or load correctly" % instance_str(c1),
sess.flush,
)
class CascadeTest(fixtures.MappedTest):
"""that cascades on polymorphic relationships continue
cascading along the path of the instance's mapper, not
the base mapper."""
@classmethod
def define_tables(cls, metadata):
global t1, t2, t3, t4
t1 = Table(
"t1",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("data", String(30)),
)
t2 = Table(
"t2",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("t1id", Integer, ForeignKey("t1.id")),
Column("type", String(30)),
Column("data", String(30)),
)
t3 = Table(
"t3",
metadata,
Column("id", Integer, ForeignKey("t2.id"), primary_key=True),
Column("moredata", String(30)),
)
t4 = Table(
"t4",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("t3id", Integer, ForeignKey("t3.id")),
Column("data", String(30)),
)
def test_cascade(self):
class T1(fixtures.BasicEntity):
pass
class T2(fixtures.BasicEntity):
pass
class T3(T2):
pass
class T4(fixtures.BasicEntity):
pass
self.mapper_registry.map_imperatively(
T1, t1, properties={"t2s": relationship(T2, cascade="all")}
)
self.mapper_registry.map_imperatively(
T2, t2, polymorphic_on=t2.c.type, polymorphic_identity="t2"
)
self.mapper_registry.map_imperatively(
T3,
t3,
inherits=T2,
polymorphic_identity="t3",
properties={"t4s": relationship(T4, cascade="all")},
)
self.mapper_registry.map_imperatively(T4, t4)
sess = fixture_session()
t1_1 = T1(data="t1")
t3_1 = T3(data="t3", moredata="t3")
t2_1 = T2(data="t2")
t1_1.t2s.append(t2_1)
t1_1.t2s.append(t3_1)
t4_1 = T4(data="t4")
t3_1.t4s.append(t4_1)
sess.add(t1_1)
assert t4_1 in sess.new
sess.flush()
sess.delete(t1_1)
assert t4_1 in sess.deleted
sess.flush()
class M2OUseGetTest(fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
Table(
"base",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("type", String(30)),
)
Table(
"sub",
metadata,
Column("id", Integer, ForeignKey("base.id"), primary_key=True),
)
Table(
"related",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("sub_id", Integer, ForeignKey("sub.id")),
)
def test_use_get(self):
base, sub, related = (
self.tables.base,
self.tables.sub,
self.tables.related,
)
# test [ticket:1186]
class Base(fixtures.BasicEntity):
pass
class Sub(Base):
pass
class Related(Base):
pass
self.mapper_registry.map_imperatively(
Base, base, polymorphic_on=base.c.type, polymorphic_identity="b"
)
self.mapper_registry.map_imperatively(
Sub, sub, inherits=Base, polymorphic_identity="s"
)
self.mapper_registry.map_imperatively(
Related,
related,
properties={
# previously, this was needed for the comparison to occur:
# the 'primaryjoin' looks just like "Sub"'s "get" clause
# (based on the Base id), and foreign_keys since that join
# condition doesn't actually have any fks in it
# 'sub':relationship(Sub,
# primaryjoin=base.c.id==related.c.sub_id,
# foreign_keys=related.c.sub_id)
# now we can use this:
"sub": relationship(Sub)
},
)
assert class_mapper(Related).get_property("sub").strategy.use_get
sess = fixture_session()
s1 = Sub()
r1 = Related(sub=s1)
sess.add(r1)
sess.flush()
sess.expunge_all()
r1 = sess.query(Related).first()
s1 = sess.query(Sub).first()
def go():
assert r1.sub
self.assert_sql_count(testing.db, go, 0)
class GetTest(fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
global foo, bar, blub
foo = Table(
"foo",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("type", String(30)),
Column("data", String(20)),
)
bar = Table(
"bar",
metadata,
Column("id", Integer, ForeignKey("foo.id"), primary_key=True),
Column("bar_data", String(20)),
)
blub = Table(
"blub",
metadata,
Column(
"blub_id",
Integer,
primary_key=True,
test_needs_autoincrement=True,
),
Column("foo_id", Integer, ForeignKey("foo.id")),
Column("bar_id", Integer, ForeignKey("bar.id")),
Column("blub_data", String(20)),
)
@classmethod
def setup_classes(cls):
class Foo(cls.Basic):
pass
class Bar(Foo):
pass
class Blub(Bar):
pass
@testing.combinations(
("polymorphic", True), ("test_get_nonpolymorphic", False), id_="ia"
)
def test_get(self, polymorphic):
foo, Bar, Blub, blub, bar, Foo = (
self.tables.foo,
self.classes.Bar,
self.classes.Blub,
self.tables.blub,
self.tables.bar,
self.classes.Foo,
)
if polymorphic:
self.mapper_registry.map_imperatively(
Foo, foo, polymorphic_on=foo.c.type, polymorphic_identity="foo"
)
self.mapper_registry.map_imperatively(
Bar, bar, inherits=Foo, polymorphic_identity="bar"
)
self.mapper_registry.map_imperatively(
Blub, blub, inherits=Bar, polymorphic_identity="blub"
)
else:
self.mapper_registry.map_imperatively(Foo, foo)
self.mapper_registry.map_imperatively(Bar, bar, inherits=Foo)
self.mapper_registry.map_imperatively(Blub, blub, inherits=Bar)
sess = fixture_session()
f = Foo()
b = Bar()
bl = Blub()
sess.add(f)
sess.add(b)
sess.add(bl)
sess.flush()
if polymorphic:
def go():
assert sess.get(Foo, f.id) is f
assert sess.get(Foo, b.id) is b
assert sess.get(Foo, bl.id) is bl
assert sess.get(Bar, b.id) is b
assert sess.get(Bar, bl.id) is bl
assert sess.get(Blub, bl.id) is bl
# test class mismatches - item is present
# in the identity map but we requested a subclass
assert sess.get(Blub, f.id) is None
assert sess.get(Blub, b.id) is None
assert sess.get(Bar, f.id) is None
self.assert_sql_count(testing.db, go, 0)
else:
# this is testing the 'wrong' behavior of using get()
# polymorphically with mappers that are not configured to be
# polymorphic. the important part being that get() always
# returns an instance of the query's type.
def go():
assert sess.get(Foo, f.id) is f
bb = sess.get(Foo, b.id)
assert isinstance(b, Foo) and bb.id == b.id
bll = sess.get(Foo, bl.id)
assert isinstance(bll, Foo) and bll.id == bl.id
assert sess.get(Bar, b.id) is b
bll = sess.get(Bar, bl.id)
assert isinstance(bll, Bar) and bll.id == bl.id
assert sess.get(Blub, bl.id) is bl
self.assert_sql_count(testing.db, go, 3)
class EagerLazyTest(fixtures.MappedTest):
"""tests eager load/lazy load of child items off inheritance mappers, tests
that LazyLoader constructs the right query condition."""
@classmethod
def define_tables(cls, metadata):
Table(
"foo",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("data", String(30)),
)
Table(
"bar",
metadata,
Column("id", Integer, ForeignKey("foo.id"), primary_key=True),
Column("bar_data", String(30)),
)
Table(
"bar_foo",
metadata,
Column("bar_id", Integer, ForeignKey("bar.id")),
Column("foo_id", Integer, ForeignKey("foo.id")),
)
@classmethod
def setup_mappers(cls):
foo, bar, bar_foo = cls.tables("foo", "bar", "bar_foo")
class Foo(cls.Comparable):
pass
class Bar(Foo):
pass
foos = cls.mapper_registry.map_imperatively(Foo, foo)
bars = cls.mapper_registry.map_imperatively(Bar, bar, inherits=foos)
bars.add_property("lazy", relationship(foos, bar_foo, lazy="select"))
bars.add_property(
"eager", relationship(foos, bar_foo, lazy="joined", viewonly=True)
)
@classmethod
def insert_data(cls, connection):
foo, bar, bar_foo = cls.tables("foo", "bar", "bar_foo")
connection.execute(foo.insert(), dict(data="foo1"))
connection.execute(bar.insert(), dict(id=1, data="bar1"))
connection.execute(foo.insert(), dict(data="foo2"))
connection.execute(bar.insert(), dict(id=2, data="bar2"))
connection.execute(foo.insert(), dict(data="foo3")) # 3
connection.execute(foo.insert(), dict(data="foo4")) # 4
connection.execute(bar_foo.insert(), dict(bar_id=1, foo_id=3))
connection.execute(bar_foo.insert(), dict(bar_id=2, foo_id=4))
def test_basic(self):
Bar = self.classes.Bar
sess = fixture_session()
q = sess.query(Bar)
self.assert_(len(q.first().lazy) == 1)
self.assert_(len(q.first().eager) == 1)
class EagerTargetingTest(fixtures.MappedTest):
"""test a scenario where joined table inheritance might be
confused as an eagerly loaded joined table."""
@classmethod
def define_tables(cls, metadata):
Table(
"a_table",
metadata,
Column("id", Integer, primary_key=True),
Column("name", String(50)),
Column("type", String(30), nullable=False),
Column("parent_id", Integer, ForeignKey("a_table.id")),
)
Table(
"b_table",
metadata,
Column("id", Integer, ForeignKey("a_table.id"), primary_key=True),
Column("b_data", String(50)),
)
def test_adapt_stringency(self):
b_table, a_table = self.tables.b_table, self.tables.a_table
class A(fixtures.ComparableEntity):
pass
class B(A):
pass
self.mapper_registry.map_imperatively(
A,
a_table,
polymorphic_on=a_table.c.type,
polymorphic_identity="A",
properties={"children": relationship(A, order_by=a_table.c.name)},
)
self.mapper_registry.map_imperatively(
B,
b_table,
inherits=A,
polymorphic_identity="B",
properties={
"b_derived": column_property(b_table.c.b_data + "DATA")
},
)
sess = fixture_session()
b1 = B(id=1, name="b1", b_data="i")
sess.add(b1)
sess.flush()
b2 = B(id=2, name="b2", b_data="l", parent_id=1)
sess.add(b2)
sess.flush()
bid = b1.id
sess.expunge_all()
node = sess.query(B).filter(B.id == bid).all()[0]
eq_(node, B(id=1, name="b1", b_data="i"))
eq_(node.children[0], B(id=2, name="b2", b_data="l"))
sess.expunge_all()
node = (
sess.query(B)
.options(joinedload(B.children))
.filter(B.id == bid)
.all()[0]
)
eq_(node, B(id=1, name="b1", b_data="i"))
eq_(node.children[0], B(id=2, name="b2", b_data="l"))
class FlushTest(fixtures.MappedTest):
"""test dependency sorting among inheriting mappers"""
@classmethod
def define_tables(cls, metadata):
Table(
"users",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("email", String(128)),
Column("password", String(16)),
)
Table(
"roles",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("description", String(32)),
)
Table(
"user_roles",
metadata,
Column(
"user_id", Integer, ForeignKey("users.id"), primary_key=True
),
Column(
"role_id", Integer, ForeignKey("roles.id"), primary_key=True
),
)
Table(
"admins",
metadata,
Column(
"admin_id",
Integer,
primary_key=True,
test_needs_autoincrement=True,
),
Column("user_id", Integer, ForeignKey("users.id")),
)
def test_one(self):
admins, users, roles, user_roles = (
self.tables.admins,
self.tables.users,
self.tables.roles,
self.tables.user_roles,
)
class User:
pass
class Role:
pass
class Admin(User):
pass
self.mapper_registry.map_imperatively(Role, roles)
user_mapper = self.mapper_registry.map_imperatively(
User,
users,
properties={
"roles": relationship(
Role, secondary=user_roles, lazy="joined"
)
},
)
self.mapper_registry.map_imperatively(
Admin, admins, inherits=user_mapper
)
sess = fixture_session()
adminrole = Role()
sess.add(adminrole)
sess.flush()
# create an Admin, and append a Role. the dependency processors
# corresponding to the "roles" attribute for the Admin mapper and the
# User mapper have to ensure that two dependency processors don't fire
# off and insert the many to many row twice.
a = Admin()
a.roles.append(adminrole)
a.password = "admin"
sess.add(a)
sess.flush()
eq_(sess.scalar(select(func.count("*")).select_from(user_roles)), 1)
def test_two(self):
admins, users, roles, user_roles = (
self.tables.admins,
self.tables.users,
self.tables.roles,
self.tables.user_roles,
)
class User:
def __init__(self, email=None, password=None):
self.email = email
self.password = password
class Role:
def __init__(self, description=None):
self.description = description
class Admin(User):
pass
self.mapper_registry.map_imperatively(Role, roles)
user_mapper = self.mapper_registry.map_imperatively(
User,
users,
properties={
"roles": relationship(
Role, secondary=user_roles, lazy="joined"
)
},
)
self.mapper_registry.map_imperatively(
Admin, admins, inherits=user_mapper
)
# create roles
adminrole = Role("admin")
sess = fixture_session()
sess.add(adminrole)
sess.flush()
# create admin user
a = Admin(email="tim", password="admin")
a.roles.append(adminrole)
sess.add(a)
sess.flush()
a.password = "sadmin"
sess.flush()
eq_(sess.scalar(select(func.count("*")).select_from(user_roles)), 1)
class PassiveDeletesTest(fixtures.MappedTest):
__requires__ = ("foreign_keys",)
@classmethod
def define_tables(cls, metadata):
Table(
"a",
metadata,
Column("id", Integer, primary_key=True),
Column("type", String(30)),
)
Table(
"b",
metadata,
Column(
"id",
Integer,
ForeignKey("a.id", ondelete="CASCADE"),
primary_key=True,
),
Column("data", String(10)),
)
Table(
"c",
metadata,
Column("cid", Integer, primary_key=True),
Column("bid", ForeignKey("b.id", ondelete="CASCADE")),
)
@classmethod
def setup_classes(cls):
class A(cls.Basic):
pass
class B(A):
pass
class C(B):
pass
def _fixture(self, a_p=False, b_p=False, c_p=False):
A, B, C = self.classes("A", "B", "C")
a, b, c = self.tables("a", "b", "c")
self.mapper_registry.map_imperatively(
A,
a,
passive_deletes=a_p,
polymorphic_on=a.c.type,
polymorphic_identity="a",
)
self.mapper_registry.map_imperatively(
B, b, inherits=A, passive_deletes=b_p, polymorphic_identity="b"
)
self.mapper_registry.map_imperatively(
C, c, inherits=B, passive_deletes=c_p, polymorphic_identity="c"
)
def test_none(self):
A, B, C = self.classes("A", "B", "C")
self._fixture()
s = fixture_session()
a1, b1, c1 = A(id=1), B(id=2), C(cid=1, id=3)
s.add_all([a1, b1, c1])
s.commit()
# want to see if the 'C' table loads even though
# a and b are loaded
c1 = s.query(B).filter_by(id=3).first()
s.delete(c1)
with self.sql_execution_asserter(testing.db) as asserter:
s.flush()
asserter.assert_(
RegexSQL(
"SELECT .* " "FROM c WHERE :param_1 = c.bid", [{"param_1": 3}]
),
CompiledSQL("DELETE FROM c WHERE c.cid = :cid", [{"cid": 1}]),
CompiledSQL("DELETE FROM b WHERE b.id = :id", [{"id": 3}]),
CompiledSQL("DELETE FROM a WHERE a.id = :id", [{"id": 3}]),
)
def test_c_only(self):
A, B, C = self.classes("A", "B", "C")
self._fixture(c_p=True)
s = fixture_session()
a1, b1, c1 = A(id=1), B(id=2), C(cid=1, id=3)
s.add_all([a1, b1, c1])
s.commit()
s.delete(a1)
with self.sql_execution_asserter(testing.db) as asserter:
s.flush()
asserter.assert_(
CompiledSQL(
"SELECT a.id AS a_id, a.type AS a_type "
"FROM a WHERE a.id = :pk_1",
[{"pk_1": 1}],
),
CompiledSQL("DELETE FROM a WHERE a.id = :id", [{"id": 1}]),
)
b1.id
s.delete(b1)
with self.sql_execution_asserter(testing.db) as asserter:
s.flush()
asserter.assert_(
CompiledSQL("DELETE FROM b WHERE b.id = :id", [{"id": 2}]),
CompiledSQL("DELETE FROM a WHERE a.id = :id", [{"id": 2}]),
)
# want to see if the 'C' table loads even though
# a and b are loaded
c1 = s.query(A).filter_by(id=3).first()
s.delete(c1)
with self.sql_execution_asserter(testing.db) as asserter:
s.flush()
asserter.assert_(
CompiledSQL("DELETE FROM b WHERE b.id = :id", [{"id": 3}]),
CompiledSQL("DELETE FROM a WHERE a.id = :id", [{"id": 3}]),
)
def test_b_only(self):
A, B, C = self.classes("A", "B", "C")
self._fixture(b_p=True)
s = fixture_session()
a1, b1, c1 = A(id=1), B(id=2), C(cid=1, id=3)
s.add_all([a1, b1, c1])
s.commit()
s.delete(a1)
with self.sql_execution_asserter(testing.db) as asserter:
s.flush()
asserter.assert_(
CompiledSQL(
"SELECT a.id AS a_id, a.type AS a_type "
"FROM a WHERE a.id = :pk_1",
[{"pk_1": 1}],
),
CompiledSQL("DELETE FROM a WHERE a.id = :id", [{"id": 1}]),
)
b1.id
s.delete(b1)
with self.sql_execution_asserter(testing.db) as asserter:
s.flush()
asserter.assert_(
CompiledSQL("DELETE FROM a WHERE a.id = :id", [{"id": 2}])
)
c1.id
s.delete(c1)
with self.sql_execution_asserter(testing.db) as asserter:
s.flush()
asserter.assert_(
CompiledSQL("DELETE FROM a WHERE a.id = :id", [{"id": 3}])
)
def test_a_only(self):
A, B, C = self.classes("A", "B", "C")
self._fixture(a_p=True)
s = fixture_session()
a1, b1, c1 = A(id=1), B(id=2), C(cid=1, id=3)
s.add_all([a1, b1, c1])
s.commit()
s.delete(a1)
with self.sql_execution_asserter(testing.db) as asserter:
s.flush()
asserter.assert_(
CompiledSQL(
"SELECT a.id AS a_id, a.type AS a_type "
"FROM a WHERE a.id = :pk_1",
[{"pk_1": 1}],
),
CompiledSQL("DELETE FROM a WHERE a.id = :id", [{"id": 1}]),
)
b1.id
s.delete(b1)
with self.sql_execution_asserter(testing.db) as asserter:
s.flush()
asserter.assert_(
CompiledSQL("DELETE FROM a WHERE a.id = :id", [{"id": 2}])
)
# want to see if the 'C' table loads even though
# a and b are loaded
c1 = s.query(A).filter_by(id=3).first()
s.delete(c1)
with self.sql_execution_asserter(testing.db) as asserter:
s.flush()
asserter.assert_(
CompiledSQL("DELETE FROM a WHERE a.id = :id", [{"id": 3}])
)
class OptimizedGetOnDeferredTest(fixtures.MappedTest):
"""test that the 'optimized get' path accommodates deferred columns.
Original issue tested is #3468, where loading of a deferred column
in an inherited subclass would fail.
At some point, the logic tested was no longer used and a less efficient
query was used to load these columns, but the test here did not inspect
the SQL such that this would be detected.
Test was then revised to more carefully test and now targets
#7463 as well.
"""
@classmethod
def define_tables(cls, metadata):
Table(
"a",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("type", String(10)),
)
Table(
"b",
metadata,
Column("id", Integer, ForeignKey("a.id"), primary_key=True),
Column("data", String(10)),
)
@classmethod
def setup_classes(cls):
class A(cls.Basic):
pass
class B(A):
pass
@classmethod
def setup_mappers(cls):
A, B = cls.classes("A", "B")
a, b = cls.tables("a", "b")
cls.mapper_registry.map_imperatively(A, a, polymorphic_on=a.c.type)
cls.mapper_registry.map_imperatively(
B,
b,
inherits=A,
polymorphic_identity="b",
properties={
"data": deferred(b.c.data),
"expr": column_property(b.c.data + "q", deferred=True),
},
)
def test_column_property(self):
A, B = self.classes("A", "B")
sess = fixture_session()
b1 = B(data="x")
sess.add(b1)
sess.flush()
b_id = b1.id
with self.sql_execution_asserter(testing.db) as asserter:
eq_(b1.expr, "xq")
asserter.assert_(
CompiledSQL(
"SELECT b.data || :data_1 AS anon_1 "
"FROM b WHERE :param_1 = b.id",
[{"param_1": b_id, "data_1": "q"}],
)
)
def test_expired_column(self):
A, B = self.classes("A", "B")
sess = fixture_session()
b1 = B(data="x")
sess.add(b1)
sess.flush()
b_id = b1.id
sess.expire(b1, ["data"])
with self.sql_execution_asserter(testing.db) as asserter:
eq_(b1.data, "x")
# uses efficient statement w/o JOIN to a
asserter.assert_(
CompiledSQL(
"SELECT b.data AS b_data FROM b WHERE :param_1 = b.id",
[{"param_1": b_id}],
)
)
def test_refresh_column(self):
"""refresh currently does not use the mapper "optimized get".
This could be added later by generalizing the code in
loading.py->load_scalar_attributes() to be used by session.refresh().
For #8703, where we are revisiting some of this logic for 2.0.0,
not doing this yet as enough is changing in 2.0 already.
"""
A, B = self.classes("A", "B")
sess = fixture_session()
b1 = B(data="x")
sess.add(b1)
sess.flush()
pk = b1.id
sess.expire(b1, ["data"])
with self.sql_execution_asserter(testing.db) as asserter:
sess.refresh(b1, ["data"])
asserter.assert_(
CompiledSQL(
# full statement that has a JOIN in it. Note that
# a.id is not included in the SELECT list
"SELECT b.data FROM a JOIN b ON a.id = b.id "
"WHERE a.id = :pk_1",
[{"pk_1": pk}]
# if we used load_scalar_attributes(), it would look like
# this
# "SELECT b.data AS b_data FROM b WHERE :param_1 = b.id",
# [{"param_1": b_id}],
)
)
def test_load_from_unloaded_subclass(self):
A, B = self.classes("A", "B")
sess = fixture_session()
b1 = B(data="x")
sess.add(b1)
sess.commit()
b_id = b1.id
sess.close()
# load polymorphically in terms of A, so that B needs another
# SELECT
b1 = sess.execute(select(A)).scalar()
# it's not loaded
assert "data" not in b1.__dict__
# but it loads successfully when requested
with self.sql_execution_asserter(testing.db) as asserter:
eq_(b1.data, "x")
# uses efficient statement w/o JOIN to a
asserter.assert_(
CompiledSQL(
"SELECT b.data AS b_data FROM b WHERE :param_1 = b.id",
[{"param_1": b_id}],
)
)
def test_load_from_expired_subclass(self):
A, B = self.classes("A", "B")
sess = fixture_session()
b1 = B(data="x")
sess.add(b1)
sess.commit()
b_id = b1.id
sess.close()
b1 = sess.execute(select(A)).scalar()
# it's not loaded
assert "data" not in b1.__dict__
eq_(b1.data, "x")
sess.expire(b1, ["data"])
with self.sql_execution_asserter(testing.db) as asserter:
eq_(b1.data, "x")
# uses efficient statement w/o JOIN to a
asserter.assert_(
CompiledSQL(
"SELECT b.data AS b_data FROM b WHERE :param_1 = b.id",
[{"param_1": b_id}],
)
)
class JoinedNoFKSortingTest(fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
Table(
"a",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
)
Table("b", metadata, Column("id", Integer, primary_key=True))
Table("c", metadata, Column("id", Integer, primary_key=True))
@classmethod
def setup_classes(cls):
class A(cls.Basic):
pass
class B(A):
pass
class C(A):
pass
@classmethod
def setup_mappers(cls):
A, B, C = cls.classes.A, cls.classes.B, cls.classes.C
cls.mapper_registry.map_imperatively(A, cls.tables.a)
cls.mapper_registry.map_imperatively(
B,
cls.tables.b,
inherits=A,
inherit_condition=cls.tables.a.c.id == cls.tables.b.c.id,
inherit_foreign_keys=cls.tables.b.c.id,
)
cls.mapper_registry.map_imperatively(
C,
cls.tables.c,
inherits=A,
inherit_condition=cls.tables.a.c.id == cls.tables.c.c.id,
inherit_foreign_keys=cls.tables.c.c.id,
)
def test_ordering(self):
B, C = self.classes.B, self.classes.C
sess = fixture_session()
sess.add_all([B(), C(), B(), C()])
self.assert_sql_execution(
testing.db,
sess.flush,
Conditional(
testing.db.dialect.insert_executemany_returning,
[
CompiledSQL(
"INSERT INTO a (id) VALUES (DEFAULT) RETURNING a.id",
[{}, {}, {}, {}],
),
],
[
CompiledSQL("INSERT INTO a () VALUES ()", {}),
CompiledSQL("INSERT INTO a () VALUES ()", {}),
CompiledSQL("INSERT INTO a () VALUES ()", {}),
CompiledSQL("INSERT INTO a () VALUES ()", {}),
],
),
AllOf(
CompiledSQL(
"INSERT INTO b (id) VALUES (:id)", [{"id": 1}, {"id": 3}]
),
CompiledSQL(
"INSERT INTO c (id) VALUES (:id)", [{"id": 2}, {"id": 4}]
),
),
)
class VersioningTest(fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
Table(
"base",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("version_id", Integer, nullable=False),
Column("value", String(40)),
Column("discriminator", Integer, nullable=False),
)
Table(
"subtable",
metadata,
Column("id", None, ForeignKey("base.id"), primary_key=True),
Column("subdata", String(50)),
)
Table(
"stuff",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("parent", Integer, ForeignKey("base.id")),
)
@testing.requires.sane_rowcount
def test_save_update(self):
subtable, base, stuff = (
self.tables.subtable,
self.tables.base,
self.tables.stuff,
)
class Base(fixtures.BasicEntity):
pass
class Sub(Base):
pass
class Stuff(Base):
pass
self.mapper_registry.map_imperatively(Stuff, stuff)
self.mapper_registry.map_imperatively(
Base,
base,
polymorphic_on=base.c.discriminator,
version_id_col=base.c.version_id,
polymorphic_identity=1,
properties={"stuff": relationship(Stuff)},
)
self.mapper_registry.map_imperatively(
Sub, subtable, inherits=Base, polymorphic_identity=2
)
sess = fixture_session(autoflush=False)
b1 = Base(value="b1")
s1 = Sub(value="sub1", subdata="some subdata")
sess.add(b1)
sess.add(s1)
sess.commit()
sess2 = fixture_session(autoflush=False)
s2 = sess2.get(Base, s1.id)
s2.subdata = "sess2 subdata"
s1.subdata = "sess1 subdata"
sess.commit()
assert_raises(
orm_exc.StaleDataError,
sess2.get,
Base,
s1.id,
with_for_update=dict(read=True),
)
if not testing.db.dialect.supports_sane_rowcount:
sess2.flush()
else:
assert_raises(orm_exc.StaleDataError, sess2.flush)
sess2.rollback()
sess2.refresh(s2)
if testing.db.dialect.supports_sane_rowcount:
assert s2.subdata == "sess1 subdata"
s2.subdata = "sess2 subdata"
sess2.flush()
@testing.requires.sane_rowcount
def test_delete(self):
subtable, base = self.tables.subtable, self.tables.base
class Base(fixtures.BasicEntity):
pass
class Sub(Base):
pass
self.mapper_registry.map_imperatively(
Base,
base,
polymorphic_on=base.c.discriminator,
version_id_col=base.c.version_id,
polymorphic_identity=1,
)
self.mapper_registry.map_imperatively(
Sub, subtable, inherits=Base, polymorphic_identity=2
)
sess = fixture_session(autoflush=False, expire_on_commit=False)
b1 = Base(value="b1")
s1 = Sub(value="sub1", subdata="some subdata")
s2 = Sub(value="sub2", subdata="some other subdata")
sess.add(b1)
sess.add(s1)
sess.add(s2)
sess.commit()
sess2 = fixture_session(autoflush=False, expire_on_commit=False)
s3 = sess2.get(Base, s1.id)
sess2.delete(s3)
sess2.commit()
s2.subdata = "some new subdata"
sess.commit()
s1.subdata = "some new subdata"
if testing.db.dialect.supports_sane_rowcount:
assert_raises(orm_exc.StaleDataError, sess.commit)
else:
sess.commit()
class DistinctPKTest(fixtures.MappedTest):
"""test the construction of mapper.primary_key when an inheriting
relationship joins on a column other than primary key column."""
run_inserts = "once"
run_deletes = None
@classmethod
def define_tables(cls, metadata):
global person_table, employee_table, Person, Employee
person_table = Table(
"persons",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("name", String(80)),
)
employee_table = Table(
"employees",
metadata,
Column(
"eid", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("salary", Integer),
Column("person_id", Integer, ForeignKey("persons.id")),
)
class Person:
def __init__(self, name):
self.name = name
class Employee(Person):
pass
@classmethod
def insert_data(cls, connection):
person_insert = person_table.insert()
connection.execute(person_insert, dict(id=1, name="alice"))
connection.execute(person_insert, dict(id=2, name="bob"))
employee_insert = employee_table.insert()
connection.execute(
employee_insert, dict(id=2, salary=250, person_id=1)
) # alice
connection.execute(
employee_insert, dict(id=3, salary=200, person_id=2)
) # bob
def test_implicit(self):
person_mapper = self.mapper_registry.map_imperatively(
Person, person_table
)
self.mapper_registry.map_imperatively(
Employee, employee_table, inherits=person_mapper
)
assert list(class_mapper(Employee).primary_key) == [person_table.c.id]
def test_explicit_props(self):
person_mapper = self.mapper_registry.map_imperatively(
Person, person_table
)
self.mapper_registry.map_imperatively(
Employee,
employee_table,
inherits=person_mapper,
properties={"pid": person_table.c.id, "eid": employee_table.c.eid},
)
self._do_test(False)
def test_explicit_composite_pk(self):
person_mapper = self.mapper_registry.map_imperatively(
Person, person_table
)
self.mapper_registry.map_imperatively(
Employee,
employee_table,
inherits=person_mapper,
properties=dict(id=[employee_table.c.eid, person_table.c.id]),
primary_key=[person_table.c.id, employee_table.c.eid],
)
assert_warns_message(
sa_exc.SAWarning,
r"On mapper Mapper\[Employee\(employees\)\], "
"primary key column 'persons.id' is being "
"combined with distinct primary key column 'employees.eid' "
"in attribute 'id'. Use explicit properties to give "
"each column its own mapped attribute name.",
self._do_test,
True,
)
def test_explicit_pk(self):
person_mapper = self.mapper_registry.map_imperatively(
Person, person_table
)
self.mapper_registry.map_imperatively(
Employee,
employee_table,
inherits=person_mapper,
primary_key=[person_table.c.id],
)
self._do_test(False)
def _do_test(self, composite):
session = fixture_session()
if composite:
alice1 = session.get(Employee, [1, 2])
bob = session.get(Employee, [2, 3])
alice2 = session.get(Employee, [1, 2])
else:
alice1 = session.get(Employee, 1)
bob = session.get(Employee, 2)
alice2 = session.get(Employee, 1)
assert alice1.name == alice2.name == "alice"
assert bob.name == "bob"
class SyncCompileTest(fixtures.MappedTest):
"""test that syncrules compile properly on custom inherit conds"""
@classmethod
def define_tables(cls, metadata):
global _a_table, _b_table, _c_table
_a_table = Table(
"a",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("data1", String(128)),
)
_b_table = Table(
"b",
metadata,
Column("a_id", Integer, ForeignKey("a.id"), primary_key=True),
Column("data2", String(128)),
)
_c_table = Table(
"c",
metadata,
# Column('a_id', Integer, ForeignKey('b.a_id'),
# primary_key=True), #works
Column("b_a_id", Integer, ForeignKey("b.a_id"), primary_key=True),
Column("data3", String(128)),
)
@testing.combinations(
lambda _a_table, _b_table: None,
lambda _a_table, _b_table: _b_table.c.a_id == _a_table.c.id,
lambda _a_table, _b_table: _a_table.c.id == _b_table.c.a_id,
argnames="j1",
)
@testing.combinations(
lambda _b_table, _c_table: None,
lambda _b_table, _c_table: _b_table.c.a_id == _c_table.c.b_a_id,
lambda _b_table, _c_table: _c_table.c.b_a_id == _b_table.c.a_id,
argnames="j2",
)
def test_joins(self, j1, j2):
_a_table, _b_table, _c_table = self.tables("a", "b", "c")
j1 = testing.resolve_lambda(j1, **locals())
j2 = testing.resolve_lambda(j2, **locals())
class A:
def __init__(self, **kwargs):
for key, value in list(kwargs.items()):
setattr(self, key, value)
class B(A):
pass
class C(B):
pass
self.mapper_registry.map_imperatively(A, _a_table)
self.mapper_registry.map_imperatively(
B, _b_table, inherits=A, inherit_condition=j1
)
self.mapper_registry.map_imperatively(
C, _c_table, inherits=B, inherit_condition=j2
)
session = fixture_session()
a = A(data1="a1")
session.add(a)
b = B(data1="b1", data2="b2")
session.add(b)
c = C(data1="c1", data2="c2", data3="c3")
session.add(c)
session.flush()
session.expunge_all()
assert len(session.query(A).all()) == 3
assert len(session.query(B).all()) == 2
assert len(session.query(C).all()) == 1
class OverrideColKeyTest(fixtures.MappedTest):
"""test overriding of column attributes."""
@classmethod
def define_tables(cls, metadata):
global base, subtable, subtable_two
base = Table(
"base",
metadata,
Column(
"base_id",
Integer,
primary_key=True,
test_needs_autoincrement=True,
),
Column("data", String(255)),
Column("sqlite_fixer", String(10)),
)
subtable = Table(
"subtable",
metadata,
Column(
"base_id",
Integer,
ForeignKey("base.base_id"),
primary_key=True,
),
Column("subdata", String(255)),
)
subtable_two = Table(
"subtable_two",
metadata,
Column("base_id", Integer, primary_key=True),
Column("fk_base_id", Integer, ForeignKey("base.base_id")),
Column("subdata", String(255)),
)
def test_plain(self):
# control case
class Base:
pass
class Sub(Base):
pass
self.mapper_registry.map_imperatively(Base, base)
self.mapper_registry.map_imperatively(Sub, subtable, inherits=Base)
# Sub gets a "base_id" property using the "base_id"
# column of both tables.
eq_(
class_mapper(Sub).get_property("base_id").columns,
[subtable.c.base_id, base.c.base_id],
)
def test_override_explicit(self):
# this pattern is what you see when using declarative
# in particular, here we do a "manual" version of
# what we'd like the mapper to do.
class Base:
pass
class Sub(Base):
pass
self.mapper_registry.map_imperatively(
Base, base, properties={"id": base.c.base_id}
)
self.mapper_registry.map_imperatively(
Sub,
subtable,
inherits=Base,
properties={
# this is the manual way to do it, is not really
# possible in declarative
"id": [base.c.base_id, subtable.c.base_id]
},
)
eq_(
class_mapper(Sub).get_property("id").columns,
[base.c.base_id, subtable.c.base_id],
)
s1 = Sub()
s1.id = 10
sess = fixture_session()
sess.add(s1)
sess.flush()
assert sess.get(Sub, 10) is s1
def test_override_onlyinparent(self):
class Base:
pass
class Sub(Base):
pass
self.mapper_registry.map_imperatively(
Base, base, properties={"id": base.c.base_id}
)
self.mapper_registry.map_imperatively(Sub, subtable, inherits=Base)
eq_(class_mapper(Sub).get_property("id").columns, [base.c.base_id])
eq_(
class_mapper(Sub).get_property("base_id").columns,
[subtable.c.base_id],
)
s1 = Sub()
s1.id = 10
s2 = Sub()
s2.base_id = 15
sess = fixture_session()
sess.add_all([s1, s2])
sess.flush()
# s1 gets '10'
assert sess.get(Sub, 10) is s1
# s2 gets a new id, base_id is overwritten by the ultimate
# PK col
assert s2.id == s2.base_id != 15
def test_subclass_renames_superclass_col_single_inh(self, decl_base):
"""tested as part of #8705.
The step where we configure columns mapped to specific keys must
take place even if the given column is already in _columntoproperty,
as would be the case if the superclass maps that column already.
"""
class A(decl_base):
__tablename__ = "a"
id = Column(Integer, primary_key=True)
a_data = Column(String)
class B(A):
b_data = column_property(A.__table__.c.a_data)
is_(A.a_data.property.columns[0], A.__table__.c.a_data)
is_(B.a_data.property.columns[0], A.__table__.c.a_data)
is_(B.b_data.property.columns[0], A.__table__.c.a_data)
def test_subsubclass_groups_super_cols(self, decl_base):
"""tested for #9220, which is a regression caused by #8705."""
class BaseClass(decl_base):
__tablename__ = "basetable"
id = Column(Integer, primary_key=True)
name = Column(String(50))
type = Column(String(20))
__mapper_args__ = {
"polymorphic_on": type,
"polymorphic_identity": "base",
}
class SubClass(BaseClass):
__tablename__ = "subtable"
id = column_property(
Column(Integer, primary_key=True), BaseClass.id
)
base_id = Column(Integer, ForeignKey("basetable.id"))
subdata1 = Column(String(50))
__mapper_args__ = {"polymorphic_identity": "sub"}
class SubSubClass(SubClass):
__tablename__ = "subsubtable"
id = column_property(
Column(Integer, ForeignKey("subtable.id"), primary_key=True),
SubClass.id,
BaseClass.id,
)
subdata2 = Column(String(50))
__mapper_args__ = {"polymorphic_identity": "subsub"}
is_(SubSubClass.id.property.columns[0], SubSubClass.__table__.c.id)
is_(
SubSubClass.id.property.columns[1]._deannotate(),
SubClass.__table__.c.id,
)
is_(
SubSubClass.id.property.columns[2]._deannotate(),
BaseClass.__table__.c.id,
)
def test_column_setup_sanity_check(self, decl_base):
class A(decl_base):
__tablename__ = "a"
id = Column(Integer, primary_key=True)
a_data = Column(String)
class B(A):
__tablename__ = "b"
id = Column(Integer, ForeignKey("a.id"), primary_key=True)
b_data = Column(String)
is_(A.id.property.parent, inspect(A))
# overlapping cols get a new prop on the subclass, with cols merged
is_(B.id.property.parent, inspect(B))
eq_(B.id.property.columns, [B.__table__.c.id, A.__table__.c.id])
# totally independent cols remain w/ parent on the originating
# mapper
is_(B.a_data.property.parent, inspect(A))
is_(B.b_data.property.parent, inspect(B))
def test_override_implicit(self):
# this is originally [ticket:1111].
# the pattern here is now disallowed by [ticket:1892]
class Base:
pass
class Sub(Base):
pass
self.mapper_registry.map_imperatively(
Base, base, properties={"id": base.c.base_id}
)
with expect_raises_message(
sa_exc.InvalidRequestError,
"Implicitly combining column base.base_id with column "
"subtable.base_id under attribute 'id'. Please configure one "
"or more attributes for these same-named columns explicitly.",
):
self.mapper_registry.map_imperatively(
Sub,
subtable,
inherits=Base,
properties={"id": subtable.c.base_id},
)
def test_pk_fk_different(self):
class Base:
pass
class Sub(Base):
pass
self.mapper_registry.map_imperatively(Base, base)
def go():
self.mapper_registry.map_imperatively(
Sub, subtable_two, inherits=Base
)
assert_warns_message(
sa_exc.SAWarning,
"Implicitly combining column base.base_id with "
"column subtable_two.base_id under attribute 'base_id'",
go,
)
def test_plain_descriptor(self):
"""test that descriptors prevent inheritance from propagating
properties to subclasses."""
class Base:
pass
class Sub(Base):
@property
def data(self):
return "im the data"
self.mapper_registry.map_imperatively(Base, base)
self.mapper_registry.map_imperatively(Sub, subtable, inherits=Base)
s1 = Sub()
sess = fixture_session()
sess.add(s1)
sess.flush()
assert sess.query(Sub).one().data == "im the data"
def test_custom_descriptor(self):
"""test that descriptors prevent inheritance from propagating
properties to subclasses."""
class MyDesc:
def __get__(self, instance, owner):
if instance is None:
return self
return "im the data"
class Base:
pass
class Sub(Base):
data = MyDesc()
self.mapper_registry.map_imperatively(Base, base)
self.mapper_registry.map_imperatively(Sub, subtable, inherits=Base)
s1 = Sub()
sess = fixture_session()
sess.add(s1)
sess.flush()
assert sess.query(Sub).one().data == "im the data"
def test_sub_columns_over_base_descriptors(self):
class Base:
@property
def subdata(self):
return "this is base"
class Sub(Base):
pass
self.mapper_registry.map_imperatively(Base, base)
self.mapper_registry.map_imperatively(Sub, subtable, inherits=Base)
sess = fixture_session()
b1 = Base()
assert b1.subdata == "this is base"
s1 = Sub()
s1.subdata = "this is sub"
assert s1.subdata == "this is sub"
sess.add_all([s1, b1])
sess.flush()
sess.expunge_all()
assert sess.get(Base, b1.base_id).subdata == "this is base"
assert sess.get(Sub, s1.base_id).subdata == "this is sub"
def test_base_descriptors_over_base_cols(self):
class Base:
@property
def data(self):
return "this is base"
class Sub(Base):
pass
self.mapper_registry.map_imperatively(Base, base)
self.mapper_registry.map_imperatively(Sub, subtable, inherits=Base)
sess = fixture_session()
b1 = Base()
assert b1.data == "this is base"
s1 = Sub()
assert s1.data == "this is base"
sess.add_all([s1, b1])
sess.flush()
sess.expunge_all()
assert sess.get(Base, b1.base_id).data == "this is base"
assert sess.get(Sub, s1.base_id).data == "this is base"
class OptimizedLoadTest(fixtures.MappedTest):
"""tests for the "optimized load" routine."""
__backend__ = True
@classmethod
def define_tables(cls, metadata):
Table(
"base",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("data", String(50)),
Column("type", String(50)),
Column("counter", Integer, server_default="1"),
)
Table(
"sub",
metadata,
Column("id", Integer, ForeignKey("base.id"), primary_key=True),
Column("sub", String(50)),
Column("subcounter", Integer, server_default="1"),
Column("subcounter2", Integer, server_default="1"),
)
Table(
"subsub",
metadata,
Column("id", Integer, ForeignKey("sub.id"), primary_key=True),
Column("subsubcounter2", Integer, server_default="1"),
)
Table(
"with_comp",
metadata,
Column("id", Integer, ForeignKey("base.id"), primary_key=True),
Column("a", String(10)),
Column("b", String(10)),
)
def test_no_optimize_on_map_to_join(self):
base, sub = self.tables.base, self.tables.sub
class Base(fixtures.ComparableEntity):
pass
class JoinBase(fixtures.ComparableEntity):
pass
class SubJoinBase(JoinBase):
pass
self.mapper_registry.map_imperatively(Base, base)
self.mapper_registry.map_imperatively(
JoinBase,
base.outerjoin(sub),
properties=util.OrderedDict(
[
("id", [base.c.id, sub.c.id]),
("counter", [base.c.counter, sub.c.subcounter]),
]
),
)
self.mapper_registry.map_imperatively(SubJoinBase, inherits=JoinBase)
sess = fixture_session()
sess.add(Base(data="data"))
sess.commit()
sjb = sess.query(SubJoinBase).one()
sjb_id = sjb.id
sess.expire(sjb)
# this should not use the optimized load,
# which assumes discrete tables
def go():
eq_(sjb.data, "data")
self.assert_sql_execution(
testing.db,
go,
CompiledSQL(
"SELECT base.id AS base_id, sub.id AS sub_id, "
"base.data AS base_data, base.type AS base_type, "
"base.counter AS base_counter, "
"sub.subcounter AS sub_subcounter, "
"sub.sub AS sub_sub, sub.subcounter2 AS sub_subcounter2 "
"FROM base LEFT OUTER JOIN sub ON base.id = sub.id "
"WHERE base.id = :pk_1",
{"pk_1": sjb_id},
),
)
def test_optimized_load_subclass_labels(self):
# test for issue #4718, however it may be difficult to maintain
# the conditions here:
# 1. optimized get is used to load some attributes
# 2. the subtable-only statement is generated
# 3. the mapper (a subclass mapper) is against a with_polymorphic
# that is using a labeled select
#
# the optimized loader has to cancel out the polymorphic for the
# query (or adapt around it) since optimized get creates a simple
# SELECT statement. Otherwise it often relies on _key_fallback
# columns in order to do the lookup.
#
# note this test can't fail when the fix is missing unless
# CursorResult._key_fallback no longer allows a non-matching column
# lookup without warning or raising.
base, sub = self.tables.base, self.tables.sub
class Base(fixtures.ComparableEntity):
pass
class Sub(Base):
pass
self.mapper_registry.map_imperatively(
Base, base, polymorphic_on=base.c.type, polymorphic_identity="base"
)
self.mapper_registry.map_imperatively(
Sub,
sub,
inherits=Base,
polymorphic_identity="sub",
with_polymorphic=(
"*",
base.outerjoin(sub)
.select()
.set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
.alias("foo"),
),
)
sess = fixture_session()
s1 = Sub(
data="s1data", sub="s1sub", subcounter=1, counter=1, subcounter2=1
)
sess.add(s1)
sess.flush()
sess.expire(s1, ["sub"])
def _key_fallback(self, key, raiseerr):
raise KeyError(key)
with mock.patch(
"sqlalchemy.engine.result.ResultMetaData._key_fallback",
_key_fallback,
):
eq_(s1.sub, "s1sub")
def test_optimized_get_blank_intermediary(self, registry, connection):
"""test #7507"""
Base = registry.generate_base()
class A(Base):
__tablename__ = "a"
id = Column(
Integer, primary_key=True, test_needs_autoincrement=True
)
a = Column(String(20), nullable=False)
type_ = Column("type", String(20))
__mapper_args__ = {
"polymorphic_on": type_,
"polymorphic_identity": "a",
}
class B(A):
__tablename__ = "b"
__mapper_args__ = {"polymorphic_identity": "b"}
id = Column(Integer, ForeignKey("a.id"), primary_key=True)
b = Column(String(20), nullable=False)
class C(B):
__tablename__ = "c"
__mapper_args__ = {"polymorphic_identity": "c"}
id = Column(Integer, ForeignKey("b.id"), primary_key=True)
class D(C):
__tablename__ = "d"
__mapper_args__ = {"polymorphic_identity": "d"}
id = Column(Integer, ForeignKey("c.id"), primary_key=True)
c = Column(String(20), nullable=False)
Base.metadata.create_all(connection)
session = Session(connection)
session.add(D(a="x", b="y", c="z"))
session.commit()
with self.sql_execution_asserter(connection) as asserter:
d = session.query(A).one()
eq_(d.c, "z")
asserter.assert_(
CompiledSQL(
"SELECT a.id AS a_id, a.a AS a_a, a.type AS a_type FROM a",
[],
),
Or(
CompiledSQL(
"SELECT d.c AS d_c, b.b AS b_b FROM d, b, c WHERE "
":param_1 = b.id AND b.id = c.id AND c.id = d.id",
[{"param_1": 1}],
),
CompiledSQL(
"SELECT b.b AS b_b, d.c AS d_c FROM b, d, c WHERE "
":param_1 = b.id AND b.id = c.id AND c.id = d.id",
[{"param_1": 1}],
),
),
)
def test_optimized_passes(self):
""" "test that the 'optimized load' routine doesn't crash when
a column in the join condition is not available."""
base, sub = self.tables.base, self.tables.sub
class Base(fixtures.ComparableEntity):
pass
class Sub(Base):
pass
self.mapper_registry.map_imperatively(
Base, base, polymorphic_on=base.c.type, polymorphic_identity="base"
)
# redefine Sub's "id" to favor the "id" col in the subtable.
# "id" is also part of the primary join condition
self.mapper_registry.map_imperatively(
Sub,
sub,
inherits=Base,
polymorphic_identity="sub",
properties={"id": [sub.c.id, base.c.id]},
)
sess = fixture_session()
s1 = Sub(data="s1data", sub="s1sub")
sess.add(s1)
sess.commit()
sess.expunge_all()
# load s1 via Base. s1.id won't populate since it's relative to
# the "sub" table. The optimized load kicks in and tries to
# generate on the primary join, but cannot since "id" is itself
# unloaded. the optimized load needs to return "None" so regular
# full-row loading proceeds
s1 = sess.query(Base).first()
assert s1.sub == "s1sub"
def test_column_expression(self):
base, sub = self.tables.base, self.tables.sub
class Base(fixtures.ComparableEntity):
pass
class Sub(Base):
pass
self.mapper_registry.map_imperatively(
Base, base, polymorphic_on=base.c.type, polymorphic_identity="base"
)
self.mapper_registry.map_imperatively(
Sub,
sub,
inherits=Base,
polymorphic_identity="sub",
properties={
"concat": column_property(sub.c.sub + "|" + sub.c.sub)
},
)
sess = fixture_session()
s1 = Sub(data="s1data", sub="s1sub")
sess.add(s1)
sess.commit()
sess.expunge_all()
s1 = sess.query(Base).first()
assert s1.concat == "s1sub|s1sub"
def test_column_expression_joined(self):
base, sub = self.tables.base, self.tables.sub
class Base(fixtures.ComparableEntity):
pass
class Sub(Base):
pass
self.mapper_registry.map_imperatively(
Base, base, polymorphic_on=base.c.type, polymorphic_identity="base"
)
self.mapper_registry.map_imperatively(
Sub,
sub,
inherits=Base,
polymorphic_identity="sub",
properties={
"concat": column_property(base.c.data + "|" + sub.c.sub)
},
)
sess = fixture_session()
s1 = Sub(data="s1data", sub="s1sub")
s2 = Sub(data="s2data", sub="s2sub")
s3 = Sub(data="s3data", sub="s3sub")
sess.add_all([s1, s2, s3])
sess.commit()
sess.expunge_all()
# query a bunch of rows to ensure there's no cartesian
# product against "base" occurring, it is in fact
# detecting that "base" needs to be in the join
# criterion
eq_(
sess.query(Base).order_by(Base.id).all(),
[
Sub(data="s1data", sub="s1sub", concat="s1data|s1sub"),
Sub(data="s2data", sub="s2sub", concat="s2data|s2sub"),
Sub(data="s3data", sub="s3sub", concat="s3data|s3sub"),
],
)
def test_composite_column_joined(self):
base, with_comp = self.tables.base, self.tables.with_comp
class Base(fixtures.BasicEntity):
pass
class WithComp(Base):
pass
class Comp:
def __init__(self, a, b):
self.a = a
self.b = b
def __composite_values__(self):
return self.a, self.b
def __eq__(self, other):
return (self.a == other.a) and (self.b == other.b)
self.mapper_registry.map_imperatively(
Base, base, polymorphic_on=base.c.type, polymorphic_identity="base"
)
self.mapper_registry.map_imperatively(
WithComp,
with_comp,
inherits=Base,
polymorphic_identity="wc",
properties={"comp": composite(Comp, with_comp.c.a, with_comp.c.b)},
)
sess = fixture_session()
s1 = WithComp(data="s1data", comp=Comp("ham", "cheese"))
s2 = WithComp(data="s2data", comp=Comp("bacon", "eggs"))
sess.add_all([s1, s2])
sess.commit()
sess.expunge_all()
s1test, s2test = sess.query(Base).order_by(Base.id).all()
assert s1test.comp
assert s2test.comp
eq_(s1test.comp, Comp("ham", "cheese"))
eq_(s2test.comp, Comp("bacon", "eggs"))
@testing.variation("eager_defaults", [True, False])
def test_load_expired_on_pending(self, eager_defaults):
base, sub = self.tables.base, self.tables.sub
expected_eager_defaults = bool(eager_defaults)
expect_returning = (
expected_eager_defaults and testing.db.dialect.insert_returning
)
class Base(fixtures.BasicEntity):
pass
class Sub(Base):
pass
self.mapper_registry.map_imperatively(
Base,
base,
polymorphic_on=base.c.type,
polymorphic_identity="base",
eager_defaults=bool(eager_defaults),
)
self.mapper_registry.map_imperatively(
Sub, sub, inherits=Base, polymorphic_identity="sub"
)
sess = fixture_session()
s1 = Sub(data="s1")
sess.add(s1)
self.assert_sql_execution(
testing.db,
sess.flush,
Conditional(
expect_returning,
[
CompiledSQL(
"INSERT INTO base (data, type) VALUES (:data, :type) "
"RETURNING base.id, base.counter",
[{"data": "s1", "type": "sub"}],
),
CompiledSQL(
"INSERT INTO sub (id, sub) VALUES (:id, :sub) "
"RETURNING sub.subcounter, sub.subcounter2",
lambda ctx: {"id": s1.id, "sub": None},
),
],
[
CompiledSQL(
"INSERT INTO base (data, type) VALUES (:data, :type)",
[{"data": "s1", "type": "sub"}],
enable_returning=False,
),
CompiledSQL(
"INSERT INTO sub (id, sub) VALUES (:id, :sub)",
lambda ctx: {"id": s1.id, "sub": None},
enable_returning=False,
),
Conditional(
bool(eager_defaults),
[
CompiledSQL(
"SELECT base.counter AS base_counter, "
"sub.subcounter AS sub_subcounter, "
"sub.subcounter2 AS sub_subcounter2 "
"FROM base JOIN sub ON base.id = sub.id "
"WHERE base.id = :pk_1",
lambda ctx: {"pk_1": s1.id},
)
],
[],
),
],
),
)
def go():
eq_(s1.subcounter2, 1)
self.assert_sql_execution(
testing.db,
go,
Conditional(
not eager_defaults and not expect_returning,
[
CompiledSQL(
"SELECT base.counter AS base_counter, "
"sub.subcounter AS sub_subcounter, sub.subcounter2 "
"AS sub_subcounter2 FROM base "
"JOIN sub ON base.id = sub.id WHERE base.id = :pk_1",
lambda ctx: {"pk_1": s1.id},
)
],
[],
),
)
def test_dont_generate_on_none(self):
base, sub = self.tables.base, self.tables.sub
class Base(fixtures.BasicEntity):
pass
class Sub(Base):
pass
self.mapper_registry.map_imperatively(
Base, base, polymorphic_on=base.c.type, polymorphic_identity="base"
)
m = self.mapper_registry.map_imperatively(
Sub, sub, inherits=Base, polymorphic_identity="sub"
)
s1 = Sub()
assert (
m._optimized_get_statement(
attributes.instance_state(s1), ["subcounter2"]
)
is None
)
# loads s1.id as None
eq_(s1.id, None)
# this now will come up with a value of None for id - should reject
assert (
m._optimized_get_statement(
attributes.instance_state(s1), ["subcounter2"]
)
is None
)
s1.id = 1
attributes.instance_state(s1)._commit_all(s1.__dict__, None)
assert (
m._optimized_get_statement(
attributes.instance_state(s1), ["subcounter2"]
)
is not None
)
def test_load_expired_on_pending_twolevel(self):
base, sub, subsub = (
self.tables.base,
self.tables.sub,
self.tables.subsub,
)
class Base(fixtures.BasicEntity):
pass
class Sub(Base):
pass
class SubSub(Sub):
pass
self.mapper_registry.map_imperatively(
Base, base, polymorphic_on=base.c.type, polymorphic_identity="base"
)
self.mapper_registry.map_imperatively(
Sub, sub, inherits=Base, polymorphic_identity="sub"
)
self.mapper_registry.map_imperatively(
SubSub, subsub, inherits=Sub, polymorphic_identity="subsub"
)
sess = fixture_session()
s1 = SubSub(data="s1", counter=1, subcounter=2)
sess.add(s1)
self.assert_sql_execution(
testing.db,
sess.flush,
CompiledSQL(
"INSERT INTO base (data, type, counter) VALUES "
"(:data, :type, :counter)",
[{"data": "s1", "type": "subsub", "counter": 1}],
),
CompiledSQL(
"INSERT INTO sub (id, sub, subcounter) VALUES "
"(:id, :sub, :subcounter)",
lambda ctx: [{"subcounter": 2, "sub": None, "id": s1.id}],
),
CompiledSQL(
"INSERT INTO subsub (id) VALUES (:id)",
lambda ctx: {"id": s1.id},
),
)
def go():
eq_(s1.subcounter2, 1)
self.assert_sql_execution(
testing.db,
go,
Or(
CompiledSQL(
"SELECT subsub.subsubcounter2 AS subsub_subsubcounter2, "
"sub.subcounter2 AS sub_subcounter2 FROM subsub, sub "
"WHERE :param_1 = sub.id AND sub.id = subsub.id",
lambda ctx: {"param_1": s1.id},
),
CompiledSQL(
"SELECT sub.subcounter2 AS sub_subcounter2, "
"subsub.subsubcounter2 AS subsub_subsubcounter2 "
"FROM sub, subsub "
"WHERE :param_1 = sub.id AND sub.id = subsub.id",
lambda ctx: {"param_1": s1.id},
),
),
)
class NoPKOnSubTableWarningTest(fixtures.MappedTest):
def _fixture(self):
metadata = MetaData()
parent = Table(
"parent", metadata, Column("id", Integer, primary_key=True)
)
child = Table(
"child", metadata, Column("id", Integer, ForeignKey("parent.id"))
)
return parent, child
def test_warning_on_sub(self):
parent, child = self._fixture()
class P:
pass
class C(P):
pass
self.mapper_registry.map_imperatively(P, parent)
assert_warns_message(
sa_exc.SAWarning,
"Could not assemble any primary keys for locally mapped "
"table 'child' - no rows will be persisted in this Table.",
self.mapper_registry.map_imperatively,
C,
child,
inherits=P,
)
def test_no_warning_with_explicit(self):
parent, child = self._fixture()
class P:
pass
class C(P):
pass
self.mapper_registry.map_imperatively(P, parent)
mc = self.mapper_registry.map_imperatively(
C, child, inherits=P, primary_key=[parent.c.id]
)
eq_(mc.primary_key, (parent.c.id,))
class InhCondTest(fixtures.MappedTest):
def test_inh_cond_nonexistent_table_unrelated(self):
metadata = MetaData()
base_table = Table(
"base", metadata, Column("id", Integer, primary_key=True)
)
derived_table = Table(
"derived",
metadata,
Column("id", Integer, ForeignKey("base.id"), primary_key=True),
Column("owner_id", Integer, ForeignKey("owner.owner_id")),
)
class Base:
pass
class Derived(Base):
pass
self.mapper_registry.map_imperatively(Base, base_table)
# succeeds, despite "owner" table not configured yet
m2 = self.mapper_registry.map_imperatively(
Derived, derived_table, inherits=Base
)
assert m2.inherit_condition.compare(
base_table.c.id == derived_table.c.id
)
def test_inh_cond_nonexistent_col_unrelated(self):
m = MetaData()
base_table = Table("base", m, Column("id", Integer, primary_key=True))
derived_table = Table(
"derived",
m,
Column("id", Integer, ForeignKey("base.id"), primary_key=True),
Column("order_id", Integer, ForeignKey("order.foo")),
)
Table("order", m, Column("id", Integer, primary_key=True))
class Base:
pass
class Derived(Base):
pass
self.mapper_registry.map_imperatively(Base, base_table)
# succeeds, despite "order.foo" doesn't exist
m2 = self.mapper_registry.map_imperatively(
Derived, derived_table, inherits=Base
)
assert m2.inherit_condition.compare(
base_table.c.id == derived_table.c.id
)
def test_inh_cond_no_fk(self):
metadata = MetaData()
base_table = Table(
"base", metadata, Column("id", Integer, primary_key=True)
)
derived_table = Table(
"derived", metadata, Column("id", Integer, primary_key=True)
)
class Base:
pass
class Derived(Base):
pass
self.mapper_registry.map_imperatively(Base, base_table)
assert_raises_message(
sa_exc.NoForeignKeysError,
"Can't determine the inherit condition between inherited table "
"'base' and inheriting table 'derived'; tables have no foreign "
"key relationships established. Please ensure the inheriting "
"table has a foreign key relationship to the inherited table, "
"or provide an 'on clause' using the 'inherit_condition' "
"mapper argument.",
self.mapper,
Derived,
derived_table,
inherits=Base,
)
def test_inh_cond_ambiguous_fk(self):
metadata = MetaData()
base_table = Table(
"base",
metadata,
Column("id", Integer, primary_key=True),
Column("favorite_derived", ForeignKey("derived.id")),
)
derived_table = Table(
"derived",
metadata,
Column("id", Integer, ForeignKey("base.id"), primary_key=True),
)
class Base:
pass
class Derived(Base):
pass
self.mapper(Base, base_table)
assert_raises_message(
sa_exc.AmbiguousForeignKeysError,
"Can't determine the inherit condition between inherited table "
"'base' and inheriting table 'derived'; tables have more than "
"one foreign key relationship established. Please specify the "
"'on clause' using the 'inherit_condition' mapper argument.",
self.mapper,
Derived,
derived_table,
inherits=Base,
)
def test_inh_cond_nonexistent_table_related(self):
m1 = MetaData()
m2 = MetaData()
base_table = Table("base", m1, Column("id", Integer, primary_key=True))
derived_table = Table(
"derived",
m2,
Column("id", Integer, ForeignKey("base.id"), primary_key=True),
)
class Base:
pass
class Derived(Base):
pass
clear_mappers()
self.mapper_registry.map_imperatively(Base, base_table)
# the ForeignKey def is correct but there are two
# different metadatas. Would like the traditional
# "noreferencedtable" error to raise so that the
# user is directed towards the FK definition in question.
assert_raises_message(
sa_exc.NoReferencedTableError,
"Foreign key associated with column 'derived.id' "
"could not find table 'base' with which to generate "
"a foreign key to target column 'id'",
self.mapper,
Derived,
derived_table,
inherits=Base,
)
def test_inh_cond_nonexistent_col_related(self):
m = MetaData()
base_table = Table("base", m, Column("id", Integer, primary_key=True))
derived_table = Table(
"derived",
m,
Column("id", Integer, ForeignKey("base.q"), primary_key=True),
)
class Base:
pass
class Derived(Base):
pass
clear_mappers()
self.mapper_registry.map_imperatively(Base, base_table)
assert_raises_message(
sa_exc.NoReferencedColumnError,
"Could not initialize target column for ForeignKey "
"'base.q' on table "
"'derived': table 'base' has no column named 'q'",
self.mapper,
Derived,
derived_table,
inherits=Base,
)
class PKDiscriminatorTest(fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
Table(
"parents",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("name", String(60)),
)
Table(
"children",
metadata,
Column("id", Integer, ForeignKey("parents.id"), primary_key=True),
Column("type", Integer, primary_key=True),
Column("name", String(60)),
)
def test_pk_as_discriminator(self):
parents, children = self.tables.parents, self.tables.children
class Parent:
def __init__(self, name=None):
self.name = name
class Child:
def __init__(self, name=None):
self.name = name
class A(Child):
pass
self.mapper_registry.map_imperatively(
Parent,
parents,
properties={"children": relationship(Child, backref="parent")},
)
self.mapper_registry.map_imperatively(
Child,
children,
polymorphic_on=children.c.type,
polymorphic_identity=1,
)
self.mapper_registry.map_imperatively(
A, inherits=Child, polymorphic_identity=2
)
s = fixture_session()
p = Parent("p1")
a = A("a1")
p.children.append(a)
s.add(p)
s.flush()
assert a.id
assert a.type == 2
p.name = "p1new"
a.name = "a1new"
s.flush()
s.expire_all()
assert a.name == "a1new"
assert p.name == "p1new"
class NoPolyIdentInMiddleTest(fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
Table(
"base",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("type", String(50), nullable=False),
)
@classmethod
def setup_classes(cls):
class A(cls.Comparable):
pass
class B(A):
pass
class C(B):
pass
class D(B):
pass
class E(A):
pass
@classmethod
def setup_mappers(cls):
A, C, B, E, D, base = (
cls.classes.A,
cls.classes.C,
cls.classes.B,
cls.classes.E,
cls.classes.D,
cls.tables.base,
)
cls.mapper_registry.map_imperatively(
A, base, polymorphic_on=base.c.type
)
with expect_warnings(
r"Mapper\[B\(base\)\] does not indicate a "
"'polymorphic_identity',"
):
cls.mapper_registry.map_imperatively(B, inherits=A)
cls.mapper_registry.map_imperatively(
C, inherits=B, polymorphic_identity="c"
)
cls.mapper_registry.map_imperatively(
D, inherits=B, polymorphic_identity="d"
)
cls.mapper_registry.map_imperatively(
E, inherits=A, polymorphic_identity="e"
)
cls.mapper_registry.configure()
def test_warning(self, decl_base):
"""test #7545"""
class A(decl_base):
__tablename__ = "a"
id = Column(Integer, primary_key=True)
type = Column(String)
__mapper_args__ = {"polymorphic_on": type}
class B(A):
__mapper_args__ = {"polymorphic_identity": "b"}
with expect_warnings(
r"Mapper\[C\(a\)\] does not indicate a " "'polymorphic_identity',"
):
class C(A):
__mapper_args__ = {}
def test_load_from_middle(self):
C, B = self.classes.C, self.classes.B
s = fixture_session()
s.add(C())
o = s.query(B).first()
eq_(o.type, "c")
assert isinstance(o, C)
def test_load_from_base(self):
A, C = self.classes.A, self.classes.C
s = fixture_session()
s.add(C())
o = s.query(A).first()
eq_(o.type, "c")
assert isinstance(o, C)
def test_discriminator(self):
C, B, base = (self.classes.C, self.classes.B, self.tables.base)
assert class_mapper(B).polymorphic_on is base.c.type
assert class_mapper(C).polymorphic_on is base.c.type
def test_load_multiple_from_middle(self):
C, B, E, D, base = (
self.classes.C,
self.classes.B,
self.classes.E,
self.classes.D,
self.tables.base,
)
s = fixture_session()
s.add_all([C(), D(), E()])
eq_(s.query(B).order_by(base.c.type).all(), [C(), D()])
class DeleteOrphanTest(fixtures.MappedTest):
"""Test the fairly obvious, that an error is raised
when attempting to insert an orphan.
Previous SQLA versions would check this constraint
in memory which is the original rationale for this test.
"""
@classmethod
def define_tables(cls, metadata):
global single, parent
single = Table(
"single",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("type", String(50), nullable=False),
Column("data", String(50)),
Column(
"parent_id", Integer, ForeignKey("parent.id"), nullable=False
),
)
parent = Table(
"parent",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("data", String(50)),
)
def test_orphan_message(self):
class Base(fixtures.BasicEntity):
pass
class SubClass(Base):
pass
class Parent(fixtures.BasicEntity):
pass
self.mapper_registry.map_imperatively(
Base,
single,
polymorphic_on=single.c.type,
polymorphic_identity="base",
)
self.mapper_registry.map_imperatively(
SubClass, inherits=Base, polymorphic_identity="sub"
)
self.mapper_registry.map_imperatively(
Parent,
parent,
properties={
"related": relationship(Base, cascade="all, delete-orphan")
},
)
sess = fixture_session()
s1 = SubClass(data="s1")
sess.add(s1)
assert_raises(sa_exc.DBAPIError, sess.flush)
class PolymorphicUnionTest(fixtures.TestBase, testing.AssertsCompiledSQL):
__dialect__ = "default"
def _fixture(self):
t1 = table(
"t1",
column("c1", Integer),
column("c2", Integer),
column("c3", Integer),
)
t2 = table(
"t2",
column("c1", Integer),
column("c2", Integer),
column("c3", Integer),
column("c4", Integer),
)
t3 = table(
"t3",
column("c1", Integer),
column("c3", Integer),
column("c5", Integer),
)
return t1, t2, t3
def test_type_col_present(self):
t1, t2, t3 = self._fixture()
self.assert_compile(
polymorphic_union(
util.OrderedDict([("a", t1), ("b", t2), ("c", t3)]), "q1"
),
"SELECT t1.c1, t1.c2, t1.c3, CAST(NULL AS INTEGER) AS c4, "
"CAST(NULL AS INTEGER) AS c5, 'a' AS q1 FROM t1 UNION ALL "
"SELECT t2.c1, t2.c2, t2.c3, t2.c4, CAST(NULL AS INTEGER) AS c5, "
"'b' AS q1 FROM t2 UNION ALL SELECT t3.c1, "
"CAST(NULL AS INTEGER) AS c2, t3.c3, CAST(NULL AS INTEGER) AS c4, "
"t3.c5, 'c' AS q1 FROM t3",
)
def test_type_col_non_present(self):
t1, t2, t3 = self._fixture()
self.assert_compile(
polymorphic_union(
util.OrderedDict([("a", t1), ("b", t2), ("c", t3)]), None
),
"SELECT t1.c1, t1.c2, t1.c3, CAST(NULL AS INTEGER) AS c4, "
"CAST(NULL AS INTEGER) AS c5 FROM t1 UNION ALL SELECT t2.c1, "
"t2.c2, t2.c3, t2.c4, CAST(NULL AS INTEGER) AS c5 FROM t2 "
"UNION ALL SELECT t3.c1, CAST(NULL AS INTEGER) AS c2, t3.c3, "
"CAST(NULL AS INTEGER) AS c4, t3.c5 FROM t3",
)
def test_no_cast_null(self):
t1, t2, t3 = self._fixture()
self.assert_compile(
polymorphic_union(
util.OrderedDict([("a", t1), ("b", t2), ("c", t3)]),
"q1",
cast_nulls=False,
),
"SELECT t1.c1, t1.c2, t1.c3, NULL AS c4, NULL AS c5, 'a' AS q1 "
"FROM t1 UNION ALL SELECT t2.c1, t2.c2, t2.c3, t2.c4, NULL AS c5, "
"'b' AS q1 FROM t2 UNION ALL SELECT t3.c1, NULL AS c2, t3.c3, "
"NULL AS c4, t3.c5, 'c' AS q1 FROM t3",
)
class DiscriminatorOrPkNoneTest(fixtures.DeclarativeMappedTest):
run_setup_mappers = "once"
__dialect__ = "default"
@classmethod
def setup_classes(cls):
Base = cls.DeclarativeBasic
class Parent(fixtures.ComparableEntity, Base):
__tablename__ = "parent"
id = Column(Integer, primary_key=True)
class A(fixtures.ComparableEntity, Base):
__tablename__ = "a"
id = Column(Integer, primary_key=True)
parent_id = Column(ForeignKey("parent.id"))
type = Column(String(50))
__mapper_args__ = {
"polymorphic_on": type,
"polymorphic_identity": "a",
}
class B(A):
__tablename__ = "b"
id = Column(ForeignKey("a.id"), primary_key=True)
__mapper_args__ = {"polymorphic_identity": "b"}
@classmethod
def insert_data(cls, connection):
Parent, A, B = cls.classes("Parent", "A", "B")
with Session(connection) as s:
p1 = Parent(id=1)
p2 = Parent(id=2)
s.add_all([p1, p2])
s.flush()
s.add_all(
[
A(id=1, parent_id=1),
B(id=2, parent_id=1),
A(id=3, parent_id=1),
B(id=4, parent_id=1),
]
)
s.flush()
s.query(A).filter(A.id.in_([3, 4])).update(
{A.type: None}, synchronize_session=False
)
s.commit()
def test_pk_is_null(self):
Parent, A = self.classes("Parent", "A")
sess = fixture_session()
q = (
sess.query(Parent, A)
.select_from(Parent)
.outerjoin(A)
.filter(Parent.id == 2)
)
row = q.all()[0]
eq_(row, (Parent(id=2), None))
def test_pk_not_null_discriminator_null_from_base(self):
(A,) = self.classes("A")
sess = fixture_session()
q = sess.query(A).filter(A.id == 3)
assert_raises_message(
sa_exc.InvalidRequestError,
r"Row with identity key \(<class '.*A'>, \(3,\), None\) can't be "
"loaded into an object; the polymorphic discriminator "
"column 'a.type' is NULL",
q.all,
)
def test_pk_not_null_discriminator_null_from_sub(self):
(B,) = self.classes("B")
sess = fixture_session()
q = sess.query(B).filter(B.id == 4)
assert_raises_message(
sa_exc.InvalidRequestError,
r"Row with identity key \(<class '.*A'>, \(4,\), None\) can't be "
"loaded into an object; the polymorphic discriminator "
"column 'a.type' is NULL",
q.all,
)
class UnexpectedPolymorphicIdentityTest(fixtures.DeclarativeMappedTest):
run_setup_mappers = "once"
__dialect__ = "default"
@classmethod
def setup_classes(cls):
Base = cls.DeclarativeBasic
class AJoined(fixtures.ComparableEntity, Base):
__tablename__ = "ajoined"
id = Column(Integer, primary_key=True)
type = Column(String(10), nullable=False)
__mapper_args__ = {
"polymorphic_on": type,
"polymorphic_identity": "a",
}
class AJoinedSubA(AJoined):
__tablename__ = "ajoinedsuba"
id = Column(ForeignKey("ajoined.id"), primary_key=True)
__mapper_args__ = {"polymorphic_identity": "suba"}
class AJoinedSubB(AJoined):
__tablename__ = "ajoinedsubb"
id = Column(ForeignKey("ajoined.id"), primary_key=True)
__mapper_args__ = {"polymorphic_identity": "subb"}
class ASingle(fixtures.ComparableEntity, Base):
__tablename__ = "asingle"
id = Column(Integer, primary_key=True)
type = Column(String(10), nullable=False)
__mapper_args__ = {
"polymorphic_on": type,
"polymorphic_identity": "a",
}
class ASingleSubA(ASingle):
__mapper_args__ = {"polymorphic_identity": "suba"}
class ASingleSubB(ASingle):
__mapper_args__ = {"polymorphic_identity": "subb"}
@classmethod
def insert_data(cls, connection):
ASingleSubA, ASingleSubB, AJoinedSubA, AJoinedSubB = cls.classes(
"ASingleSubA", "ASingleSubB", "AJoinedSubA", "AJoinedSubB"
)
with Session(connection) as s:
s.add_all(
[ASingleSubA(), ASingleSubB(), AJoinedSubA(), AJoinedSubB()]
)
s.commit()
def test_single_invalid_ident(self):
ASingle, ASingleSubA = self.classes("ASingle", "ASingleSubA")
s = fixture_session()
q = s.query(ASingleSubA).from_statement(select(ASingle))
assert_raises_message(
sa_exc.InvalidRequestError,
r"Row with identity key \(.*ASingle.*\) can't be loaded into an "
r"object; the polymorphic discriminator column '.*.type' refers "
r"to Mapper\[ASingleSubB\(asingle\)\], which is not a "
r"sub-mapper of the requested "
r"Mapper\[ASingleSubA\(asingle\)\]",
q.all,
)
def test_joined_invalid_ident(self):
AJoined, AJoinedSubA = self.classes("AJoined", "AJoinedSubA")
s = fixture_session()
q = s.query(AJoinedSubA).from_statement(select(AJoined))
assert_raises_message(
sa_exc.InvalidRequestError,
r"Row with identity key \(.*AJoined.*\) can't be loaded into an "
r"object; the polymorphic discriminator column '.*.type' refers "
r"to Mapper\[AJoinedSubB\(ajoinedsubb\)\], which is "
"not a "
r"sub-mapper of the requested "
r"Mapper\[AJoinedSubA\(ajoinedsuba\)\]",
q.all,
)
class CompositeJoinedInTest(fixtures.DeclarativeMappedTest):
"""test #9164"""
run_setup_mappers = "once"
__dialect__ = "default"
@classmethod
def setup_classes(cls):
Base = cls.DeclarativeBasic
class A(fixtures.ComparableEntity, Base):
__tablename__ = "table_a"
order_id: Mapped[str] = mapped_column(String(50), primary_key=True)
_sku: Mapped[str] = mapped_column(String(50), primary_key=True)
__mapper_args__ = {
"polymorphic_identity": "a",
"polymorphic_on": "type",
}
type: Mapped[str]
def __init__(self, order_id: str, sku: str):
self.order_id = order_id
self._sku = sku
class B(A):
__tablename__ = "table_b"
_increment_id: Mapped[str] = mapped_column(
String(50), primary_key=True
)
_sku: Mapped[str] = mapped_column(String(50), primary_key=True)
__table_args__ = (
ForeignKeyConstraint(
["_increment_id", "_sku"],
["table_a.order_id", "table_a._sku"],
),
)
__mapper_args__ = {"polymorphic_identity": "b"}
def test_round_trip(self):
B = self.classes.B
sess = fixture_session()
b1 = B(order_id="iid1", sku="sku1")
sess.add(b1)
sess.commit()
eq_(sess.scalar(select(B)), b1)
class NameConflictTest(fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
Table(
"content",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("type", String(30)),
)
Table(
"foo",
metadata,
Column("id", Integer, ForeignKey("content.id"), primary_key=True),
Column("content_type", String(30)),
)
def test_name_conflict(self):
class Content:
pass
class Foo(Content):
pass
self.mapper_registry.map_imperatively(
Content,
self.tables.content,
polymorphic_on=self.tables.content.c.type,
)
self.mapper_registry.map_imperatively(
Foo, self.tables.foo, inherits=Content, polymorphic_identity="foo"
)
sess = fixture_session()
f = Foo()
f.content_type = "bar"
sess.add(f)
sess.flush()
f_id = f.id
sess.expunge_all()
assert sess.get(Content, f_id).content_type == "bar"
|