sqlalchemy / test / sql / test_metadata.py

   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
from sqlalchemy.testing import assert_raises
from sqlalchemy.testing import assert_raises_message
from sqlalchemy.testing import emits_warning

import pickle
from sqlalchemy import Integer, String, UniqueConstraint, \
    CheckConstraint, ForeignKey, MetaData, Sequence, \
    ForeignKeyConstraint, ColumnDefault, Index, event,\
    events, Unicode, types as sqltypes
from sqlalchemy.testing.schema import Table, Column
from sqlalchemy import schema, exc
import sqlalchemy as tsa
from sqlalchemy.testing import fixtures
from sqlalchemy import testing
from sqlalchemy.testing import ComparesTables, AssertsCompiledSQL
from sqlalchemy.testing import eq_, is_

class MetaDataTest(fixtures.TestBase, ComparesTables):
    def test_metadata_connect(self):
        metadata = MetaData()
        t1 = Table('table1', metadata,
            Column('col1', Integer, primary_key=True),
            Column('col2', String(20)))
        metadata.bind = testing.db
        metadata.create_all()
        try:
            assert t1.count().scalar() == 0
        finally:
            metadata.drop_all()

    def test_metadata_contains(self):
        metadata = MetaData()
        t1 = Table('t1', metadata, Column('x', Integer))
        t2 = Table('t2', metadata, Column('x', Integer), schema='foo')
        t3 = Table('t2', MetaData(), Column('x', Integer))
        t4 = Table('t1', MetaData(), Column('x', Integer), schema='foo')

        assert "t1" in metadata
        assert "foo.t2" in metadata
        assert "t2" not in metadata
        assert "foo.t1" not in metadata
        assert t1 in metadata
        assert t2 in metadata
        assert t3 not in metadata
        assert t4 not in metadata

    def test_uninitialized_column_copy(self):
        for col in [
            Column('foo', String(), nullable=False),
            Column('baz', String(), unique=True),
            Column(Integer(), primary_key=True),
            Column('bar', Integer(), Sequence('foo_seq'), primary_key=True,
                                                            key='bar'),
            Column(Integer(), ForeignKey('bat.blah'), doc="this is a col"),
            Column('bar', Integer(), ForeignKey('bat.blah'), primary_key=True,
                                                            key='bar'),
            Column('bar', Integer(), info={'foo': 'bar'}),
        ]:
            c2 = col.copy()
            for attr in ('name', 'type', 'nullable',
                        'primary_key', 'key', 'unique', 'info',
                        'doc'):
                eq_(getattr(col, attr), getattr(c2, attr))
            eq_(len(col.foreign_keys), len(c2.foreign_keys))
            if col.default:
                eq_(c2.default.name, 'foo_seq')
            for a1, a2 in zip(col.foreign_keys, c2.foreign_keys):
                assert a1 is not a2
                eq_(a2._colspec, 'bat.blah')

    def test_col_subclass_copy(self):
        class MyColumn(schema.Column):
            def __init__(self, *args, **kw):
                self.widget = kw.pop('widget', None)
                super(MyColumn, self).__init__(*args, **kw)

            def copy(self, *arg, **kw):
                c = super(MyColumn, self).copy(*arg, **kw)
                c.widget = self.widget
                return c
        c1 = MyColumn('foo', Integer, widget='x')
        c2 = c1.copy()
        assert isinstance(c2, MyColumn)
        eq_(c2.widget, 'x')

    def test_uninitialized_column_copy_events(self):
        msgs = []
        def write(c, t):
            msgs.append("attach %s.%s" % (t.name, c.name))
        c1 = Column('foo', String())
        m = MetaData()
        for i in range(3):
            cx = c1.copy()
            # as of 0.7, these events no longer copy.  its expected
            # that listeners will be re-established from the
            # natural construction of things.
            cx._on_table_attach(write)
            Table('foo%d' % i, m, cx)
        eq_(msgs, ['attach foo0.foo', 'attach foo1.foo', 'attach foo2.foo'])

    def test_schema_collection_add(self):
        metadata = MetaData()

        Table('t1', metadata, Column('x', Integer), schema='foo')
        Table('t2', metadata, Column('x', Integer), schema='bar')
        Table('t3', metadata, Column('x', Integer))

        eq_(metadata._schemas, set(['foo', 'bar']))
        eq_(len(metadata.tables), 3)

    def test_schema_collection_remove(self):
        metadata = MetaData()

        t1 = Table('t1', metadata, Column('x', Integer), schema='foo')
        Table('t2', metadata, Column('x', Integer), schema='bar')
        t3 = Table('t3', metadata, Column('x', Integer), schema='bar')

        metadata.remove(t3)
        eq_(metadata._schemas, set(['foo', 'bar']))
        eq_(len(metadata.tables), 2)

        metadata.remove(t1)
        eq_(metadata._schemas, set(['bar']))
        eq_(len(metadata.tables), 1)

    def test_schema_collection_remove_all(self):
        metadata = MetaData()

        Table('t1', metadata, Column('x', Integer), schema='foo')
        Table('t2', metadata, Column('x', Integer), schema='bar')

        metadata.clear()
        eq_(metadata._schemas, set())
        eq_(len(metadata.tables), 0)

    def test_metadata_tables_immutable(self):
        metadata = MetaData()

        Table('t1', metadata, Column('x', Integer))
        assert 't1' in metadata.tables

        assert_raises(
            TypeError,
            lambda: metadata.tables.pop('t1')
        )

    @testing.provide_metadata
    def test_dupe_tables(self):
        metadata = self.metadata
        Table('table1', metadata,
                Column('col1', Integer, primary_key=True),
                Column('col2', String(20)))

        metadata.create_all()
        Table('table1', metadata, autoload=True)
        def go():
            Table('table1', metadata,
                    Column('col1', Integer, primary_key=True),
                    Column('col2', String(20)))
        assert_raises_message(
            tsa.exc.InvalidRequestError,
                "Table 'table1' is already defined for this "
                "MetaData instance.  Specify 'extend_existing=True' "
                "to redefine options and columns on an existing "
                "Table object.",
            go
        )

    def test_fk_copy(self):
        c1 = Column('foo', Integer)
        c2 = Column('bar', Integer)
        m = MetaData()
        t1 = Table('t', m, c1, c2)

        kw = dict(onupdate="X",
                        ondelete="Y", use_alter=True, name='f1',
                        deferrable="Z", initially="Q", link_to_name=True)

        fk1 = ForeignKey(c1, **kw)
        fk2 = ForeignKeyConstraint((c1,), (c2,), **kw)

        t1.append_constraint(fk2)
        fk1c = fk1.copy()
        fk2c = fk2.copy()

        for k in kw:
            eq_(getattr(fk1c, k), kw[k])
            eq_(getattr(fk2c, k), kw[k])

    def test_check_constraint_copy(self):
        r = lambda x: x
        c = CheckConstraint("foo bar",
                            name='name',
                            initially=True,
                            deferrable=True,
                            _create_rule=r)
        c2 = c.copy()
        eq_(c2.name, 'name')
        eq_(str(c2.sqltext), "foo bar")
        eq_(c2.initially, True)
        eq_(c2.deferrable, True)
        assert c2._create_rule is r

    def test_col_replace_w_constraint(self):
        m = MetaData()
        a = Table('a', m, Column('id', Integer, primary_key=True))

        aid = Column('a_id', ForeignKey('a.id'))
        b = Table('b', m, aid)
        b.append_column(aid)

        assert b.c.a_id.references(a.c.id)
        eq_(len(b.constraints), 2)

    def test_fk_construct(self):
        c1 = Column('foo', Integer)
        c2 = Column('bar', Integer)
        m = MetaData()
        t1 = Table('t', m, c1, c2)
        fk1 = ForeignKeyConstraint(('foo', ), ('bar', ), table=t1)
        assert fk1 in t1.constraints

    def test_fk_no_such_parent_col_error(self):
        meta = MetaData()
        a = Table('a', meta, Column('a', Integer))
        Table('b', meta, Column('b', Integer))

        def go():
            a.append_constraint(
                ForeignKeyConstraint(['x'], ['b.b'])
            )
        assert_raises_message(
            exc.ArgumentError,
            "Can't create ForeignKeyConstraint on "
            "table 'a': no column named 'x' is present.",
            go
        )

    def test_fk_no_such_target_col_error_upfront(self):
        meta = MetaData()
        a = Table('a', meta, Column('a', Integer))
        Table('b', meta, Column('b', Integer))

        a.append_constraint(ForeignKeyConstraint(['a'], ['b.x']))

        assert_raises_message(
            exc.NoReferencedColumnError,
            "Could not initialize target column for ForeignKey 'b.x' on "
            "table 'a': table 'b' has no column named 'x'",
            getattr, list(a.foreign_keys)[0], "column"
        )

    def test_fk_no_such_target_col_error_delayed(self):
        meta = MetaData()
        a = Table('a', meta, Column('a', Integer))
        a.append_constraint(
            ForeignKeyConstraint(['a'], ['b.x']))

        b = Table('b', meta, Column('b', Integer))

        assert_raises_message(
            exc.NoReferencedColumnError,
            "Could not initialize target column for ForeignKey 'b.x' on "
            "table 'a': table 'b' has no column named 'x'",
            getattr, list(a.foreign_keys)[0], "column"
        )


    @testing.exclude('mysql', '<', (4, 1, 1), 'early types are squirrely')
    def test_to_metadata(self):
        meta = MetaData()

        table = Table('mytable', meta,
            Column('myid', Integer, Sequence('foo_id_seq'), primary_key=True),
            Column('name', String(40), nullable=True),
            Column('foo', String(40), nullable=False, server_default='x',
                                                        server_onupdate='q'),
            Column('bar', String(40), nullable=False, default='y',
                                                        onupdate='z'),
            Column('description', String(30),
                                    CheckConstraint("description='hi'")),
            UniqueConstraint('name'),
            test_needs_fk=True,
        )

        table2 = Table('othertable', meta,
            Column('id', Integer, Sequence('foo_seq'), primary_key=True),
            Column('myid', Integer,
                        ForeignKey('mytable.myid'),
                    ),
            test_needs_fk=True,
            )

        def test_to_metadata():
            meta2 = MetaData()
            table_c = table.tometadata(meta2)
            table2_c = table2.tometadata(meta2)
            return (table_c, table2_c)

        def test_pickle():
            meta.bind = testing.db
            meta2 = pickle.loads(pickle.dumps(meta))
            assert meta2.bind is None
            pickle.loads(pickle.dumps(meta2))
            return (meta2.tables['mytable'], meta2.tables['othertable'])

        def test_pickle_via_reflect():
            # this is the most common use case, pickling the results of a
            # database reflection
            meta2 = MetaData(bind=testing.db)
            t1 = Table('mytable', meta2, autoload=True)
            Table('othertable', meta2, autoload=True)
            meta3 = pickle.loads(pickle.dumps(meta2))
            assert meta3.bind is None
            assert meta3.tables['mytable'] is not t1

            return (meta3.tables['mytable'], meta3.tables['othertable'])

        meta.create_all(testing.db)
        try:
            for test, has_constraints, reflect in \
                    (test_to_metadata, True, False), \
                    (test_pickle, True, False), \
                    (test_pickle_via_reflect, False, True):
                table_c, table2_c = test()
                self.assert_tables_equal(table, table_c)
                self.assert_tables_equal(table2, table2_c)
                assert table is not table_c
                assert table.primary_key is not table_c.primary_key
                assert list(table2_c.c.myid.foreign_keys)[0].column \
                    is table_c.c.myid
                assert list(table2_c.c.myid.foreign_keys)[0].column \
                    is not table.c.myid
                assert 'x' in str(table_c.c.foo.server_default.arg)
                if not reflect:
                    assert isinstance(table_c.c.myid.default, Sequence)
                    assert str(table_c.c.foo.server_onupdate.arg) == 'q'
                    assert str(table_c.c.bar.default.arg) == 'y'
                    assert getattr(table_c.c.bar.onupdate.arg, 'arg',
                                   table_c.c.bar.onupdate.arg) == 'z'
                    assert isinstance(table2_c.c.id.default, Sequence)

                # constraints dont get reflected for any dialect right
                # now

                if has_constraints:
                    for c in table_c.c.description.constraints:
                        if isinstance(c, CheckConstraint):
                            break
                    else:
                        assert False
                    assert str(c.sqltext) == "description='hi'"
                    for c in table_c.constraints:
                        if isinstance(c, UniqueConstraint):
                            break
                    else:
                        assert False
                    assert c.columns.contains_column(table_c.c.name)
                    assert not c.columns.contains_column(table.c.name)


        finally:
            meta.drop_all(testing.db)

    def test_col_key_fk_parent_tometadata(self):
        # test #2643
        m1 = MetaData()
        a = Table('a', m1, Column('x', Integer))
        b = Table('b', m1, Column('x', Integer, ForeignKey('a.x'), key='y'))
        assert b.c.y.references(a.c.x)

        m2 = MetaData()
        b2 = b.tometadata(m2)
        a2 = a.tometadata(m2)
        assert b2.c.y.references(a2.c.x)


    def test_pickle_metadata_sequence_restated(self):
        m1 = MetaData()
        Table('a', m1,
             Column('id', Integer, primary_key=True),
             Column('x', Integer, Sequence("x_seq")))

        m2 = pickle.loads(pickle.dumps(m1))

        s2 = Sequence("x_seq")
        t2 = Table('a', m2,
             Column('id', Integer, primary_key=True),
             Column('x', Integer, s2),
             extend_existing=True)

        assert m2._sequences['x_seq'] is t2.c.x.default
        assert m2._sequences['x_seq'] is s2


    def test_sequence_restated_replaced(self):
        """Test restatement of Sequence replaces."""

        m1 = MetaData()
        s1 = Sequence("x_seq")
        t = Table('a', m1,
             Column('x', Integer, s1)
        )
        assert m1._sequences['x_seq'] is s1

        s2 = Sequence('x_seq')
        Table('a', m1,
             Column('x', Integer, s2),
             extend_existing=True
        )
        assert t.c.x.default is s2
        assert m1._sequences['x_seq'] is s2


    def test_pickle_metadata_sequence_implicit(self):
        m1 = MetaData()
        Table('a', m1,
             Column('id', Integer, primary_key=True),
             Column('x', Integer, Sequence("x_seq")))

        m2 = pickle.loads(pickle.dumps(m1))

        t2 = Table('a', m2, extend_existing=True)

        eq_(m2._sequences, {'x_seq': t2.c.x.default})

    def test_pickle_metadata_schema(self):
        m1 = MetaData()
        Table('a', m1,
             Column('id', Integer, primary_key=True),
             Column('x', Integer, Sequence("x_seq")),
             schema='y')

        m2 = pickle.loads(pickle.dumps(m1))

        Table('a', m2, schema='y',
             extend_existing=True)

        eq_(m2._schemas, m1._schemas)

    def test_tometadata_with_schema(self):
        meta = MetaData()

        table = Table('mytable', meta,
            Column('myid', Integer, primary_key=True),
            Column('name', String(40), nullable=True),
            Column('description', String(30),
                            CheckConstraint("description='hi'")),
            UniqueConstraint('name'),
            test_needs_fk=True,
        )

        table2 = Table('othertable', meta,
            Column('id', Integer, primary_key=True),
            Column('myid', Integer, ForeignKey('mytable.myid')),
            test_needs_fk=True,
            )

        meta2 = MetaData()
        table_c = table.tometadata(meta2, schema='someschema')
        table2_c = table2.tometadata(meta2, schema='someschema')

        eq_(str(table_c.join(table2_c).onclause), str(table_c.c.myid
            == table2_c.c.myid))
        eq_(str(table_c.join(table2_c).onclause),
            'someschema.mytable.myid = someschema.othertable.myid')

    def test_tometadata_with_default_schema(self):
        meta = MetaData()

        table = Table('mytable', meta,
            Column('myid', Integer, primary_key=True),
            Column('name', String(40), nullable=True),
            Column('description', String(30),
                        CheckConstraint("description='hi'")),
            UniqueConstraint('name'),
            test_needs_fk=True,
            schema='myschema',
        )

        table2 = Table('othertable', meta,
            Column('id', Integer, primary_key=True),
            Column('myid', Integer, ForeignKey('myschema.mytable.myid')),
            test_needs_fk=True,
            schema='myschema',
            )

        meta2 = MetaData()
        table_c = table.tometadata(meta2)
        table2_c = table2.tometadata(meta2)

        eq_(str(table_c.join(table2_c).onclause), str(table_c.c.myid
            == table2_c.c.myid))
        eq_(str(table_c.join(table2_c).onclause),
            'myschema.mytable.myid = myschema.othertable.myid')


    def test_tometadata_kwargs(self):
        meta = MetaData()

        table = Table('mytable', meta,
            Column('myid', Integer, primary_key=True),
            mysql_engine='InnoDB',
        )

        meta2 = MetaData()
        table_c = table.tometadata(meta2)

        eq_(table.kwargs, table_c.kwargs)

    def test_tometadata_indexes(self):
        meta = MetaData()

        table = Table('mytable', meta,
            Column('id', Integer, primary_key=True),
            Column('data1', Integer, index=True),
            Column('data2', Integer),
        )
        Index('multi', table.c.data1, table.c.data2),

        meta2 = MetaData()
        table_c = table.tometadata(meta2)

        def _get_key(i):
            return [i.name, i.unique] + \
                    sorted(i.kwargs.items()) + \
                    list(i.columns.keys())

        eq_(
            sorted([_get_key(i) for i in table.indexes]),
            sorted([_get_key(i) for i in table_c.indexes])
        )

    @emits_warning("Table '.+' already exists within the given MetaData")
    def test_tometadata_already_there(self):

        meta1 = MetaData()
        table1 = Table('mytable', meta1,
            Column('myid', Integer, primary_key=True),
        )
        meta2 = MetaData()
        table2 = Table('mytable', meta2,
            Column('yourid', Integer, primary_key=True),
        )

        table_c = table1.tometadata(meta2)
        table_d = table2.tometadata(meta2)

        # d'oh!
        assert table_c is table_d

    def test_metadata_schema_arg(self):
        m1 = MetaData(schema='sch1')
        m2 = MetaData(schema='sch1', quote_schema=True)
        m3 = MetaData(schema='sch1', quote_schema=False)
        m4 = MetaData()

        for i, (name, metadata, schema, quote_schema,
                        exp_schema, exp_quote_schema) in enumerate([
                                ('t1', m1, None, None, 'sch1', None),
                                ('t2', m1, 'sch2', None, 'sch2', None),
                                ('t3', m1, 'sch2', True, 'sch2', True),
                                ('t4', m1, 'sch1', None, 'sch1', None),
                                ('t1', m2, None, None, 'sch1', True),
                                ('t2', m2, 'sch2', None, 'sch2', None),
                                ('t3', m2, 'sch2', True, 'sch2', True),
                                ('t4', m2, 'sch1', None, 'sch1', None),
                                ('t1', m3, None, None, 'sch1', False),
                                ('t2', m3, 'sch2', None, 'sch2', None),
                                ('t3', m3, 'sch2', True, 'sch2', True),
                                ('t4', m3, 'sch1', None, 'sch1', None),
                                ('t1', m4, None, None, None, None),
                                ('t2', m4, 'sch2', None, 'sch2', None),
                                ('t3', m4, 'sch2', True, 'sch2', True),
                                ('t4', m4, 'sch1', None, 'sch1', None),
                        ]):
            kw = {}
            if schema is not None:
                kw['schema'] = schema
            if quote_schema is not None:
                kw['quote_schema'] = quote_schema
            t = Table(name, metadata, **kw)
            eq_(t.schema, exp_schema, "test %d, table schema" % i)
            eq_(t.schema.quote if t.schema is not None else None,
                            exp_quote_schema,
                            "test %d, table quote_schema" % i)
            seq = Sequence(name, metadata=metadata, **kw)
            eq_(seq.schema, exp_schema, "test %d, seq schema" % i)
            eq_(seq.schema.quote if seq.schema is not None else None,
                            exp_quote_schema,
                            "test %d, seq quote_schema" % i)

    def test_manual_dependencies(self):
        meta = MetaData()
        a = Table('a', meta, Column('foo', Integer))
        b = Table('b', meta, Column('foo', Integer))
        c = Table('c', meta, Column('foo', Integer))
        d = Table('d', meta, Column('foo', Integer))
        e = Table('e', meta, Column('foo', Integer))

        e.add_is_dependent_on(c)
        a.add_is_dependent_on(b)
        b.add_is_dependent_on(d)
        e.add_is_dependent_on(b)
        c.add_is_dependent_on(a)
        eq_(
            meta.sorted_tables,
            [d, b, a, c, e]
        )

    def test_tometadata_default_schema_metadata(self):
        meta = MetaData(schema='myschema')

        table = Table('mytable', meta,
            Column('myid', Integer, primary_key=True),
            Column('name', String(40), nullable=True),
            Column('description', String(30), CheckConstraint("description='hi'")),
            UniqueConstraint('name'),
            test_needs_fk=True
        )

        table2 = Table('othertable', meta,
            Column('id', Integer, primary_key=True),
            Column('myid', Integer, ForeignKey('myschema.mytable.myid')),
            test_needs_fk=True
            )

        meta2 = MetaData(schema='someschema')
        table_c = table.tometadata(meta2, schema=None)
        table2_c = table2.tometadata(meta2, schema=None)

        eq_(str(table_c.join(table2_c).onclause),
                str(table_c.c.myid == table2_c.c.myid))
        eq_(str(table_c.join(table2_c).onclause),
                "someschema.mytable.myid = someschema.othertable.myid")

    def test_tometadata_strip_schema(self):
        meta = MetaData()

        table = Table('mytable', meta,
            Column('myid', Integer, primary_key=True),
            Column('name', String(40), nullable=True),
            Column('description', String(30),
                        CheckConstraint("description='hi'")),
            UniqueConstraint('name'),
            test_needs_fk=True,
        )

        table2 = Table('othertable', meta,
            Column('id', Integer, primary_key=True),
            Column('myid', Integer, ForeignKey('mytable.myid')),
            test_needs_fk=True,
            )

        meta2 = MetaData()
        table_c = table.tometadata(meta2, schema=None)
        table2_c = table2.tometadata(meta2, schema=None)

        eq_(str(table_c.join(table2_c).onclause), str(table_c.c.myid
            == table2_c.c.myid))
        eq_(str(table_c.join(table2_c).onclause),
            'mytable.myid = othertable.myid')

    def test_nonexistent(self):
        assert_raises(tsa.exc.NoSuchTableError, Table,
                          'fake_table',
                          MetaData(testing.db), autoload=True)

    def test_assorted_repr(self):
        t1 = Table("foo", MetaData(), Column("x", Integer))
        i1 = Index("bar", t1.c.x)
        ck = schema.CheckConstraint("x > y", name="someconstraint")

        for const, exp in (
            (Sequence("my_seq"),
                "Sequence('my_seq')"),
            (Sequence("my_seq", start=5),
                "Sequence('my_seq', start=5)"),
            (Column("foo", Integer),
                "Column('foo', Integer(), table=None)"),
            (Table("bar", MetaData(), Column("x", String)),
                "Table('bar', MetaData(bind=None), "
                "Column('x', String(), table=<bar>), schema=None)"),
            (schema.DefaultGenerator(for_update=True),
                "DefaultGenerator(for_update=True)"),
            (schema.Index("bar", "c"), "Index('bar')"),
            (i1, "Index('bar', Column('x', Integer(), table=<foo>))"),
            (schema.FetchedValue(), "FetchedValue()"),
            (ck,
                    "CheckConstraint("
                    "%s"
                    ", name='someconstraint')" % repr(ck.sqltext)),
        ):
            eq_(
                repr(const),
                exp
            )

class TableTest(fixtures.TestBase, AssertsCompiledSQL):
    @testing.skip_if('mssql', 'different col format')
    def test_prefixes(self):
        from sqlalchemy import Table
        table1 = Table("temporary_table_1", MetaData(),
                      Column("col1", Integer),
                      prefixes=["TEMPORARY"])

        self.assert_compile(
            schema.CreateTable(table1),
            "CREATE TEMPORARY TABLE temporary_table_1 (col1 INTEGER)"
        )

        table2 = Table("temporary_table_2", MetaData(),
                      Column("col1", Integer),
                      prefixes=["VIRTUAL"])
        self.assert_compile(
            schema.CreateTable(table2),
            "CREATE VIRTUAL TABLE temporary_table_2 (col1 INTEGER)"
        )

    def test_table_info(self):
        metadata = MetaData()
        t1 = Table('foo', metadata, info={'x': 'y'})
        t2 = Table('bar', metadata, info={})
        t3 = Table('bat', metadata)
        assert t1.info == {'x': 'y'}
        assert t2.info == {}
        assert t3.info == {}
        for t in (t1, t2, t3):
            t.info['bar'] = 'zip'
            assert t.info['bar'] == 'zip'

    def test_c_immutable(self):
        m = MetaData()
        t1 = Table('t', m, Column('x', Integer), Column('y', Integer))
        assert_raises(
            TypeError,
            t1.c.extend, [Column('z', Integer)]
        )

        def assign():
            t1.c['z'] = Column('z', Integer)
        assert_raises(
            TypeError,
            assign
        )

        def assign2():
            t1.c.z = Column('z', Integer)
        assert_raises(
            TypeError,
            assign2
        )

    def test_autoincrement_replace(self):
        m = MetaData()

        t = Table('t', m,
            Column('id', Integer, primary_key=True)
        )

        is_(t._autoincrement_column, t.c.id)

        t = Table('t', m,
            Column('id', Integer, primary_key=True),
            extend_existing=True
        )
        is_(t._autoincrement_column, t.c.id)

class SchemaTypeTest(fixtures.TestBase):
    class MyType(sqltypes.SchemaType, sqltypes.TypeEngine):
        column = None
        table = None
        evt_targets = ()

        def _set_table(self, column, table):
            super(SchemaTypeTest.MyType, self)._set_table(column, table)
            self.column = column
            self.table = table

        def _on_table_create(self, target, bind, **kw):
            self.evt_targets += (target,)

    def test_independent_schema(self):
        m = MetaData()
        type_ = self.MyType(schema="q")
        t1 = Table('x', m, Column("y", type_), schema="z")
        eq_(t1.c.y.type.schema, "q")

    def test_inherit_schema(self):
        m = MetaData()
        type_ = self.MyType(schema="q", inherit_schema=True)
        t1 = Table('x', m, Column("y", type_), schema="z")
        eq_(t1.c.y.type.schema, "z")

    def test_independent_schema_enum(self):
        m = MetaData()
        type_ = sqltypes.Enum("a", schema="q")
        t1 = Table('x', m, Column("y", type_), schema="z")
        eq_(t1.c.y.type.schema, "q")

    def test_inherit_schema_enum(self):
        m = MetaData()
        type_ = sqltypes.Enum("a", "b", "c", schema="q", inherit_schema=True)
        t1 = Table('x', m, Column("y", type_), schema="z")
        eq_(t1.c.y.type.schema, "z")

    def test_tometadata_copy_type(self):
        m1 = MetaData()

        type_ = self.MyType()
        t1 = Table('x', m1, Column("y", type_))

        m2 = MetaData()
        t2 = t1.tometadata(m2)

        # metadata isn't set
        is_(t2.c.y.type.metadata, None)

        # our test type sets table, though
        is_(t2.c.y.type.table, t2)

    def test_tometadata_independent_schema(self):
        m1 = MetaData()

        type_ = self.MyType()
        t1 = Table('x', m1, Column("y", type_))

        m2 = MetaData()
        t2 = t1.tometadata(m2, schema="bar")

        eq_(t2.c.y.type.schema, None)

    def test_tometadata_inherit_schema(self):
        m1 = MetaData()

        type_ = self.MyType(inherit_schema=True)
        t1 = Table('x', m1, Column("y", type_))

        m2 = MetaData()
        t2 = t1.tometadata(m2, schema="bar")

        eq_(t1.c.y.type.schema, None)
        eq_(t2.c.y.type.schema, "bar")

    def test_tometadata_independent_events(self):
        m1 = MetaData()

        type_ = self.MyType()
        t1 = Table('x', m1, Column("y", type_))

        m2 = MetaData()
        t2 = t1.tometadata(m2)

        t1.dispatch.before_create(t1, testing.db)
        eq_(t1.c.y.type.evt_targets, (t1,))
        eq_(t2.c.y.type.evt_targets, ())

        t2.dispatch.before_create(t2, testing.db)
        t2.dispatch.before_create(t2, testing.db)
        eq_(t1.c.y.type.evt_targets, (t1,))
        eq_(t2.c.y.type.evt_targets, (t2, t2))



class SchemaTest(fixtures.TestBase, AssertsCompiledSQL):

    def test_default_schema_metadata_fk(self):
        m = MetaData(schema="foo")
        t1 = Table('t1', m, Column('x', Integer))
        t2 = Table('t2', m, Column('x', Integer, ForeignKey('t1.x')))
        assert t2.c.x.references(t1.c.x)

    def test_ad_hoc_schema_equiv_fk(self):
        m = MetaData()
        t1 = Table('t1', m, Column('x', Integer), schema="foo")
        t2 = Table('t2', m, Column('x', Integer, ForeignKey('t1.x')), schema="foo")
        assert_raises(
            exc.NoReferencedTableError,
            lambda: t2.c.x.references(t1.c.x)
        )

    def test_default_schema_metadata_fk_alt_remote(self):
        m = MetaData(schema="foo")
        t1 = Table('t1', m, Column('x', Integer))
        t2 = Table('t2', m, Column('x', Integer, ForeignKey('t1.x')),
                                schema="bar")
        assert t2.c.x.references(t1.c.x)

    def test_default_schema_metadata_fk_alt_local_raises(self):
        m = MetaData(schema="foo")
        t1 = Table('t1', m, Column('x', Integer), schema="bar")
        t2 = Table('t2', m, Column('x', Integer, ForeignKey('t1.x')))
        assert_raises(
            exc.NoReferencedTableError,
            lambda: t2.c.x.references(t1.c.x)
        )

    def test_default_schema_metadata_fk_alt_local(self):
        m = MetaData(schema="foo")
        t1 = Table('t1', m, Column('x', Integer), schema="bar")
        t2 = Table('t2', m, Column('x', Integer, ForeignKey('bar.t1.x')))
        assert t2.c.x.references(t1.c.x)

    def test_create_drop_schema(self):

        self.assert_compile(
            schema.CreateSchema("sa_schema"),
            "CREATE SCHEMA sa_schema"
        )
        self.assert_compile(
            schema.DropSchema("sa_schema"),
            "DROP SCHEMA sa_schema"
        )
        self.assert_compile(
            schema.DropSchema("sa_schema", cascade=True),
            "DROP SCHEMA sa_schema CASCADE"
        )

    def test_iteration(self):
        metadata = MetaData()
        table1 = Table('table1', metadata, Column('col1', Integer,
                       primary_key=True), schema='someschema')
        table2 = Table('table2', metadata, Column('col1', Integer,
                       primary_key=True), Column('col2', Integer,
                       ForeignKey('someschema.table1.col1')),
                       schema='someschema')

        t1 = str(schema.CreateTable(table1).compile(bind=testing.db))
        t2 = str(schema.CreateTable(table2).compile(bind=testing.db))
        if testing.db.dialect.preparer(testing.db.dialect).omit_schema:
            assert t1.index("CREATE TABLE table1") > -1
            assert t2.index("CREATE TABLE table2") > -1
        else:
            assert t1.index("CREATE TABLE someschema.table1") > -1
            assert t2.index("CREATE TABLE someschema.table2") > -1


class UseExistingTest(fixtures.TablesTest):
    @classmethod
    def define_tables(cls, metadata):
        Table('users', metadata,
                    Column('id', Integer, primary_key=True),
                    Column('name', String(30)))

    def _useexisting_fixture(self):
        meta2 = MetaData(testing.db)
        Table('users', meta2, autoload=True)
        return meta2

    def _notexisting_fixture(self):
        return MetaData(testing.db)

    def test_exception_no_flags(self):
        meta2 = self._useexisting_fixture()
        def go():
            Table('users', meta2, Column('name',
                          Unicode), autoload=True)
        assert_raises_message(
            exc.InvalidRequestError,
                "Table 'users' is already defined for this "\
                "MetaData instance.",
            go
        )

    @testing.uses_deprecated
    def test_deprecated_useexisting(self):
        meta2 = self._useexisting_fixture()
        users = Table('users', meta2, Column('name', Unicode),
                      autoload=True, useexisting=True)
        assert isinstance(users.c.name.type, Unicode)
        assert not users.quote
        users = Table('users', meta2, quote=True, autoload=True,
                      useexisting=True)
        assert users.quote

    def test_keep_plus_existing_raises(self):
        meta2 = self._useexisting_fixture()
        assert_raises(
            exc.ArgumentError,
            Table, 'users', meta2, keep_existing=True,
                extend_existing=True
        )

    @testing.uses_deprecated
    def test_existing_plus_useexisting_raises(self):
        meta2 = self._useexisting_fixture()
        assert_raises(
            exc.ArgumentError,
            Table, 'users', meta2, useexisting=True,
                extend_existing=True
        )

    def test_keep_existing_no_dupe_constraints(self):
        meta2 = self._notexisting_fixture()
        users = Table('users', meta2,
            Column('id', Integer),
            Column('name', Unicode),
            UniqueConstraint('name'),
            keep_existing=True
        )
        assert 'name' in users.c
        assert 'id' in users.c
        eq_(len(users.constraints), 2)

        u2 = Table('users', meta2,
            Column('id', Integer),
            Column('name', Unicode),
            UniqueConstraint('name'),
            keep_existing=True
        )
        eq_(len(u2.constraints), 2)

    def test_extend_existing_dupes_constraints(self):
        meta2 = self._notexisting_fixture()
        users = Table('users', meta2,
            Column('id', Integer),
            Column('name', Unicode),
            UniqueConstraint('name'),
            extend_existing=True
        )
        assert 'name' in users.c
        assert 'id' in users.c
        eq_(len(users.constraints), 2)

        u2 = Table('users', meta2,
            Column('id', Integer),
            Column('name', Unicode),
            UniqueConstraint('name'),
            extend_existing=True
        )
        # constraint got duped
        eq_(len(u2.constraints), 3)

    def test_keep_existing_coltype(self):
        meta2 = self._useexisting_fixture()
        users = Table('users', meta2, Column('name', Unicode),
                      autoload=True, keep_existing=True)
        assert not isinstance(users.c.name.type, Unicode)

    def test_keep_existing_quote(self):
        meta2 = self._useexisting_fixture()
        users = Table('users', meta2, quote=True, autoload=True,
                      keep_existing=True)
        assert not users.name.quote

    def test_keep_existing_add_column(self):
        meta2 = self._useexisting_fixture()
        users = Table('users', meta2,
                        Column('foo', Integer),
                        autoload=True,
                      keep_existing=True)
        assert "foo" not in users.c

    def test_keep_existing_coltype_no_orig(self):
        meta2 = self._notexisting_fixture()
        users = Table('users', meta2, Column('name', Unicode),
                      autoload=True, keep_existing=True)
        assert isinstance(users.c.name.type, Unicode)

    def test_keep_existing_quote_no_orig(self):
        meta2 = self._notexisting_fixture()
        users = Table('users', meta2, quote=True,
                        autoload=True,
                      keep_existing=True)
        assert users.name.quote

    def test_keep_existing_add_column_no_orig(self):
        meta2 = self._notexisting_fixture()
        users = Table('users', meta2,
                        Column('foo', Integer),
                        autoload=True,
                      keep_existing=True)
        assert "foo" in users.c

    def test_keep_existing_coltype_no_reflection(self):
        meta2 = self._useexisting_fixture()
        users = Table('users', meta2, Column('name', Unicode),
                      keep_existing=True)
        assert not isinstance(users.c.name.type, Unicode)

    def test_keep_existing_quote_no_reflection(self):
        meta2 = self._useexisting_fixture()
        users = Table('users', meta2, quote=True,
                      keep_existing=True)
        assert not users.name.quote

    def test_keep_existing_add_column_no_reflection(self):
        meta2 = self._useexisting_fixture()
        users = Table('users', meta2,
                        Column('foo', Integer),
                      keep_existing=True)
        assert "foo" not in users.c

    def test_extend_existing_coltype(self):
        meta2 = self._useexisting_fixture()
        users = Table('users', meta2, Column('name', Unicode),
                      autoload=True, extend_existing=True)
        assert isinstance(users.c.name.type, Unicode)

    def test_extend_existing_quote(self):
        meta2 = self._useexisting_fixture()
        assert_raises_message(
            tsa.exc.ArgumentError,
            "Can't redefine 'quote' or 'quote_schema' arguments",
            Table, 'users', meta2, quote=True, autoload=True,
                      extend_existing=True
        )

    def test_extend_existing_add_column(self):
        meta2 = self._useexisting_fixture()
        users = Table('users', meta2,
                        Column('foo', Integer),
                        autoload=True,
                      extend_existing=True)
        assert "foo" in users.c

    def test_extend_existing_coltype_no_orig(self):
        meta2 = self._notexisting_fixture()
        users = Table('users', meta2, Column('name', Unicode),
                      autoload=True, extend_existing=True)
        assert isinstance(users.c.name.type, Unicode)

    def test_extend_existing_quote_no_orig(self):
        meta2 = self._notexisting_fixture()
        users = Table('users', meta2, quote=True,
                        autoload=True,
                      extend_existing=True)
        assert users.name.quote

    def test_extend_existing_add_column_no_orig(self):
        meta2 = self._notexisting_fixture()
        users = Table('users', meta2,
                        Column('foo', Integer),
                        autoload=True,
                      extend_existing=True)
        assert "foo" in users.c

    def test_extend_existing_coltype_no_reflection(self):
        meta2 = self._useexisting_fixture()
        users = Table('users', meta2, Column('name', Unicode),
                      extend_existing=True)
        assert isinstance(users.c.name.type, Unicode)

    def test_extend_existing_quote_no_reflection(self):
        meta2 = self._useexisting_fixture()
        assert_raises_message(
            tsa.exc.ArgumentError,
            "Can't redefine 'quote' or 'quote_schema' arguments",
            Table, 'users', meta2, quote=True,
                      extend_existing=True
        )

    def test_extend_existing_add_column_no_reflection(self):
        meta2 = self._useexisting_fixture()
        users = Table('users', meta2,
                        Column('foo', Integer),
                      extend_existing=True)
        assert "foo" in users.c

class ConstraintTest(fixtures.TestBase):
    def _single_fixture(self):
        m = MetaData()

        t1 = Table('t1', m,
            Column('a', Integer),
            Column('b', Integer)
        )

        t2 = Table('t2', m,
            Column('a', Integer, ForeignKey('t1.a'))
        )

        t3 = Table('t3', m,
            Column('a', Integer)
        )
        return t1, t2, t3

    def test_table_references(self):
        t1, t2, t3 = self._single_fixture()
        assert list(t2.c.a.foreign_keys)[0].references(t1)
        assert not list(t2.c.a.foreign_keys)[0].references(t3)

    def test_column_references(self):
        t1, t2, t3 = self._single_fixture()
        assert t2.c.a.references(t1.c.a)
        assert not t2.c.a.references(t3.c.a)
        assert not t2.c.a.references(t1.c.b)

    def test_column_references_derived(self):
        t1, t2, t3 = self._single_fixture()
        s1 = tsa.select([tsa.select([t1]).alias()])
        assert t2.c.a.references(s1.c.a)
        assert not t2.c.a.references(s1.c.b)

    def test_copy_doesnt_reference(self):
        t1, t2, t3 = self._single_fixture()
        a2 = t2.c.a.copy()
        assert not a2.references(t1.c.a)
        assert not a2.references(t1.c.b)

    def test_derived_column_references(self):
        t1, t2, t3 = self._single_fixture()
        s1 = tsa.select([tsa.select([t2]).alias()])
        assert s1.c.a.references(t1.c.a)
        assert not s1.c.a.references(t1.c.b)

    def test_related_column_not_present_atfirst_ok(self):
        m = MetaData()
        base_table = Table("base", m,
            Column("id", Integer, primary_key=True)
        )
        fk = ForeignKey('base.q')
        derived_table = Table("derived", m,
            Column("id", None, fk,
                primary_key=True),
        )

        base_table.append_column(Column('q', Integer))
        assert fk.column is base_table.c.q
        assert isinstance(derived_table.c.id.type, Integer)

    def test_invalid_composite_fk_check_strings(self):
        m = MetaData()

        assert_raises_message(
            exc.ArgumentError,
            r"ForeignKeyConstraint on t1\(x, y\) refers to "
                "multiple remote tables: t2 and t3",
            Table,
            't1', m, Column('x', Integer), Column('y', Integer),
            ForeignKeyConstraint(['x', 'y'], ['t2.x', 't3.y'])
        )

    def test_invalid_composite_fk_check_columns(self):
        m = MetaData()

        t2 = Table('t2', m, Column('x', Integer))
        t3 = Table('t3', m, Column('y', Integer))

        assert_raises_message(
            exc.ArgumentError,
            r"ForeignKeyConstraint on t1\(x, y\) refers to "
                "multiple remote tables: t2 and t3",
            Table,
            't1', m, Column('x', Integer), Column('y', Integer),
            ForeignKeyConstraint(['x', 'y'], [t2.c.x, t3.c.y])
        )

    def test_invalid_composite_fk_check_columns_notattached(self):
        m = MetaData()
        x = Column('x', Integer)
        y = Column('y', Integer)

        # no error is raised for this one right now.
        # which is a minor bug.
        Table('t1', m, Column('x', Integer), Column('y', Integer),
                ForeignKeyConstraint(['x', 'y'], [x, y])
            )

        t2 = Table('t2', m, x)
        t3 = Table('t3', m, y)

    def test_constraint_copied_to_proxy_ok(self):
        m = MetaData()
        t1 = Table('t1', m, Column('id', Integer, primary_key=True))
        t2 = Table('t2', m, Column('id', Integer, ForeignKey('t1.id'),
                        primary_key=True))

        s = tsa.select([t2])
        t2fk = list(t2.c.id.foreign_keys)[0]
        sfk = list(s.c.id.foreign_keys)[0]

        # the two FKs share the ForeignKeyConstraint
        is_(
            t2fk.constraint,
            sfk.constraint
        )

        # but the ForeignKeyConstraint isn't
        # aware of the select's FK
        eq_(
            t2fk.constraint.elements,
            [t2fk]
        )

    def test_type_propagate_composite_fk_string(self):
        metadata = MetaData()
        a = Table('a', metadata,
                  Column('key1', Integer, primary_key=True),
                  Column('key2', String(40), primary_key=True))

        b = Table('b', metadata,
                  Column('a_key1', None),
                  Column('a_key2', None),
                  Column('id', Integer, primary_key=True),
                  ForeignKeyConstraint(['a_key1', 'a_key2'],
                                       ['a.key1', 'a.key2'])
                  )

        assert isinstance(b.c.a_key1.type, Integer)
        assert isinstance(b.c.a_key2.type, String)

    def test_type_propagate_composite_fk_col(self):
        metadata = MetaData()
        a = Table('a', metadata,
                  Column('key1', Integer, primary_key=True),
                  Column('key2', String(40), primary_key=True))

        b = Table('b', metadata,
                  Column('a_key1', None),
                  Column('a_key2', None),
                  Column('id', Integer, primary_key=True),
                  ForeignKeyConstraint(['a_key1', 'a_key2'],
                                       [a.c.key1, a.c.key2])
                  )

        assert isinstance(b.c.a_key1.type, Integer)
        assert isinstance(b.c.a_key2.type, String)

    def test_type_propagate_standalone_fk_string(self):
        metadata = MetaData()
        a = Table('a', metadata,
                  Column('key1', Integer, primary_key=True))

        b = Table('b', metadata,
                  Column('a_key1', None, ForeignKey("a.key1")),
                  )

        assert isinstance(b.c.a_key1.type, Integer)

    def test_type_propagate_standalone_fk_col(self):
        metadata = MetaData()
        a = Table('a', metadata,
                  Column('key1', Integer, primary_key=True))

        b = Table('b', metadata,
                  Column('a_key1', None, ForeignKey(a.c.key1)),
                  )

        assert isinstance(b.c.a_key1.type, Integer)

    def test_type_propagate_chained_string_source_first(self):
        metadata = MetaData()
        a = Table('a', metadata,
                  Column('key1', Integer, primary_key=True))

        b = Table('b', metadata,
                  Column('a_key1', None, ForeignKey("a.key1")),
                  )

        c = Table('c', metadata,
                  Column('b_key1', None, ForeignKey("b.a_key1")),
                  )

        assert isinstance(b.c.a_key1.type, Integer)
        assert isinstance(c.c.b_key1.type, Integer)

    def test_type_propagate_chained_string_source_last(self):
        metadata = MetaData()

        b = Table('b', metadata,
                  Column('a_key1', None, ForeignKey("a.key1")),
                  )

        c = Table('c', metadata,
                  Column('b_key1', None, ForeignKey("b.a_key1")),
                  )

        a = Table('a', metadata,
                  Column('key1', Integer, primary_key=True))

        assert isinstance(b.c.a_key1.type, Integer)
        assert isinstance(c.c.b_key1.type, Integer)

    def test_type_propagate_chained_col_orig_first(self):
        metadata = MetaData()
        a = Table('a', metadata,
                  Column('key1', Integer, primary_key=True))

        b = Table('b', metadata,
                  Column('a_key1', None, ForeignKey(a.c.key1)),
                  )

        c = Table('c', metadata,
                  Column('b_key1', None, ForeignKey(b.c.a_key1)),
                  )

        assert isinstance(b.c.a_key1.type, Integer)
        assert isinstance(c.c.b_key1.type, Integer)

    def test_column_accessor_col(self):
        c1 = Column('x', Integer)
        fk = ForeignKey(c1)
        is_(fk.column, c1)

    def test_column_accessor_clause_element(self):
        c1 = Column('x', Integer)

        class CThing(object):
            def __init__(self, c):
                self.c = c
            def __clause_element__(self):
                return self.c

        fk = ForeignKey(CThing(c1))
        is_(fk.column, c1)

    def test_column_accessor_string_no_parent(self):
        fk = ForeignKey("sometable.somecol")
        assert_raises_message(
            exc.InvalidRequestError,
            "this ForeignKey object does not yet have a parent "
            "Column associated with it.",
            getattr, fk, "column"
        )

    def test_column_accessor_string_no_parent_table(self):
        fk = ForeignKey("sometable.somecol")
        c1 = Column('x', fk)
        assert_raises_message(
            exc.InvalidRequestError,
            "this ForeignKey's parent column is not yet "
            "associated with a Table.",
            getattr, fk, "column"
        )

    def test_column_accessor_string_no_target_table(self):
        fk = ForeignKey("sometable.somecol")
        c1 = Column('x', fk)
        t1 = Table('t', MetaData(), c1)
        assert_raises_message(
            exc.NoReferencedTableError,
            "Foreign key associated with column 't.x' could not find "
            "table 'sometable' with which to generate a "
            "foreign key to target column 'somecol'",
            getattr, fk, "column"
        )

    def test_column_accessor_string_no_target_column(self):
        fk = ForeignKey("sometable.somecol")
        c1 = Column('x', fk)
        m = MetaData()
        t1 = Table('t', m, c1)
        t2 = Table("sometable", m, Column('notsomecol', Integer))
        assert_raises_message(
            exc.NoReferencedColumnError,
            "Could not initialize target column for ForeignKey "
            "'sometable.somecol' on table 't': "
            "table 'sometable' has no column named 'somecol'",
            getattr, fk, "column"
        )

    def test_remove_table_fk_bookkeeping(self):
        metadata = MetaData()
        fk = ForeignKey('t1.x')
        t2 = Table('t2', metadata, Column('y', Integer, fk))
        t3 = Table('t3', metadata, Column('y', Integer, ForeignKey('t1.x')))

        assert t2.key in metadata.tables
        assert ("t1", "x") in metadata._fk_memos

        metadata.remove(t2)

        # key is removed
        assert t2.key not in metadata.tables

        # the memo for the FK is still there
        assert ("t1", "x") in metadata._fk_memos

        # fk is not in the collection
        assert fk not in metadata._fk_memos[("t1", "x")]

        # make the referenced table
        t1 = Table('t1', metadata, Column('x', Integer))

        # t2 tells us exactly what's wrong
        assert_raises_message(
            exc.InvalidRequestError,
            "Table t2 is no longer associated with its parent MetaData",
            getattr, fk, "column"
        )

        # t3 is unaffected
        assert t3.c.y.references(t1.c.x)

        # remove twice OK
        metadata.remove(t2)


class ColumnDefinitionTest(AssertsCompiledSQL, fixtures.TestBase):
    """Test Column() construction."""

    __dialect__ = 'default'

    def columns(self):
        return [Column(Integer),
                 Column('b', Integer),
                 Column(Integer),
                 Column('d', Integer),
                 Column(Integer, name='e'),
                 Column(type_=Integer),
                 Column(Integer()),
                 Column('h', Integer()),
                 Column(type_=Integer())]

    def test_basic(self):
        c = self.columns()

        for i, v in ((0, 'a'), (2, 'c'), (5, 'f'), (6, 'g'), (8, 'i')):
            c[i].name = v
            c[i].key = v
        del i, v

        tbl = Table('table', MetaData(), *c)

        for i, col in enumerate(tbl.c):
            assert col.name == c[i].name

    def test_name_none(self):

        c = Column(Integer)
        assert_raises_message(
            exc.ArgumentError,
            "Column must be constructed with a non-blank name or assign a "
            "non-blank .name ",
            Table, 't', MetaData(), c)

    def test_name_blank(self):

        c = Column('', Integer)
        assert_raises_message(
            exc.ArgumentError,
            "Column must be constructed with a non-blank name or assign a "
            "non-blank .name ",
            Table, 't', MetaData(), c)

    def test_dupe_column(self):
        c = Column('x', Integer)
        Table('t', MetaData(), c)

        assert_raises_message(
            exc.ArgumentError,
            "Column object already assigned to Table 't'",
            Table, 'q', MetaData(), c)

    def test_incomplete_key(self):
        c = Column(Integer)
        assert c.name is None
        assert c.key is None

        c.name = 'named'
        Table('t', MetaData(), c)

        assert c.name == 'named'
        assert c.name == c.key


    def test_bogus(self):
        assert_raises(exc.ArgumentError, Column, 'foo', name='bar')
        assert_raises(exc.ArgumentError, Column, 'foo', Integer,
                          type_=Integer())

    def test_custom_subclass_proxy(self):
        """test proxy generation of a Column subclass, can be compiled."""

        from sqlalchemy.schema import Column
        from sqlalchemy.ext.compiler import compiles
        from sqlalchemy.sql import select

        class MyColumn(Column):
            def _constructor(self, name, type, **kw):
                kw['name'] = name
                return MyColumn(type, **kw)

            def __init__(self, type, **kw):
                Column.__init__(self, type, **kw)

            def my_goofy_thing(self):
                return "hi"

        @compiles(MyColumn)
        def goofy(element, compiler, **kw):
            s = compiler.visit_column(element, **kw)
            return s + "-"

        id = MyColumn(Integer, primary_key=True)
        id.name = 'id'
        name = MyColumn(String)
        name.name = 'name'
        t1 = Table('foo', MetaData(),
            id,
            name
        )

        # goofy thing
        eq_(t1.c.name.my_goofy_thing(), "hi")

        # create proxy
        s = select([t1.select().alias()])

        # proxy has goofy thing
        eq_(s.c.name.my_goofy_thing(), "hi")

        # compile works
        self.assert_compile(
            select([t1.select().alias()]),
            "SELECT anon_1.id-, anon_1.name- FROM "
            "(SELECT foo.id- AS id, foo.name- AS name "
            "FROM foo) AS anon_1",
        )

    def test_custom_subclass_proxy_typeerror(self):
        from sqlalchemy.schema import Column
        from sqlalchemy.sql import select

        class MyColumn(Column):
            def __init__(self, type, **kw):
                Column.__init__(self, type, **kw)

        id = MyColumn(Integer, primary_key=True)
        id.name = 'id'
        name = MyColumn(String)
        name.name = 'name'
        t1 = Table('foo', MetaData(),
            id,
            name
        )
        assert_raises_message(
            TypeError,
            "Could not create a copy of this <class "
            "'test.sql.test_metadata..*MyColumn'> "
            "object.  Ensure the class includes a _constructor()",
            getattr, select([t1.select().alias()]), 'c'
        )

    def test_custom_create(self):
        from sqlalchemy.ext.compiler import compiles, deregister

        @compiles(schema.CreateColumn)
        def compile(element, compiler, **kw):
            column = element.element

            if "special" not in column.info:
                return compiler.visit_create_column(element, **kw)

            text = "%s SPECIAL DIRECTIVE %s" % (
                    column.name,
                    compiler.type_compiler.process(column.type)
                )
            default = compiler.get_column_default_string(column)
            if default is not None:
                text += " DEFAULT " + default

            if not column.nullable:
                text += " NOT NULL"

            if column.constraints:
                text += " ".join(
                            compiler.process(const)
                            for const in column.constraints)
            return text

        t = Table('mytable', MetaData(),
                Column('x', Integer, info={"special": True}, primary_key=True),
                Column('y', String(50)),
                Column('z', String(20), info={"special": True})
            )

        self.assert_compile(
            schema.CreateTable(t),
            "CREATE TABLE mytable (x SPECIAL DIRECTIVE INTEGER "
                "NOT NULL, y VARCHAR(50), "
                "z SPECIAL DIRECTIVE VARCHAR(20), PRIMARY KEY (x))"
        )

        deregister(schema.CreateColumn)

class ColumnDefaultsTest(fixtures.TestBase):
    """test assignment of default fixures to columns"""

    def _fixture(self, *arg, **kw):
        return Column('x', Integer, *arg, **kw)

    def test_server_default_positional(self):
        target = schema.DefaultClause('y')
        c = self._fixture(target)
        assert c.server_default is target
        assert target.column is c

    def test_onupdate_default_not_server_default_one(self):
        target1 = schema.DefaultClause('y')
        target2 = schema.DefaultClause('z')

        c = self._fixture(server_default=target1, server_onupdate=target2)
        eq_(c.server_default.arg, 'y')
        eq_(c.server_onupdate.arg, 'z')

    def test_onupdate_default_not_server_default_two(self):
        target1 = schema.DefaultClause('y', for_update=True)
        target2 = schema.DefaultClause('z', for_update=True)

        c = self._fixture(server_default=target1, server_onupdate=target2)
        eq_(c.server_default.arg, 'y')
        eq_(c.server_onupdate.arg, 'z')

    def test_onupdate_default_not_server_default_three(self):
        target1 = schema.DefaultClause('y', for_update=False)
        target2 = schema.DefaultClause('z', for_update=True)

        c = self._fixture(target1, target2)
        eq_(c.server_default.arg, 'y')
        eq_(c.server_onupdate.arg, 'z')

    def test_onupdate_default_not_server_default_four(self):
        target1 = schema.DefaultClause('y', for_update=False)

        c = self._fixture(server_onupdate=target1)
        is_(c.server_default, None)
        eq_(c.server_onupdate.arg, 'y')

    def test_server_default_keyword_as_schemaitem(self):
        target = schema.DefaultClause('y')
        c = self._fixture(server_default=target)
        assert c.server_default is target
        assert target.column is c

    def test_server_default_keyword_as_clause(self):
        target = 'y'
        c = self._fixture(server_default=target)
        assert c.server_default.arg == target
        assert c.server_default.column is c

    def test_server_default_onupdate_positional(self):
        target = schema.DefaultClause('y', for_update=True)
        c = self._fixture(target)
        assert c.server_onupdate is target
        assert target.column is c

    def test_server_default_onupdate_keyword_as_schemaitem(self):
        target = schema.DefaultClause('y', for_update=True)
        c = self._fixture(server_onupdate=target)
        assert c.server_onupdate is target
        assert target.column is c

    def test_server_default_onupdate_keyword_as_clause(self):
        target = 'y'
        c = self._fixture(server_onupdate=target)
        assert c.server_onupdate.arg == target
        assert c.server_onupdate.column is c

    def test_column_default_positional(self):
        target = schema.ColumnDefault('y')
        c = self._fixture(target)
        assert c.default is target
        assert target.column is c

    def test_column_default_keyword_as_schemaitem(self):
        target = schema.ColumnDefault('y')
        c = self._fixture(default=target)
        assert c.default is target
        assert target.column is c

    def test_column_default_keyword_as_clause(self):
        target = 'y'
        c = self._fixture(default=target)
        assert c.default.arg == target
        assert c.default.column is c

    def test_column_default_onupdate_positional(self):
        target = schema.ColumnDefault('y', for_update=True)
        c = self._fixture(target)
        assert c.onupdate is target
        assert target.column is c

    def test_column_default_onupdate_keyword_as_schemaitem(self):
        target = schema.ColumnDefault('y', for_update=True)
        c = self._fixture(onupdate=target)
        assert c.onupdate is target
        assert target.column is c

    def test_column_default_onupdate_keyword_as_clause(self):
        target = 'y'
        c = self._fixture(onupdate=target)
        assert c.onupdate.arg == target
        assert c.onupdate.column is c

class ColumnOptionsTest(fixtures.TestBase):

    def test_default_generators(self):
        g1, g2 = Sequence('foo_id_seq'), ColumnDefault('f5')
        assert Column(String, default=g1).default is g1
        assert Column(String, onupdate=g1).onupdate is g1
        assert Column(String, default=g2).default is g2
        assert Column(String, onupdate=g2).onupdate is g2

    def _null_type_error(self, col):
        t = Table('t', MetaData(), col)
        assert_raises_message(
            exc.CompileError,
            r"\(in table 't', column 'foo'\): Can't generate DDL for NullType",
            schema.CreateTable(t).compile
        )

    def _no_name_error(self, col):
        assert_raises_message(
            exc.ArgumentError,
            "Column must be constructed with a non-blank name or "
            "assign a non-blank .name",
            Table, 't', MetaData(), col
        )

    def _no_error(self, col):
        m = MetaData()
        b = Table('bar', m, Column('id', Integer))
        t = Table('t', m, col)
        schema.CreateTable(t).compile()

    def test_argument_signatures(self):
        self._no_name_error(Column())
        self._null_type_error(Column("foo"))
        self._no_name_error(Column(default="foo"))

        self._no_name_error(Column(Sequence("a")))
        self._null_type_error(Column("foo", default="foo"))

        self._null_type_error(Column("foo", Sequence("a")))

        self._no_name_error(Column(ForeignKey('bar.id')))

        self._no_error(Column("foo", ForeignKey('bar.id')))

        self._no_name_error(Column(ForeignKey('bar.id'), default="foo"))

        self._no_name_error(Column(ForeignKey('bar.id'), Sequence("a")))
        self._no_error(Column("foo", ForeignKey('bar.id'), default="foo"))
        self._no_error(Column("foo", ForeignKey('bar.id'), Sequence("a")))


    def test_column_info(self):

        c1 = Column('foo', String, info={'x': 'y'})
        c2 = Column('bar', String, info={})
        c3 = Column('bat', String)
        assert c1.info == {'x': 'y'}
        assert c2.info == {}
        assert c3.info == {}

        for c in (c1, c2, c3):
            c.info['bar'] = 'zip'
            assert c.info['bar'] == 'zip'


class CatchAllEventsTest(fixtures.TestBase):

    def teardown(self):
        events.SchemaEventTarget.dispatch._clear()

    def test_all_events(self):
        canary = []
        def before_attach(obj, parent):
            canary.append("%s->%s" % (obj.__class__.__name__,
                                parent.__class__.__name__))

        def after_attach(obj, parent):
            canary.append("%s->%s" % (obj.__class__.__name__, parent))

        event.listen(schema.SchemaItem, "before_parent_attach", before_attach)
        event.listen(schema.SchemaItem, "after_parent_attach", after_attach)

        m = MetaData()
        Table('t1', m,
            Column('id', Integer, Sequence('foo_id'), primary_key=True),
            Column('bar', String, ForeignKey('t2.id'))
        )
        Table('t2', m,
            Column('id', Integer, primary_key=True),
        )

        eq_(
            canary,
            ['Sequence->Column', 'Sequence->id', 'ForeignKey->Column',
             'ForeignKey->bar', 'Table->MetaData',
             'PrimaryKeyConstraint->Table', 'PrimaryKeyConstraint->t1',
             'Column->Table', 'Column->t1', 'Column->Table',
             'Column->t1', 'ForeignKeyConstraint->Table',
             'ForeignKeyConstraint->t1', 'Table->MetaData(bind=None)',
             'Table->MetaData', 'PrimaryKeyConstraint->Table',
             'PrimaryKeyConstraint->t2', 'Column->Table', 'Column->t2',
             'Table->MetaData(bind=None)']
        )

    def test_events_per_constraint(self):
        canary = []

        def evt(target):
            def before_attach(obj, parent):
                canary.append("%s->%s" % (target.__name__,
                                        parent.__class__.__name__))

            def after_attach(obj, parent):
                canary.append("%s->%s" % (target.__name__, parent))
            event.listen(target, "before_parent_attach", before_attach)
            event.listen(target, "after_parent_attach", after_attach)

        for target in [
            schema.ForeignKeyConstraint, schema.PrimaryKeyConstraint,
            schema.UniqueConstraint,
            schema.CheckConstraint
        ]:
            evt(target)

        m = MetaData()
        Table('t1', m,
            Column('id', Integer, Sequence('foo_id'), primary_key=True),
            Column('bar', String, ForeignKey('t2.id')),
            Column('bat', Integer, unique=True),
        )
        Table('t2', m,
            Column('id', Integer, primary_key=True),
            Column('bar', Integer),
            Column('bat', Integer),
            CheckConstraint("bar>5"),
            UniqueConstraint('bar', 'bat')
        )
        eq_(
            canary,
            [
                'PrimaryKeyConstraint->Table', 'PrimaryKeyConstraint->t1',
                'ForeignKeyConstraint->Table', 'ForeignKeyConstraint->t1',
                'UniqueConstraint->Table', 'UniqueConstraint->t1',
                'PrimaryKeyConstraint->Table', 'PrimaryKeyConstraint->t2',
                'CheckConstraint->Table', 'CheckConstraint->t2',
                'UniqueConstraint->Table', 'UniqueConstraint->t2'
            ]
        )
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.