summaryrefslogtreecommitdiff
path: root/test/orm/declarative/test_mixin.py
blob: 380abc4e906a499af6b61a9786ec674abd56db31 (plain)
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
from operator import is_not

from typing_extensions import Annotated

import sqlalchemy as sa
from sqlalchemy import ForeignKey
from sqlalchemy import func
from sqlalchemy import Integer
from sqlalchemy import MetaData
from sqlalchemy import select
from sqlalchemy import String
from sqlalchemy import testing
from sqlalchemy.orm import base as orm_base
from sqlalchemy.orm import class_mapper
from sqlalchemy.orm import clear_mappers
from sqlalchemy.orm import close_all_sessions
from sqlalchemy.orm import column_property
from sqlalchemy.orm import configure_mappers
from sqlalchemy.orm import declarative_base
from sqlalchemy.orm import declarative_mixin
from sqlalchemy.orm import DeclarativeBase
from sqlalchemy.orm import declared_attr
from sqlalchemy.orm import deferred
from sqlalchemy.orm import events as orm_events
from sqlalchemy.orm import has_inherited_table
from sqlalchemy.orm import Mapped
from sqlalchemy.orm import registry
from sqlalchemy.orm import relationship
from sqlalchemy.orm import synonym
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 is_true
from sqlalchemy.testing import mock
from sqlalchemy.testing.fixtures import fixture_session
from sqlalchemy.testing.schema import Column
from sqlalchemy.testing.schema import mapped_column
from sqlalchemy.testing.schema import Table
from sqlalchemy.testing.util import gc_collect
from sqlalchemy.util import classproperty

Base = None
mapper_registry = None


class DeclarativeTestBase(
    testing.AssertsCompiledSQL,
    fixtures.TestBase,
    testing.AssertsExecutionResults,
):
    def setup_test(self):
        global Base, mapper_registry

        mapper_registry = registry(metadata=MetaData())

        class Base(DeclarativeBase):
            registry = mapper_registry

    def teardown_test(self):
        close_all_sessions()
        clear_mappers()
        with testing.db.begin() as conn:
            Base.metadata.drop_all(conn)


class DeclarativeMixinTest(DeclarativeTestBase):
    @testing.combinations("generate_base", "subclass", argnames="base_type")
    def test_init_subclass_works(self, registry, base_type):
        reg = registry
        if base_type == "generate_base":

            class Base:
                def __init_subclass__(cls):
                    cls.id = Column(Integer, primary_key=True)

            Base = registry.generate_base(cls=Base)
        elif base_type == "subclass":

            class Base(DeclarativeBase):
                registry = reg

                def __init_subclass__(cls):
                    cls.id = Column(Integer, primary_key=True)
                    # hmmm what do we think of this.  if DeclarativeBase
                    # used a full metaclass approach we wouldn't need this.
                    super().__init_subclass__()

        else:
            assert False

        class Foo(Base):
            __tablename__ = "foo"
            name = Column(String)

        self.assert_compile(select(Foo), "SELECT foo.name, foo.id FROM foo")

    def test_simple_wbase(self):
        class MyMixin:

            id = Column(
                Integer, primary_key=True, test_needs_autoincrement=True
            )

            def foo(self):
                return "bar" + str(self.id)

        class MyModel(Base, MyMixin):

            __tablename__ = "test"
            name = Column(String(100), nullable=False, index=True)

        Base.metadata.create_all(testing.db)
        session = fixture_session()
        session.add(MyModel(name="testing"))
        session.flush()
        session.expunge_all()
        obj = session.query(MyModel).one()
        eq_(obj.id, 1)
        eq_(obj.name, "testing")
        eq_(obj.foo(), "bar1")

    def test_simple_wdecorator(self):
        class MyMixin:

            id = Column(
                Integer, primary_key=True, test_needs_autoincrement=True
            )

            def foo(self):
                return "bar" + str(self.id)

        @mapper_registry.mapped
        class MyModel(MyMixin):

            __tablename__ = "test"
            name = Column(String(100), nullable=False, index=True)

        Base.metadata.create_all(testing.db)
        session = fixture_session()
        session.add(MyModel(name="testing"))
        session.flush()
        session.expunge_all()
        obj = session.query(MyModel).one()
        eq_(obj.id, 1)
        eq_(obj.name, "testing")
        eq_(obj.foo(), "bar1")

    def test_declarative_mixin_decorator(self):
        @declarative_mixin
        class MyMixin:

            id = Column(
                Integer, primary_key=True, test_needs_autoincrement=True
            )

            def foo(self):
                return "bar" + str(self.id)

        @mapper_registry.mapped
        class MyModel(MyMixin):

            __tablename__ = "test"
            name = Column(String(100), nullable=False, index=True)

        Base.metadata.create_all(testing.db)
        session = fixture_session()
        session.add(MyModel(name="testing"))
        session.flush()
        session.expunge_all()
        obj = session.query(MyModel).one()
        eq_(obj.id, 1)
        eq_(obj.name, "testing")
        eq_(obj.foo(), "bar1")

    @testing.combinations(Column, mapped_column, argnames="_column")
    def test_unique_column(self, _column):
        class MyMixin:

            id = _column(Integer, primary_key=True)
            value = _column(String, unique=True)

        class MyModel(Base, MyMixin):

            __tablename__ = "test"

        assert MyModel.__table__.c.value.unique

    @testing.combinations(Column, mapped_column, argnames="_column")
    def test_hierarchical_bases_wbase(self, _column):
        class MyMixinParent:

            id = _column(
                Integer, primary_key=True, test_needs_autoincrement=True
            )

            def foo(self):
                return "bar" + str(self.id)

        class MyMixin(MyMixinParent):

            baz = _column(String(100), nullable=False, index=True)

        class MyModel(Base, MyMixin):

            __tablename__ = "test"
            name = _column(String(100), nullable=False, index=True)

        Base.metadata.create_all(testing.db)
        session = fixture_session()
        session.add(MyModel(name="testing", baz="fu"))
        session.flush()
        session.expunge_all()
        obj = session.query(MyModel).one()
        eq_(obj.id, 1)
        eq_(obj.name, "testing")
        eq_(obj.foo(), "bar1")
        eq_(obj.baz, "fu")

    @testing.combinations(Column, mapped_column, argnames="_column")
    def test_hierarchical_bases_wdecorator(self, _column):
        class MyMixinParent:

            id = _column(
                Integer, primary_key=True, test_needs_autoincrement=True
            )

            def foo(self):
                return "bar" + str(self.id)

        class MyMixin(MyMixinParent):

            baz = _column(String(100), nullable=False, index=True)

        @mapper_registry.mapped
        class MyModel(MyMixin):

            __tablename__ = "test"
            name = Column(String(100), nullable=False, index=True)

        Base.metadata.create_all(testing.db)
        session = fixture_session()
        session.add(MyModel(name="testing", baz="fu"))
        session.flush()
        session.expunge_all()
        obj = session.query(MyModel).one()
        eq_(obj.id, 1)
        eq_(obj.name, "testing")
        eq_(obj.foo(), "bar1")
        eq_(obj.baz, "fu")

    @testing.combinations(Column, mapped_column, argnames="_column")
    def test_mixin_overrides_wbase(self, _column):
        """test a mixin that overrides a column on a superclass."""

        class MixinA:
            foo = _column(String(50))

        class MixinB(MixinA):
            foo = _column(Integer)

        class MyModelA(Base, MixinA):
            __tablename__ = "testa"
            id = _column(Integer, primary_key=True)

        class MyModelB(Base, MixinB):
            __tablename__ = "testb"
            id = _column(Integer, primary_key=True)

        eq_(MyModelA.__table__.c.foo.type.__class__, String)
        eq_(MyModelB.__table__.c.foo.type.__class__, Integer)

    def test_mixin_overrides_wdecorator(self):
        """test a mixin that overrides a column on a superclass."""

        class MixinA:
            foo = Column(String(50))

        class MixinB(MixinA):
            foo = Column(Integer)

        @mapper_registry.mapped
        class MyModelA(MixinA):
            __tablename__ = "testa"
            id = Column(Integer, primary_key=True)

        @mapper_registry.mapped
        class MyModelB(MixinB):
            __tablename__ = "testb"
            id = Column(Integer, primary_key=True)

        eq_(MyModelA.__table__.c.foo.type.__class__, String)
        eq_(MyModelB.__table__.c.foo.type.__class__, Integer)

    def test_same_base_multiple_times(self):
        class User(Base):
            __tablename__ = "user"

            id = Column(Integer, primary_key=True)
            name = Column(String)
            surname = Column(String)

        class SpecialUser(User):
            __abstract__ = True

        class ConvenienceStuff(User):
            __abstract__ = True

            def fullname(self):
                return self.name + " " + self.surname

        class Manager(SpecialUser, ConvenienceStuff, User):
            __tablename__ = "manager"

            id = Column(Integer, ForeignKey("user.id"), primary_key=True)
            title = Column(String)

        eq_(Manager.__table__.name, "manager")

    def test_same_base_multiple_metadata(self):
        m1 = MetaData()
        m2 = MetaData()

        class B1(Base):
            __abstract__ = True
            metadata = m1

        class B2(Base):
            __abstract__ = True
            metadata = m2

            def fullname(self):
                return self.name + " " + self.surname

        class User(B1):
            __tablename__ = "user"

            id = Column(Integer, primary_key=True)
            name = Column(String)
            surname = Column(String)

        class AD(B1):
            __tablename__ = "address"

            id = Column(Integer, primary_key=True)

        class OtherUser(B2):
            __tablename__ = "user"

            id = Column(Integer, primary_key=True)
            username = Column(String)

        class BUser(Base):
            __tablename__ = "user"

            id = Column(Integer, primary_key=True)
            login = Column(String)

        eq_(set(m1.tables), {"user", "address"})
        eq_(set(m2.tables), {"user"})
        eq_(set(Base.registry.metadata.tables), {"user"})

        eq_(Base.registry.metadata.tables["user"].c.keys(), ["id", "login"])
        eq_(m1.tables["user"].c.keys(), ["id", "name", "surname"])
        eq_(m2.tables["user"].c.keys(), ["id", "username"])

    def test_same_registry_multiple_metadata(self):
        m1 = MetaData()
        m2 = MetaData()

        reg = registry()

        class B1:
            metadata = m1

        class B2:
            metadata = m2

            def fullname(self):
                return self.name + " " + self.surname

        @reg.mapped
        class User(B1):
            __tablename__ = "user"

            id = Column(Integer, primary_key=True)
            name = Column(String)
            surname = Column(String)

        @reg.mapped
        class AD(B1):
            __tablename__ = "address"

            id = Column(Integer, primary_key=True)

        @reg.mapped
        class OtherUser(B2):
            __tablename__ = "user"

            id = Column(Integer, primary_key=True)
            username = Column(String)

        @reg.mapped
        class BUser:
            __tablename__ = "user"

            id = Column(Integer, primary_key=True)
            login = Column(String)

        eq_(set(m1.tables), {"user", "address"})
        eq_(set(m2.tables), {"user"})
        eq_(set(reg.metadata.tables), {"user"})

        eq_(reg.metadata.tables["user"].c.keys(), ["id", "login"])
        eq_(m1.tables["user"].c.keys(), ["id", "name", "surname"])
        eq_(m2.tables["user"].c.keys(), ["id", "username"])

    @testing.combinations(Column, mapped_column, argnames="_column")
    @testing.combinations("strname", "colref", "objref", argnames="fk_type")
    def test_fk_mixin(self, decl_base, fk_type, _column):
        class Bar(decl_base):
            __tablename__ = "bar"

            id = _column(Integer, primary_key=True)

        if fk_type == "strname":
            fk = ForeignKey("bar.id")
        elif fk_type == "colref":
            fk = ForeignKey(Bar.__table__.c.id)
        elif fk_type == "objref":
            fk = ForeignKey(Bar.id)
        else:
            assert False

        class MyMixin:
            foo = _column(Integer, fk)

        class A(MyMixin, decl_base):
            __tablename__ = "a"

            id = _column(Integer, primary_key=True)

        class B(MyMixin, decl_base):
            __tablename__ = "b"

            id = _column(Integer, primary_key=True)

        is_true(A.__table__.c.foo.references(Bar.__table__.c.id))
        is_true(B.__table__.c.foo.references(Bar.__table__.c.id))

        fka = list(A.__table__.c.foo.foreign_keys)[0]
        fkb = list(A.__table__.c.foo.foreign_keys)[0]
        is_not(fka, fkb)

    @testing.combinations(Column, mapped_column, argnames="_column")
    def test_fk_mixin_self_referential_error(self, decl_base, _column):
        class MyMixin:
            id = _column(Integer, primary_key=True)
            foo = _column(Integer, ForeignKey(id))

        with expect_raises_message(
            sa.exc.InvalidRequestError,
            "Columns with foreign keys to non-table-bound columns "
            "must be declared as @declared_attr",
        ):

            class A(MyMixin, decl_base):
                __tablename__ = "a"

    @testing.combinations(Column, mapped_column, argnames="_column")
    def test_fk_mixin_self_referential_declared_attr(self, decl_base, _column):
        class MyMixin:
            id = _column(Integer, primary_key=True)

            @declared_attr
            def foo(cls):
                return _column(Integer, ForeignKey(cls.id))

        class A(MyMixin, decl_base):
            __tablename__ = "a"

        class B(MyMixin, decl_base):
            __tablename__ = "b"

        is_true(A.__table__.c.foo.references(A.__table__.c.id))
        is_true(B.__table__.c.foo.references(B.__table__.c.id))

        fka = list(A.__table__.c.foo.foreign_keys)[0]
        fkb = list(A.__table__.c.foo.foreign_keys)[0]
        is_not(fka, fkb)

        is_true(A.__table__.c.foo.references(A.__table__.c.id))
        is_true(B.__table__.c.foo.references(B.__table__.c.id))

        fka = list(A.__table__.c.foo.foreign_keys)[0]
        fkb = list(A.__table__.c.foo.foreign_keys)[0]
        is_not(fka, fkb)

    def test_not_allowed(self):
        class MyRelMixin:
            foo = relationship("Bar")

        def go():
            class MyModel(Base, MyRelMixin):

                __tablename__ = "foo"

        assert_raises(sa.exc.InvalidRequestError, go)

        class MyDefMixin:
            foo = deferred(Column("foo", String))

        def go():
            class MyModel(Base, MyDefMixin):
                __tablename__ = "foo"

        assert_raises(sa.exc.InvalidRequestError, go)

        class MyCPropMixin:
            foo = column_property(Column("foo", String))

        def go():
            class MyModel(Base, MyCPropMixin):
                __tablename__ = "foo"

        assert_raises(sa.exc.InvalidRequestError, go)

    def test_table_name_inherited(self):
        class MyMixin:
            @declared_attr
            def __tablename__(cls):
                return cls.__name__.lower()

            id = Column(Integer, primary_key=True)

        class MyModel(Base, MyMixin):
            pass

        eq_(MyModel.__table__.name, "mymodel")

    def test_classproperty_still_works(self):
        class MyMixin:
            @classproperty
            def __tablename__(cls):
                return cls.__name__.lower()

            id = Column(Integer, primary_key=True)

        class MyModel(Base, MyMixin):
            __tablename__ = "overridden"

        eq_(MyModel.__table__.name, "overridden")

    def test_table_name_not_inherited(self):
        class MyMixin:
            @declared_attr
            def __tablename__(cls):
                return cls.__name__.lower()

            id = Column(Integer, primary_key=True)

        class MyModel(Base, MyMixin):
            __tablename__ = "overridden"

        eq_(MyModel.__table__.name, "overridden")

    def test_table_name_inheritance_order(self):
        class MyMixin1:
            @declared_attr
            def __tablename__(cls):
                return cls.__name__.lower() + "1"

        class MyMixin2:
            @declared_attr
            def __tablename__(cls):
                return cls.__name__.lower() + "2"

        class MyModel(Base, MyMixin1, MyMixin2):
            id = Column(Integer, primary_key=True)

        eq_(MyModel.__table__.name, "mymodel1")

    def test_table_name_dependent_on_subclass(self):
        class MyHistoryMixin:
            @declared_attr
            def __tablename__(cls):
                return cls.parent_name + "_changelog"

        class MyModel(Base, MyHistoryMixin):
            parent_name = "foo"
            id = Column(Integer, primary_key=True)

        eq_(MyModel.__table__.name, "foo_changelog")

    def test_table_args_inherited(self):
        class MyMixin:
            __table_args__ = {"mysql_engine": "InnoDB"}

        class MyModel(Base, MyMixin):
            __tablename__ = "test"
            id = Column(Integer, primary_key=True)

        eq_(MyModel.__table__.kwargs, {"mysql_engine": "InnoDB"})

    def test_table_args_inherited_descriptor(self):
        class MyMixin:
            @declared_attr
            def __table_args__(cls):
                return {"info": cls.__name__}

        class MyModel(Base, MyMixin):
            __tablename__ = "test"
            id = Column(Integer, primary_key=True)

        eq_(MyModel.__table__.info, "MyModel")

    def test_table_args_inherited_single_table_inheritance(self):
        class MyMixin:
            __table_args__ = {"mysql_engine": "InnoDB"}

        class General(Base, MyMixin):
            __tablename__ = "test"
            id = Column(Integer, primary_key=True)
            type_ = Column(String(50))
            __mapper__args = {"polymorphic_on": type_}

        class Specific(General):
            __mapper_args__ = {"polymorphic_identity": "specific"}

        assert Specific.__table__ is General.__table__
        eq_(General.__table__.kwargs, {"mysql_engine": "InnoDB"})

    def test_columns_single_table_inheritance(self):
        """Test a column on a mixin with an alternate attribute name,
        mapped to a superclass and single-table inheritance subclass.
        The superclass table gets the column, the subclass shares
        the MapperProperty.

        """

        class MyMixin:
            foo = Column("foo", Integer)
            bar = Column("bar_newname", Integer)

        class General(Base, MyMixin):
            __tablename__ = "test"
            id = Column(Integer, primary_key=True)
            type_ = Column(String(50))
            __mapper__args = {"polymorphic_on": type_}

        class Specific(General):
            __mapper_args__ = {"polymorphic_identity": "specific"}

        assert General.bar.prop.columns[0] is General.__table__.c.bar_newname
        assert len(General.bar.prop.columns) == 1
        assert Specific.bar.prop is General.bar.prop

    @testing.skip_if(
        lambda: testing.against("oracle"),
        "Test has an empty insert in it at the moment",
    )
    @testing.combinations(Column, mapped_column, argnames="_column")
    def test_columns_single_inheritance_conflict_resolution(self, _column):
        """Test that a declared_attr can return the existing column and it will
        be ignored.  this allows conditional columns to be added.

        See [ticket:2472].

        """

        class Person(Base):
            __tablename__ = "person"
            id = _column(Integer, primary_key=True)

        class Mixin:
            @declared_attr
            def target_id(cls):
                return cls.__table__.c.get(
                    "target_id", _column(Integer, ForeignKey("other.id"))
                )

            @declared_attr
            def target(cls):
                return relationship("Other")

        class Engineer(Mixin, Person):

            """single table inheritance"""

        class Manager(Mixin, Person):

            """single table inheritance"""

        class Other(Base):
            __tablename__ = "other"
            id = _column(Integer, primary_key=True)

        is_(
            Engineer.target_id.property.columns[0],
            Person.__table__.c.target_id,
        )
        is_(
            Manager.target_id.property.columns[0], Person.__table__.c.target_id
        )
        # do a brief round trip on this
        Base.metadata.create_all(testing.db)
        session = fixture_session()
        o1, o2 = Other(), Other()
        session.add_all(
            [Engineer(target=o1), Manager(target=o2), Manager(target=o1)]
        )
        session.commit()
        eq_(session.query(Engineer).first().target, o1)

    @testing.combinations(Column, mapped_column, argnames="_column")
    def test_columns_joined_table_inheritance(self, _column):
        """Test a column on a mixin with an alternate attribute name,
        mapped to a superclass and joined-table inheritance subclass.
        Both tables get the column, in the case of the subclass the two
        columns are joined under one MapperProperty.

        """

        class MyMixin:
            foo = _column("foo", Integer)
            bar = _column("bar_newname", Integer)

        class General(Base, MyMixin):
            __tablename__ = "test"
            id = _column(Integer, primary_key=True)
            type_ = _column(String(50))
            __mapper_args__ = {"polymorphic_on": type_}

        class Specific(General):
            __tablename__ = "sub"
            id = _column(Integer, ForeignKey("test.id"), primary_key=True)
            __mapper_args__ = {"polymorphic_identity": "specific"}

        assert General.bar.prop.columns[0] is General.__table__.c.bar_newname
        assert len(General.bar.prop.columns) == 1
        assert Specific.bar.prop is General.bar.prop
        eq_(len(Specific.bar.prop.columns), 1)
        assert Specific.bar.prop.columns[0] is General.__table__.c.bar_newname

    def test_column_join_checks_superclass_type(self):
        """Test that the logic which joins subclass props to those
        of the superclass checks that the superclass property is a column.

        """

        class General(Base):
            __tablename__ = "test"
            id = Column(Integer, primary_key=True)
            general_id = Column(Integer, ForeignKey("test.id"))
            type_ = relationship("General")

        class Specific(General):
            __tablename__ = "sub"
            id = Column(Integer, ForeignKey("test.id"), primary_key=True)
            type_ = Column("foob", String(50))

        assert isinstance(General.type_.property, sa.orm.RelationshipProperty)
        assert Specific.type_.property.columns[0] is Specific.__table__.c.foob

    def test_column_join_checks_subclass_type(self):
        """Test that the logic which joins subclass props to those
        of the superclass checks that the subclass property is a column.

        """

        def go():
            class General(Base):
                __tablename__ = "test"
                id = Column(Integer, primary_key=True)
                type_ = Column("foob", Integer)

            class Specific(General):
                __tablename__ = "sub"
                id = Column(Integer, ForeignKey("test.id"), primary_key=True)
                specific_id = Column(Integer, ForeignKey("sub.id"))
                type_ = relationship("Specific")

        assert_raises_message(
            sa.exc.ArgumentError, "column 'foob' conflicts with property", go
        )

    def test_table_args_overridden(self):
        class MyMixin:
            __table_args__ = {"mysql_engine": "Foo"}

        class MyModel(Base, MyMixin):
            __tablename__ = "test"
            __table_args__ = {"mysql_engine": "InnoDB"}
            id = Column(Integer, primary_key=True)

        eq_(MyModel.__table__.kwargs, {"mysql_engine": "InnoDB"})

    @testing.teardown_events(orm_events.MapperEvents)
    def test_declare_first_mixin(self):
        canary = mock.Mock()

        class MyMixin:
            @classmethod
            def __declare_first__(cls):
                canary.declare_first__(cls)

            @classmethod
            def __declare_last__(cls):
                canary.declare_last__(cls)

        class MyModel(Base, MyMixin):
            __tablename__ = "test"
            id = Column(Integer, primary_key=True)

        configure_mappers()

        eq_(
            canary.mock_calls,
            [
                mock.call.declare_first__(MyModel),
                mock.call.declare_last__(MyModel),
            ],
        )

    @testing.teardown_events(orm_events.MapperEvents)
    def test_declare_first_base(self):
        canary = mock.Mock()

        class MyMixin:
            @classmethod
            def __declare_first__(cls):
                canary.declare_first__(cls)

            @classmethod
            def __declare_last__(cls):
                canary.declare_last__(cls)

        class Base(MyMixin):
            pass

        Base = declarative_base(cls=Base)

        class MyModel(Base):
            __tablename__ = "test"
            id = Column(Integer, primary_key=True)

        configure_mappers()

        eq_(
            canary.mock_calls,
            [
                mock.call.declare_first__(MyModel),
                mock.call.declare_last__(MyModel),
            ],
        )

    @testing.teardown_events(orm_events.MapperEvents)
    def test_declare_first_direct(self):
        canary = mock.Mock()

        class MyOtherModel(Base):
            __tablename__ = "test2"
            id = Column(Integer, primary_key=True)

            @classmethod
            def __declare_first__(cls):
                canary.declare_first__(cls)

            @classmethod
            def __declare_last__(cls):
                canary.declare_last__(cls)

        configure_mappers()

        eq_(
            canary.mock_calls,
            [
                mock.call.declare_first__(MyOtherModel),
                mock.call.declare_last__(MyOtherModel),
            ],
        )

    def test_mapper_args_declared_attr(self):
        class ComputedMapperArgs:
            @declared_attr
            def __mapper_args__(cls):
                if cls.__name__ == "Person":
                    return {"polymorphic_on": cls.discriminator}
                else:
                    return {"polymorphic_identity": cls.__name__}

        class Person(Base, ComputedMapperArgs):
            __tablename__ = "people"
            id = Column(Integer, primary_key=True)
            discriminator = Column("type", String(50))

        class Engineer(Person):
            pass

        configure_mappers()
        assert class_mapper(Person).polymorphic_on is Person.__table__.c.type
        eq_(class_mapper(Engineer).polymorphic_identity, "Engineer")

    def test_mapper_args_declared_attr_two(self):

        # same as test_mapper_args_declared_attr, but we repeat
        # ComputedMapperArgs on both classes for no apparent reason.

        class ComputedMapperArgs:
            @declared_attr
            def __mapper_args__(cls):
                if cls.__name__ == "Person":
                    return {"polymorphic_on": cls.discriminator}
                else:
                    return {"polymorphic_identity": cls.__name__}

        class Person(Base, ComputedMapperArgs):

            __tablename__ = "people"
            id = Column(Integer, primary_key=True)
            discriminator = Column("type", String(50))

        class Engineer(Person, ComputedMapperArgs):
            pass

        configure_mappers()
        assert class_mapper(Person).polymorphic_on is Person.__table__.c.type
        eq_(class_mapper(Engineer).polymorphic_identity, "Engineer")

    def test_table_args_composite(self):
        class MyMixin1:

            __table_args__ = {"info": {"baz": "bob"}}

        class MyMixin2:

            __table_args__ = {"info": {"foo": "bar"}}

        class MyModel(Base, MyMixin1, MyMixin2):

            __tablename__ = "test"

            @declared_attr
            def __table_args__(self):
                info = {}
                args = dict(info=info)
                info.update(MyMixin1.__table_args__["info"])
                info.update(MyMixin2.__table_args__["info"])
                return args

            id = Column(Integer, primary_key=True)

        eq_(MyModel.__table__.info, {"foo": "bar", "baz": "bob"})

    def test_mapper_args_inherited(self):
        class MyMixin:

            __mapper_args__ = {"always_refresh": True}

        class MyModel(Base, MyMixin):

            __tablename__ = "test"
            id = Column(Integer, primary_key=True)

        eq_(MyModel.__mapper__.always_refresh, True)

    def test_mapper_args_inherited_descriptor(self):
        class MyMixin:
            @declared_attr
            def __mapper_args__(cls):

                # tenuous, but illustrates the problem!

                if cls.__name__ == "MyModel":
                    return dict(always_refresh=True)
                else:
                    return dict(always_refresh=False)

        class MyModel(Base, MyMixin):

            __tablename__ = "test"
            id = Column(Integer, primary_key=True)

        eq_(MyModel.__mapper__.always_refresh, True)

    def test_mapper_args_polymorphic_on_inherited(self):
        class MyMixin:

            type_ = Column(String(50))
            __mapper_args__ = {"polymorphic_on": type_}

        class MyModel(Base, MyMixin):

            __tablename__ = "test"
            id = Column(Integer, primary_key=True)

        col = MyModel.__mapper__.polymorphic_on
        eq_(col.name, "type_")
        assert col.table is not None

    def test_mapper_args_overridden(self):
        class MyMixin:

            __mapper_args__ = dict(always_refresh=True)

        class MyModel(Base, MyMixin):

            __tablename__ = "test"
            __mapper_args__ = dict(always_refresh=False)
            id = Column(Integer, primary_key=True)

        eq_(MyModel.__mapper__.always_refresh, False)

    def test_mapper_args_composite(self):
        class MyMixin1:

            type_ = Column(String(50))
            __mapper_args__ = {"polymorphic_on": type_}

        class MyMixin2:

            __mapper_args__ = {"always_refresh": True}

        class MyModel(Base, MyMixin1, MyMixin2):

            __tablename__ = "test"

            @declared_attr
            def __mapper_args__(cls):
                args = {}
                args.update(MyMixin1.__mapper_args__)
                args.update(MyMixin2.__mapper_args__)
                if cls.__name__ != "MyModel":
                    args.pop("polymorphic_on")
                    args["polymorphic_identity"] = cls.__name__

                return args

            id = Column(Integer, primary_key=True)

        class MySubModel(MyModel):
            pass

        eq_(MyModel.__mapper__.polymorphic_on.name, "type_")
        assert MyModel.__mapper__.polymorphic_on.table is not None
        eq_(MyModel.__mapper__.always_refresh, True)
        eq_(MySubModel.__mapper__.always_refresh, True)
        eq_(MySubModel.__mapper__.polymorphic_identity, "MySubModel")

    def test_mapper_args_property(self):
        class MyModel(Base):
            @declared_attr
            def __tablename__(cls):
                return cls.__name__.lower()

            @declared_attr
            def __table_args__(cls):
                return {"mysql_engine": "InnoDB"}

            @declared_attr
            def __mapper_args__(cls):
                args = {}
                args["polymorphic_identity"] = cls.__name__
                return args

            id = Column(Integer, primary_key=True)

        class MySubModel(MyModel):
            id = Column(Integer, ForeignKey("mymodel.id"), primary_key=True)

        class MySubModel2(MyModel):
            __tablename__ = "sometable"
            id = Column(Integer, ForeignKey("mymodel.id"), primary_key=True)

        eq_(MyModel.__mapper__.polymorphic_identity, "MyModel")
        eq_(MySubModel.__mapper__.polymorphic_identity, "MySubModel")
        eq_(MyModel.__table__.kwargs["mysql_engine"], "InnoDB")
        eq_(MySubModel.__table__.kwargs["mysql_engine"], "InnoDB")
        eq_(MySubModel2.__table__.kwargs["mysql_engine"], "InnoDB")
        eq_(MyModel.__table__.name, "mymodel")
        eq_(MySubModel.__table__.name, "mysubmodel")

    def test_mapper_args_custom_base(self):
        """test the @declared_attr approach from a custom base."""

        class Base:
            @declared_attr
            def __tablename__(cls):
                return cls.__name__.lower()

            @declared_attr
            def __table_args__(cls):
                return {"mysql_engine": "InnoDB"}

            @declared_attr
            def id(self):
                return Column(Integer, primary_key=True)

        Base = declarative_base(cls=Base)

        class MyClass(Base):
            pass

        class MyOtherClass(Base):
            pass

        eq_(MyClass.__table__.kwargs["mysql_engine"], "InnoDB")
        eq_(MyClass.__table__.name, "myclass")
        eq_(MyOtherClass.__table__.name, "myotherclass")
        assert MyClass.__table__.c.id.table is MyClass.__table__
        assert MyOtherClass.__table__.c.id.table is MyOtherClass.__table__

    def test_single_table_no_propagation(self):
        class IdColumn:

            id = Column(Integer, primary_key=True)

        class Generic(Base, IdColumn):

            __tablename__ = "base"
            discriminator = Column("type", String(50))
            __mapper_args__ = dict(polymorphic_on=discriminator)
            value = Column(Integer())

        class Specific(Generic):

            __mapper_args__ = dict(polymorphic_identity="specific")

        assert Specific.__table__ is Generic.__table__
        eq_(list(Generic.__table__.c.keys()), ["type", "value", "id"])
        assert (
            class_mapper(Specific).polymorphic_on is Generic.__table__.c.type
        )
        eq_(class_mapper(Specific).polymorphic_identity, "specific")

    def test_joined_table_propagation(self):
        class CommonMixin:
            @declared_attr
            def __tablename__(cls):
                return cls.__name__.lower()

            __table_args__ = {"mysql_engine": "InnoDB"}
            timestamp = mapped_column(Integer)
            id = Column(Integer, primary_key=True)

        class Generic(Base, CommonMixin):

            discriminator = Column("python_type", String(50))
            __mapper_args__ = dict(polymorphic_on=discriminator)

        class Specific(Generic):

            __mapper_args__ = dict(polymorphic_identity="specific")
            id = Column(Integer, ForeignKey("generic.id"), primary_key=True)

        eq_(Generic.__table__.name, "generic")
        eq_(Specific.__table__.name, "specific")
        eq_(
            list(Generic.__table__.c.keys()),
            ["python_type", "timestamp", "id"],
        )
        eq_(list(Specific.__table__.c.keys()), ["id"])
        eq_(Generic.__table__.kwargs, {"mysql_engine": "InnoDB"})
        eq_(Specific.__table__.kwargs, {"mysql_engine": "InnoDB"})

    def test_some_propagation(self):
        class CommonMixin:
            @declared_attr
            def __tablename__(cls):
                return cls.__name__.lower()

            __table_args__ = {"mysql_engine": "InnoDB"}
            timestamp = Column(Integer)

        class BaseType(Base, CommonMixin):

            discriminator = Column("type", String(50))
            __mapper_args__ = dict(polymorphic_on=discriminator)
            id = Column(Integer, primary_key=True)
            value = Column(Integer())

        class Single(BaseType):

            __tablename__ = None
            __mapper_args__ = dict(polymorphic_identity="type1")

        class Joined(BaseType):

            __mapper_args__ = dict(polymorphic_identity="type2")
            id = Column(Integer, ForeignKey("basetype.id"), primary_key=True)

        eq_(BaseType.__table__.name, "basetype")
        eq_(
            list(BaseType.__table__.c.keys()),
            ["type", "id", "value", "timestamp"],
        )
        eq_(BaseType.__table__.kwargs, {"mysql_engine": "InnoDB"})
        assert Single.__table__ is BaseType.__table__
        eq_(Joined.__table__.name, "joined")
        eq_(list(Joined.__table__.c.keys()), ["id"])
        eq_(Joined.__table__.kwargs, {"mysql_engine": "InnoDB"})

    def test_col_copy_vs_declared_attr_joined_propagation(self):
        class Mixin:
            a = Column(Integer)

            @declared_attr
            def b(cls):
                return Column(Integer)

        class A(Mixin, Base):
            __tablename__ = "a"
            id = Column(Integer, primary_key=True)

        class B(A):
            __tablename__ = "b"
            id = Column(Integer, ForeignKey("a.id"), primary_key=True)

        assert "a" in A.__table__.c
        assert "b" in A.__table__.c
        assert "a" not in B.__table__.c
        assert "b" not in B.__table__.c

    def test_col_copy_vs_declared_attr_joined_propagation_newname(self):
        class Mixin:
            a = Column("a1", Integer)

            @declared_attr
            def b(cls):
                return Column("b1", Integer)

        class A(Mixin, Base):
            __tablename__ = "a"
            id = Column(Integer, primary_key=True)

        class B(A):
            __tablename__ = "b"
            id = Column(Integer, ForeignKey("a.id"), primary_key=True)

        assert "a1" in A.__table__.c
        assert "b1" in A.__table__.c
        assert "a1" not in B.__table__.c
        assert "b1" not in B.__table__.c

    def test_col_copy_vs_declared_attr_single_propagation(self):
        class Mixin:
            a = Column(Integer)

            @declared_attr
            def b(cls):
                return Column(Integer)

        class A(Mixin, Base):
            __tablename__ = "a"
            id = Column(Integer, primary_key=True)

        class B(A):
            pass

        assert "a" in A.__table__.c
        assert "b" in A.__table__.c

    def test_non_propagating_mixin(self):
        class NoJoinedTableNameMixin:
            @declared_attr
            def __tablename__(cls):
                if has_inherited_table(cls):
                    return None
                return cls.__name__.lower()

        class BaseType(Base, NoJoinedTableNameMixin):

            discriminator = Column("type", String(50))
            __mapper_args__ = dict(polymorphic_on=discriminator)
            id = Column(Integer, primary_key=True)
            value = Column(Integer())

        class Specific(BaseType):

            __mapper_args__ = dict(polymorphic_identity="specific")

        eq_(BaseType.__table__.name, "basetype")
        eq_(list(BaseType.__table__.c.keys()), ["type", "id", "value"])
        assert Specific.__table__ is BaseType.__table__
        assert (
            class_mapper(Specific).polymorphic_on is BaseType.__table__.c.type
        )
        eq_(class_mapper(Specific).polymorphic_identity, "specific")

    def test_non_propagating_mixin_used_for_joined(self):
        class TableNameMixin:
            @declared_attr
            def __tablename__(cls):
                if (
                    has_inherited_table(cls)
                    and TableNameMixin not in cls.__bases__
                ):
                    return None
                return cls.__name__.lower()

        class BaseType(Base, TableNameMixin):

            discriminator = Column("type", String(50))
            __mapper_args__ = dict(polymorphic_on=discriminator)
            id = Column(Integer, primary_key=True)
            value = Column(Integer())

        class Specific(BaseType, TableNameMixin):

            __mapper_args__ = dict(polymorphic_identity="specific")
            id = Column(Integer, ForeignKey("basetype.id"), primary_key=True)

        eq_(BaseType.__table__.name, "basetype")
        eq_(list(BaseType.__table__.c.keys()), ["type", "id", "value"])
        eq_(Specific.__table__.name, "specific")
        eq_(list(Specific.__table__.c.keys()), ["id"])

    def test_single_back_propagate(self):
        class ColumnMixin:

            timestamp = Column(Integer)

        class BaseType(Base):

            __tablename__ = "foo"
            discriminator = Column("type", String(50))
            __mapper_args__ = dict(polymorphic_on=discriminator)
            id = Column(Integer, primary_key=True)

        class Specific(BaseType, ColumnMixin):

            __mapper_args__ = dict(polymorphic_identity="specific")

        eq_(list(BaseType.__table__.c.keys()), ["type", "id", "timestamp"])

    def test_table_in_model_and_same_column_in_mixin(self):
        class ColumnMixin:

            data = Column(Integer)

        class Model(Base, ColumnMixin):

            __table__ = Table(
                "foo",
                Base.metadata,
                Column("data", Integer),
                Column("id", Integer, primary_key=True),
            )

        model_col = Model.__table__.c.data
        mixin_col = ColumnMixin.data
        assert model_col is not mixin_col
        eq_(model_col.name, "data")
        assert model_col.type.__class__ is mixin_col.type.__class__

    def test_table_in_model_and_different_named_column_in_mixin(self):
        class ColumnMixin:
            tada = Column(Integer)

        def go():
            class Model(Base, ColumnMixin):

                __table__ = Table(
                    "foo",
                    Base.metadata,
                    Column("data", Integer),
                    Column("id", Integer, primary_key=True),
                )
                foo = relationship("Dest")

        assert_raises_message(
            sa.exc.ArgumentError,
            "Can't add additional column 'tada' when " "specifying __table__",
            go,
        )

    def test_table_in_model_and_different_named_alt_key_column_in_mixin(self):

        # here, the __table__ has a column 'tada'.  We disallow
        # the add of the 'foobar' column, even though it's
        # keyed to 'tada'.

        class ColumnMixin:
            tada = Column("foobar", Integer)

        def go():
            class Model(Base, ColumnMixin):

                __table__ = Table(
                    "foo",
                    Base.metadata,
                    Column("data", Integer),
                    Column("tada", Integer),
                    Column("id", Integer, primary_key=True),
                )
                foo = relationship("Dest")

        assert_raises_message(
            sa.exc.ArgumentError,
            "Can't add additional column 'foobar' when "
            "specifying __table__",
            go,
        )

    def test_table_in_model_overrides_different_typed_column_in_mixin(self):
        class ColumnMixin:

            data = Column(String)

        class Model(Base, ColumnMixin):

            __table__ = Table(
                "foo",
                Base.metadata,
                Column("data", Integer),
                Column("id", Integer, primary_key=True),
            )

        model_col = Model.__table__.c.data
        mixin_col = ColumnMixin.data
        assert model_col is not mixin_col
        eq_(model_col.name, "data")
        assert model_col.type.__class__ is Integer

    def test_mixin_column_ordering(self):
        class Foo:

            col1 = Column(Integer)
            col3 = Column(Integer)

        class Bar:

            col2 = Column(Integer)
            col4 = Column(Integer)

        class Model(Base, Foo, Bar):

            id = Column(Integer, primary_key=True)
            __tablename__ = "model"

        eq_(
            list(Model.__table__.c.keys()),
            ["id", "col1", "col3", "col2", "col4"],
        )

    def test_honor_class_mro_one(self):
        class HasXMixin:
            @declared_attr
            def x(self):
                return Column(Integer)

        class Parent(HasXMixin, Base):
            __tablename__ = "parent"
            id = Column(Integer, primary_key=True)

        class Child(Parent):
            __tablename__ = "child"
            id = Column(Integer, ForeignKey("parent.id"), primary_key=True)

        assert "x" not in Child.__table__.c

    def test_honor_class_mro_two(self):
        class HasXMixin:
            @declared_attr
            def x(self):
                return Column(Integer)

        class Parent(HasXMixin, Base):
            __tablename__ = "parent"
            id = Column(Integer, primary_key=True)

            def x(self):
                return "hi"

        class C(Parent):
            __tablename__ = "c"
            id = Column(Integer, ForeignKey("parent.id"), primary_key=True)

        assert C().x() == "hi"

    def test_arbitrary_attrs_one(self):
        class HasMixin:
            @declared_attr
            def some_attr(cls):
                return cls.__name__ + "SOME ATTR"

        class Mapped(HasMixin, Base):
            __tablename__ = "t"
            id = Column(Integer, primary_key=True)

        eq_(Mapped.some_attr, "MappedSOME ATTR")
        eq_(Mapped.__dict__["some_attr"], "MappedSOME ATTR")

    def test_arbitrary_attrs_two(self):
        from sqlalchemy.ext.associationproxy import association_proxy

        class FilterA(Base):
            __tablename__ = "filter_a"
            id = Column(Integer(), primary_key=True)
            parent_id = Column(Integer(), ForeignKey("type_a.id"))
            filter = Column(String())

            def __init__(self, filter_, **kw):
                self.filter = filter_

        class FilterB(Base):
            __tablename__ = "filter_b"
            id = Column(Integer(), primary_key=True)
            parent_id = Column(Integer(), ForeignKey("type_b.id"))
            filter = Column(String())

            def __init__(self, filter_, **kw):
                self.filter = filter_

        class FilterMixin:
            @declared_attr
            def _filters(cls):
                return relationship(
                    cls.filter_class, cascade="all,delete,delete-orphan"
                )

            @declared_attr
            def filters(cls):
                return association_proxy("_filters", "filter")

        class TypeA(Base, FilterMixin):
            __tablename__ = "type_a"
            filter_class = FilterA
            id = Column(Integer(), primary_key=True)

        class TypeB(Base, FilterMixin):
            __tablename__ = "type_b"
            filter_class = FilterB
            id = Column(Integer(), primary_key=True)

        TypeA(filters=["foo"])
        TypeB(filters=["foo"])

    def test_arbitrary_attrs_three(self):
        class Mapped(Base):
            __tablename__ = "t"
            id = Column(Integer, primary_key=True)

            @declared_attr
            def some_attr(cls):
                return cls.__name__ + "SOME ATTR"

        eq_(Mapped.some_attr, "MappedSOME ATTR")
        eq_(Mapped.__dict__["some_attr"], "MappedSOME ATTR")

    def test_arbitrary_attrs_doesnt_apply_to_abstract_declared_attr(self):
        names = ["name1", "name2", "name3"]

        class SomeAbstract(Base):
            __abstract__ = True

            @declared_attr
            def some_attr(cls):
                return names.pop(0)

        class M1(SomeAbstract):
            __tablename__ = "t1"
            id = Column(Integer, primary_key=True)

        class M2(SomeAbstract):
            __tablename__ = "t2"
            id = Column(Integer, primary_key=True)

        eq_(M1.__dict__["some_attr"], "name1")
        eq_(M2.__dict__["some_attr"], "name2")

    def test_arbitrary_attrs_doesnt_apply_to_prepare_nocascade(self):
        names = ["name1", "name2", "name3"]

        class SomeAbstract(Base):
            __tablename__ = "t0"
            __no_table__ = True

            # used by AbstractConcreteBase
            _sa_decl_prepare_nocascade = True

            id = Column(Integer, primary_key=True)

            @declared_attr
            def some_attr(cls):
                return names.pop(0)

        class M1(SomeAbstract):
            __tablename__ = "t1"
            id = Column(Integer, primary_key=True)

        class M2(SomeAbstract):
            __tablename__ = "t2"
            id = Column(Integer, primary_key=True)

        eq_(M1.some_attr, "name2")
        eq_(M2.some_attr, "name3")
        eq_(M1.__dict__["some_attr"], "name2")
        eq_(M2.__dict__["some_attr"], "name3")
        assert isinstance(SomeAbstract.__dict__["some_attr"], declared_attr)


class DeclarativeMixinPropertyTest(
    DeclarativeTestBase, testing.AssertsCompiledSQL
):
    def test_column_property(self):
        class MyMixin:
            @declared_attr
            def prop_hoho(cls):
                return column_property(Column("prop", String(50)))

        class MyModel(Base, MyMixin):

            __tablename__ = "test"
            id = Column(
                Integer, primary_key=True, test_needs_autoincrement=True
            )

        class MyOtherModel(Base, MyMixin):

            __tablename__ = "othertest"
            id = Column(
                Integer, primary_key=True, test_needs_autoincrement=True
            )

        assert MyModel.__table__.c.prop is not None
        assert MyOtherModel.__table__.c.prop is not None
        assert MyModel.__table__.c.prop is not MyOtherModel.__table__.c.prop
        assert MyModel.prop_hoho.property.columns == [MyModel.__table__.c.prop]
        assert MyOtherModel.prop_hoho.property.columns == [
            MyOtherModel.__table__.c.prop
        ]
        assert (
            MyModel.prop_hoho.property is not MyOtherModel.prop_hoho.property
        )
        Base.metadata.create_all(testing.db)
        sess = fixture_session()
        m1, m2 = MyModel(prop_hoho="foo"), MyOtherModel(prop_hoho="bar")
        sess.add_all([m1, m2])
        sess.flush()
        eq_(sess.query(MyModel).filter(MyModel.prop_hoho == "foo").one(), m1)
        eq_(
            sess.query(MyOtherModel)
            .filter(MyOtherModel.prop_hoho == "bar")
            .one(),
            m2,
        )

    @testing.combinations(
        "anno",
        "anno_w_clsmeth",
        "pep593",
        "nonanno",
        "legacy",
        argnames="clstype",
    )
    def test_column_property_col_ref(self, decl_base, clstype):

        if clstype == "anno":

            class SomethingMixin:
                x: Mapped[int]
                y: Mapped[int] = mapped_column()

                @declared_attr
                def x_plus_y(cls) -> Mapped[int]:
                    return column_property(cls.x + cls.y)

        elif clstype == "anno_w_clsmeth":
            # this form works better w/ pylance, so support it
            class SomethingMixin:
                x: Mapped[int]
                y: Mapped[int] = mapped_column()

                @declared_attr
                @classmethod
                def x_plus_y(cls) -> Mapped[int]:
                    return column_property(cls.x + cls.y)

        elif clstype == "nonanno":

            class SomethingMixin:
                x = mapped_column(Integer)
                y = mapped_column(Integer)

                @declared_attr
                def x_plus_y(cls) -> Mapped[int]:
                    return column_property(cls.x + cls.y)

        elif clstype == "pep593":
            myint = Annotated[int, mapped_column(Integer)]

            class SomethingMixin:
                x: Mapped[myint]
                y: Mapped[myint]

                @declared_attr
                def x_plus_y(cls) -> Mapped[int]:
                    return column_property(cls.x + cls.y)

        elif clstype == "legacy":

            class SomethingMixin:
                x = Column(Integer)
                y = Column(Integer)

                @declared_attr
                def x_plus_y(cls) -> Mapped[int]:
                    return column_property(cls.x + cls.y)

        else:
            assert False

        class Something(SomethingMixin, Base):
            __tablename__ = "something"

            id: Mapped[int] = mapped_column(primary_key=True)

        class SomethingElse(SomethingMixin, Base):
            __tablename__ = "something_else"

            id: Mapped[int] = mapped_column(primary_key=True)

        # use the mixin twice, make sure columns are copied, etc
        self.assert_compile(
            select(Something.x_plus_y),
            "SELECT something.x + something.y AS anon_1 FROM something",
        )

        self.assert_compile(
            select(SomethingElse.x_plus_y),
            "SELECT something_else.x + something_else.y AS anon_1 "
            "FROM something_else",
        )

    def test_doc(self):
        """test documentation transfer.

        the documentation situation with @declared_attr is problematic.
        at least see if mapped subclasses get the doc.

        """

        class MyMixin:
            @declared_attr
            def type_(cls):
                """this is a document."""

                return Column(String(50))

            @declared_attr
            def t2(cls):
                """this is another document."""

                return column_property(Column(String(50)))

        class MyModel(Base, MyMixin):

            __tablename__ = "test"
            id = Column(Integer, primary_key=True)

        configure_mappers()
        eq_(MyModel.type_.__doc__, """this is a document.""")
        eq_(MyModel.t2.__doc__, """this is another document.""")

    def test_correct_for_proxies(self):
        from sqlalchemy.ext.hybrid import hybrid_property
        from sqlalchemy import inspect

        class Mixin:
            @hybrid_property
            def hp1(cls):
                return 42

            @declared_attr
            def hp2(cls):
                @hybrid_property
                def hp2(self):
                    return 42

                return hp2

        class Base(declarative_base(), Mixin):
            __tablename__ = "test"
            id = Column(String, primary_key=True)

        class Derived(Base):
            pass

        # in all cases we get a proxy when we use class-bound access
        # for the hybrid
        assert Base.hp1._is_internal_proxy
        assert Base.hp2._is_internal_proxy
        assert Derived.hp1._is_internal_proxy
        assert Derived.hp2._is_internal_proxy

        # however when declarative sets it up, it checks for this proxy
        # and adjusts
        b1 = inspect(Base)
        d1 = inspect(Derived)
        is_(b1.all_orm_descriptors["hp1"], d1.all_orm_descriptors["hp1"])

        is_(b1.all_orm_descriptors["hp2"], d1.all_orm_descriptors["hp2"])

    def test_correct_for_proxies_doesnt_impact_synonyms(self):
        from sqlalchemy import inspect

        class Mixin:
            @declared_attr
            def data_syn(cls):
                return synonym("data")

        class Base(declarative_base(), Mixin):
            __tablename__ = "test"
            id = Column(String, primary_key=True)
            data = Column(String)
            type = Column(String)
            __mapper_args__ = {
                "polymorphic_on": type,
                "polymorphic_identity": "base",
            }

        class Derived(Base):
            __mapper_args__ = {"polymorphic_identity": "derived"}

        assert Base.data_syn._is_internal_proxy
        assert Derived.data_syn._is_internal_proxy

        b1 = inspect(Base)
        d1 = inspect(Derived)
        is_(b1.attrs["data_syn"], d1.attrs["data_syn"])

        s = fixture_session()
        self.assert_compile(
            s.query(Base.data_syn).filter(Base.data_syn == "foo"),
            "SELECT test.data AS test_data FROM test "
            "WHERE test.data = :data_1",
            dialect="default",
        )
        self.assert_compile(
            s.query(Derived.data_syn).filter(Derived.data_syn == "foo"),
            "SELECT test.data AS test_data FROM test WHERE test.data = "
            ":data_1 AND test.type IN (__[POSTCOMPILE_type_1])",
            dialect="default",
            checkparams={"type_1": ["derived"], "data_1": "foo"},
        )

    def test_column_in_mapper_args(self):
        class MyMixin:
            @declared_attr
            def type_(cls):
                return Column(String(50))

            __mapper_args__ = {"polymorphic_on": type_}

        class MyModel(Base, MyMixin):

            __tablename__ = "test"
            id = Column(Integer, primary_key=True)

        configure_mappers()
        col = MyModel.__mapper__.polymorphic_on
        eq_(col.name, "type_")
        assert col.table is not None

    def test_column_in_mapper_args_used_multiple_times(self):
        class MyMixin:

            version_id = Column(Integer)
            __mapper_args__ = {"version_id_col": version_id}

        class ModelOne(Base, MyMixin):

            __tablename__ = "m1"
            id = Column(Integer, primary_key=True)

        class ModelTwo(Base, MyMixin):

            __tablename__ = "m2"
            id = Column(Integer, primary_key=True)

        is_(
            ModelOne.__mapper__.version_id_col, ModelOne.__table__.c.version_id
        )
        is_(
            ModelTwo.__mapper__.version_id_col, ModelTwo.__table__.c.version_id
        )

    def test_deferred(self):
        class MyMixin:
            @declared_attr
            def data(cls):
                return deferred(Column("data", String(50)))

        class MyModel(Base, MyMixin):

            __tablename__ = "test"
            id = Column(
                Integer, primary_key=True, test_needs_autoincrement=True
            )

        Base.metadata.create_all(testing.db)
        sess = fixture_session()
        sess.add_all([MyModel(data="d1"), MyModel(data="d2")])
        sess.flush()
        sess.expunge_all()
        d1, d2 = sess.query(MyModel).order_by(MyModel.data)
        assert "data" not in d1.__dict__
        assert d1.data == "d1"
        assert "data" in d1.__dict__

    def _test_relationship(self, usestring):
        class RefTargetMixin:
            @declared_attr
            def target_id(cls):
                return Column("target_id", ForeignKey("target.id"))

            if usestring:

                @declared_attr
                def target(cls):
                    return relationship(
                        "Target",
                        primaryjoin="Target.id==%s.target_id" % cls.__name__,
                    )

            else:

                @declared_attr
                def target(cls):
                    return relationship("Target")

        class Foo(Base, RefTargetMixin):

            __tablename__ = "foo"
            id = Column(
                Integer, primary_key=True, test_needs_autoincrement=True
            )

        class Bar(Base, RefTargetMixin):

            __tablename__ = "bar"
            id = Column(
                Integer, primary_key=True, test_needs_autoincrement=True
            )

        class Target(Base):

            __tablename__ = "target"
            id = Column(
                Integer, primary_key=True, test_needs_autoincrement=True
            )

        Base.metadata.create_all(testing.db)
        sess = fixture_session()
        t1, t2 = Target(), Target()
        f1, f2, b1 = Foo(target=t1), Foo(target=t2), Bar(target=t1)
        sess.add_all([f1, f2, b1])
        sess.flush()
        eq_(sess.query(Foo).filter(Foo.target == t2).one(), f2)
        eq_(sess.query(Bar).filter(Bar.target == t2).first(), None)
        sess.expire_all()
        eq_(f1.target, t1)

    def test_relationship(self):
        self._test_relationship(False)

    def test_relationship_primryjoin(self):
        self._test_relationship(True)


class DeclaredAttrTest(DeclarativeTestBase, testing.AssertsCompiledSQL):
    __dialect__ = "default"

    def test_singleton_behavior_within_decl(self):
        counter = mock.Mock()

        class Mixin:
            @declared_attr
            def my_prop(cls):
                counter(cls)
                return Column("x", Integer)

        class A(Base, Mixin):
            __tablename__ = "a"
            id = Column(Integer, primary_key=True)

            @declared_attr
            def my_other_prop(cls):
                return column_property(cls.my_prop + 5)

        eq_(counter.mock_calls, [mock.call(A)])

        class B(Base, Mixin):
            __tablename__ = "b"
            id = Column(Integer, primary_key=True)

            @declared_attr
            def my_other_prop(cls):
                return column_property(cls.my_prop + 5)

        eq_(counter.mock_calls, [mock.call(A), mock.call(B)])

        # this is why we need singleton-per-class behavior.   We get
        # an un-bound "x" column otherwise here, because my_prop() generates
        # multiple columns.
        a_col = A.my_other_prop.__clause_element__().element.left
        b_col = B.my_other_prop.__clause_element__().element.left
        is_(a_col.table, A.__table__)
        is_(b_col.table, B.__table__)
        is_(a_col, A.__table__.c.x)
        is_(b_col, B.__table__.c.x)

        s = fixture_session()
        self.assert_compile(
            s.query(A),
            "SELECT a.x + :x_1 AS anon_1, a.id AS a_id, a.x AS a_x FROM a",
        )
        self.assert_compile(
            s.query(B),
            "SELECT b.x + :x_1 AS anon_1, b.id AS b_id, b.x AS b_x FROM b",
        )

    @testing.requires.predictable_gc
    def test_singleton_gc(self):
        counter = mock.Mock()

        class Mixin:
            @declared_attr
            def my_prop(cls):
                counter(cls.__name__)
                return Column("x", Integer)

        class A(Base, Mixin):
            __tablename__ = "b"
            id = Column(Integer, primary_key=True)

            @declared_attr
            def my_other_prop(cls):
                return column_property(cls.my_prop + 5)

        eq_(counter.mock_calls, [mock.call("A")])
        del A
        gc_collect()

        from sqlalchemy.orm.clsregistry import _key_is_empty

        assert _key_is_empty(
            "A",
            Base.registry._class_registry,
            lambda cls: hasattr(cls, "my_other_prop"),
        )

    def test_can_we_access_the_mixin_straight(self):
        class Mixin:
            @declared_attr
            def my_prop(cls):
                return Column("x", Integer)

        with expect_warnings(
            "Unmanaged access of declarative attribute my_prop "
            "from non-mapped class Mixin"
        ):
            Mixin.my_prop

    def test_can_we_access_the_mixin_straight_special_names(self):
        class Mixin:
            @declared_attr.directive
            def __table_args__(cls):
                return (1, 2, 3)

            @declared_attr.directive
            def __arbitrary__(cls):
                return (4, 5, 6)

        eq_(Mixin.__table_args__, (1, 2, 3))
        eq_(Mixin.__arbitrary__, (4, 5, 6))

    def test_non_decl_access(self):
        counter = mock.Mock()

        class Mixin:
            @declared_attr.directive
            def __tablename__(cls):
                counter(cls)
                return "foo"

        class Foo(Mixin, Base):
            id = Column(Integer, primary_key=True)

            @declared_attr.directive
            def x(cls):
                cls.__tablename__

            @declared_attr.directive
            def y(cls):
                cls.__tablename__

        eq_(counter.mock_calls, [mock.call(Foo)])

        eq_(Foo.__tablename__, "foo")
        eq_(Foo.__tablename__, "foo")

        # here we are testing that access of __tablename__ does in fact
        # call the user-defined function, as we are no longer in the
        # "declarative_scan" phase.  the class *is* mapped here.
        eq_(
            counter.mock_calls,
            [mock.call(Foo), mock.call(Foo), mock.call(Foo)],
        )

    def test_property_noncascade(self):
        counter = mock.Mock()

        class Mixin:
            @declared_attr
            def my_prop(cls):
                counter(cls)
                return column_property(cls.x + 2)

        class A(Base, Mixin):
            __tablename__ = "a"

            id = Column(Integer, primary_key=True)
            x = Column(Integer)

        class B(A):
            pass

        eq_(counter.mock_calls, [mock.call(A)])

    def test_property_cascade_mixin(self):
        counter = mock.Mock()

        class Mixin:
            @declared_attr.cascading
            def my_prop(cls):
                counter(cls)
                return column_property(cls.x + 2)

        class A(Base, Mixin):
            __tablename__ = "a"

            id = Column(Integer, primary_key=True)
            x = Column(Integer)

        class B(A):
            pass

        eq_(counter.mock_calls, [mock.call(A), mock.call(B)])

    def test_property_cascade_mixin_override(self):
        counter = mock.Mock()

        class Mixin:
            @declared_attr.cascading
            def my_prop(cls):
                counter(cls)
                return column_property(cls.x + 2)

        class A(Base, Mixin):
            __tablename__ = "a"

            id = Column(Integer, primary_key=True)
            x = Column(Integer)

        with expect_warnings(
            "Attribute 'my_prop' on class .*B.* "
            "cannot be processed due to @declared_attr.cascading; "
            "skipping"
        ):

            class B(A):
                my_prop = Column("foobar", Integer)

        eq_(counter.mock_calls, [mock.call(A), mock.call(B)])

    def test_property_cascade_abstract(self):
        counter = mock.Mock()

        class Abs(Base):
            __abstract__ = True

            @declared_attr.cascading
            def my_prop(cls):
                counter(cls)
                return column_property(cls.x + 2)

        class A(Abs):
            __tablename__ = "a"

            id = Column(Integer, primary_key=True)
            x = Column(Integer)

        class B(A):
            pass

        eq_(counter.mock_calls, [mock.call(A), mock.call(B)])

    def test_warn_cascading_used_w_tablename(self):
        class Mixin:
            @declared_attr.cascading
            def __tablename__(cls):
                return "foo"

        with expect_warnings(
            "@declared_attr.cascading is not supported on the "
            "__tablename__ attribute on class .*A."
        ):

            class A(Mixin, Base):
                id = Column(Integer, primary_key=True)

        eq_(A.__table__.name, "foo")

    def test_col_prop_attrs_associated_w_class_for_mapper_args(self):
        from sqlalchemy import Column
        import collections

        asserted = collections.defaultdict(set)

        class Mixin:
            @declared_attr.cascading
            def my_attr(cls):
                if has_inherited_table(cls):
                    id_ = Column(ForeignKey("a.my_attr"), primary_key=True)
                    asserted["b"].add(id_)
                else:
                    id_ = Column(Integer, primary_key=True)
                    asserted["a"].add(id_)
                return id_

        class A(Base, Mixin):
            __tablename__ = "a"

            @declared_attr
            def __mapper_args__(cls):
                asserted["a"].add(cls.my_attr)
                return {}

        # here:
        # 1. A is mapped.  so A.my_attr is now the InstrumentedAttribute.
        # 2. B wants to call my_attr also.  Due to .cascading, it has been
        # invoked specific to B, and is present in the dict_ that will
        # be used when we map the class.  But except for the
        # special setattr() we do in _scan_attributes() in this case, would
        # otherwise not been set on the class as anything from this call;
        # the usual mechanics of calling it from the descriptor also do not
        # work because A is fully mapped and because A set it up, is currently
        # that non-expected InstrumentedAttribute and replaces the
        # descriptor from being invoked.

        class B(A):
            __tablename__ = "b"

            @declared_attr
            def __mapper_args__(cls):
                asserted["b"].add(cls.my_attr)
                return {}

        eq_(
            asserted,
            {
                "a": {A.my_attr.property.columns[0]},
                "b": {B.my_attr.property.columns[0]},
            },
        )

    def test_column_pre_map(self):
        counter = mock.Mock()

        class Mixin:
            @declared_attr
            def my_col(cls):
                counter(cls)
                assert not orm_base._mapper_or_none(cls)
                return Column("x", Integer)

        class A(Base, Mixin):
            __tablename__ = "a"

            id = Column(Integer, primary_key=True)

        eq_(counter.mock_calls, [mock.call(A)])

    def test_mixin_attr_refers_to_column_copies(self):
        # this @declared_attr can refer to User.id
        # freely because we now do the "copy column" operation
        # before the declared_attr is invoked.

        counter = mock.Mock()

        class HasAddressCount:
            id = Column(Integer, primary_key=True)

            @declared_attr
            def address_count(cls):
                counter(cls.id)
                return column_property(
                    select(func.count(Address.id))
                    .where(Address.user_id == cls.id)
                    .scalar_subquery()
                )

        class Address(Base):
            __tablename__ = "address"
            id = Column(Integer, primary_key=True)
            user_id = Column(ForeignKey("user.id"))

        class User(Base, HasAddressCount):
            __tablename__ = "user"

        eq_(counter.mock_calls, [mock.call(User.id)])

        sess = fixture_session()
        self.assert_compile(
            sess.query(User).having(User.address_count > 5),
            "SELECT (SELECT count(address.id) AS "
            'count_1 FROM address WHERE address.user_id = "user".id) '
            'AS anon_1, "user".id AS user_id FROM "user" '
            "HAVING (SELECT count(address.id) AS "
            'count_1 FROM address WHERE address.user_id = "user".id) '
            "> :param_1",
        )

    def test_multilevel_mixin_attr_refers_to_column_copies(self):
        """test #8190.

        This test is the same idea as test_mixin_attr_refers_to_column_copies
        but tests the column copies from superclasses.

        """
        counter = mock.Mock()

        class SomeOtherMixin:
            status = Column(String)

        class HasAddressCount(SomeOtherMixin):
            id = Column(Integer, primary_key=True)

            @declared_attr
            def address_count(cls):
                counter(cls.id)
                counter(cls.status)
                return column_property(
                    select(func.count(Address.id))
                    .where(Address.user_id == cls.id)
                    .where(cls.status == "some status")
                    .scalar_subquery()
                )

        class Address(Base):
            __tablename__ = "address"
            id = Column(Integer, primary_key=True)
            user_id = Column(ForeignKey("user.id"))

        class User(Base, HasAddressCount):
            __tablename__ = "user"

        eq_(counter.mock_calls, [mock.call(User.id), mock.call(User.status)])

        sess = fixture_session()
        self.assert_compile(
            sess.query(User).having(User.address_count > 5),
            "SELECT (SELECT count(address.id) AS count_1 FROM address "
            'WHERE address.user_id = "user".id AND "user".status = :param_1) '
            'AS anon_1, "user".id AS user_id, "user".status AS user_status '
            'FROM "user" HAVING (SELECT count(address.id) AS count_1 '
            'FROM address WHERE address.user_id = "user".id '
            'AND "user".status = :param_1) > :param_2',
        )


class AbstractTest(DeclarativeTestBase):
    def test_abstract_boolean(self):
        class A(Base):
            __abstract__ = True
            __tablename__ = "x"
            id = Column(Integer, primary_key=True)

        class B(Base):
            __abstract__ = False
            __tablename__ = "y"
            id = Column(Integer, primary_key=True)

        class C(Base):
            __abstract__ = False
            __tablename__ = "z"
            id = Column(Integer, primary_key=True)

        class D(Base):
            __tablename__ = "q"
            id = Column(Integer, primary_key=True)

        eq_(set(Base.metadata.tables), {"y", "z", "q"})

    def test_middle_abstract_attributes(self):
        # test for [ticket:3219]
        class A(Base):
            __tablename__ = "a"

            id = Column(Integer, primary_key=True)
            name = Column(String)

        class B(A):
            __abstract__ = True
            data = Column(String)

        class C(B):
            c_value = Column(String)

        eq_(sa.inspect(C).attrs.keys(), ["id", "name", "c_value", "data"])

    def test_implicit_abstract_viadecorator(self):
        @mapper_registry.mapped
        class A:
            __tablename__ = "a"

            id = Column(Integer, primary_key=True)
            name = Column(String)

        class B(A):
            data = Column(String)

        @mapper_registry.mapped
        class C(B):
            c_value = Column(String)

        eq_(sa.inspect(C).attrs.keys(), ["id", "name", "c_value", "data"])

    def test_middle_abstract_inherits(self):
        # test for [ticket:3240]

        class A(Base):
            __tablename__ = "a"
            id = Column(Integer, primary_key=True)

        class AAbs(A):
            __abstract__ = True

        class B1(A):
            __tablename__ = "b1"
            id = Column(ForeignKey("a.id"), primary_key=True)

        class B2(AAbs):
            __tablename__ = "b2"
            id = Column(ForeignKey("a.id"), primary_key=True)

        assert B1.__mapper__.inherits is A.__mapper__

        assert B2.__mapper__.inherits is A.__mapper__