summaryrefslogtreecommitdiff
path: root/lib/sqlalchemy/schema.py
blob: 2e5a1a6371e94fa34d24108ab401eb796bde7b25 (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
# schema.py
# Copyright (C) 2005, 2006, 2007, 2008, 2009 Michael Bayer mike_mp@zzzcomputing.com
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php

"""The schema module provides the building blocks for database metadata.

Each element within this module describes a database entity which can be
created and dropped, or is otherwise part of such an entity.  Examples include
tables, columns, sequences, and indexes.

All entities are subclasses of :class:`~sqlalchemy.schema.SchemaItem`, and as defined
in this module they are intended to be agnostic of any vendor-specific
constructs.

A collection of entities are grouped into a unit called
:class:`~sqlalchemy.schema.MetaData`.  MetaData serves as a logical grouping of schema
elements, and can also be associated with an actual database connection such
that operations involving the contained elements can contact the database as
needed.

Two of the elements here also build upon their "syntactic" counterparts, which
are defined in :class:`~sqlalchemy.sql.expression.`, specifically
:class:`~sqlalchemy.schema.Table` and :class:`~sqlalchemy.schema.Column`.  Since these objects
are part of the SQL expression language, they are usable as components in SQL
expressions.

"""
import re, inspect
from sqlalchemy import exc, util, dialects
from sqlalchemy.sql import expression, visitors

URL = None

__all__ = ['SchemaItem', 'Table', 'Column', 'ForeignKey', 'Sequence', 'Index',
           'ForeignKeyConstraint', 'PrimaryKeyConstraint', 'CheckConstraint',
           'UniqueConstraint', 'DefaultGenerator', 'Constraint', 'MetaData',
           'ThreadLocalMetaData', 'SchemaVisitor', 'PassiveDefault',
           'DefaultClause', 'FetchedValue', 'ColumnDefault', 'DDL',
           'CreateTable', 'DropTable', 'CreateSequence', 'DropSequence',
           'AddConstraint', 'DropConstraint',
           ]
__all__.sort()

class SchemaItem(visitors.Visitable):
    """Base class for items that define a database schema."""

    __visit_name__ = 'schema_item'
    quote = None

    def _init_items(self, *args):
        """Initialize the list of child items for this SchemaItem."""

        for item in args:
            if item is not None:
                item._set_parent(self)

    def _set_parent(self, parent):
        """Associate with this SchemaItem's parent object."""

        raise NotImplementedError()

    def get_children(self, **kwargs):
        """used to allow SchemaVisitor access"""
        return []

    def __repr__(self):
        return "%s()" % self.__class__.__name__

    @util.memoized_property
    def info(self):
        return {}

def _get_table_key(name, schema):
    if schema is None:
        return name
    else:
        return schema + "." + name

class Table(SchemaItem, expression.TableClause):
    """Represent a table in a database.
    
    e.g.::
    
        mytable = Table("mytable", metadata, 
                        Column('mytable_id', Integer, primary_key=True),
                        Column('value', String(50))
                   )

    The Table object constructs a unique instance of itself based on its
    name within the given MetaData object.   Constructor
    arguments are as follows:
    
    :param name: The name of this table as represented in the database. 

        This property, along with the *schema*, indicates the *singleton
        identity* of this table in relation to its parent :class:`MetaData`.
        Additional calls to :class:`Table` with the same name, metadata,
        and schema name will return the same :class:`Table` object.

        Names which contain no upper case characters
        will be treated as case insensitive names, and will not be quoted
        unless they are a reserved word.  Names with any number of upper
        case characters will be quoted and sent exactly.  Note that this
        behavior applies even for databases which standardize upper 
        case names as case insensitive such as Oracle.

    :param metadata: a :class:`MetaData` object which will contain this 
        table.  The metadata is used as a point of association of this table
        with other tables which are referenced via foreign key.  It also
        may be used to associate this table with a particular 
        :class:`~sqlalchemy.engine.base.Connectable`.

    :param \*args: Additional positional arguments are used primarily
        to add the list of :class:`Column` objects contained within this table.
        Similar to the style of a CREATE TABLE statement, other :class:`SchemaItem`
        constructs may be added here, including :class:`PrimaryKeyConstraint`,
        and :class:`ForeignKeyConstraint`.
        
    :param autoload: Defaults to False: the Columns for this table should be reflected
        from the database.  Usually there will be no Column objects in the
        constructor if this property is set.

    :param autoload_with: If autoload==True, this is an optional Engine or Connection
        instance to be used for the table reflection.  If ``None``, the
        underlying MetaData's bound connectable will be used.

    :param implicit_returning: True by default - indicates that 
        RETURNING can be used by default to fetch newly inserted primary key 
        values, for backends which support this.  Note that 
        create_engine() also provides an implicit_returning flag.

    :param include_columns: A list of strings indicating a subset of columns to be loaded via
        the ``autoload`` operation; table columns who aren't present in
        this list will not be represented on the resulting ``Table``
        object.  Defaults to ``None`` which indicates all columns should
        be reflected.

    :param info: A dictionary which defaults to ``{}``.  A space to store application 
        specific data. This must be a dictionary.

    :param mustexist: When ``True``, indicates that this Table must already 
        be present in the given :class:`MetaData`` collection.

    :param prefixes:
        A list of strings to insert after CREATE in the CREATE TABLE
        statement.  They will be separated by spaces.

    :param quote: Force quoting of this table's name on or off, corresponding
        to ``True`` or ``False``.  When left at its default of ``None``,
        the column identifier will be quoted according to whether the name is
        case sensitive (identifiers with at least one upper case character are 
        treated as case sensitive), or if it's a reserved word.  This flag 
        is only needed to force quoting of a reserved word which is not known
        by the SQLAlchemy dialect.

    :param quote_schema: same as 'quote' but applies to the schema identifier.

    :param schema: The *schema name* for this table, which is required if the table
        resides in a schema other than the default selected schema for the
        engine's database connection.  Defaults to ``None``.

    :param useexisting: When ``True``, indicates that if this Table is already
        present in the given :class:`MetaData`, apply further arguments within
        the constructor to the existing :class:`Table`.  If this flag is not 
        set, an error is raised when the parameters of an existing :class:`Table`
        are overwritten.

    """
    
    __visit_name__ = 'table'

    ddl_events = ('before-create', 'after-create', 'before-drop', 'after-drop')

    def __new__(cls, *args, **kw):
        if not args:
            # python3k pickle seems to call this
            return object.__new__(cls)
            
        try:
            name, metadata, args = args[0], args[1], args[2:]
        except IndexError:
            raise TypeError("Table() takes at least two arguments")
        
        schema = kw.get('schema', None)
        useexisting = kw.pop('useexisting', False)
        mustexist = kw.pop('mustexist', False)
        key = _get_table_key(name, schema)
        if key in metadata.tables:
            if not useexisting and bool(args):
                raise exc.InvalidRequestError(
                    "Table '%s' is already defined for this MetaData instance.  "
                    "Specify 'useexisting=True' to redefine options and "
                    "columns on an existing Table object." % key)
            table = metadata.tables[key]
            table._init_existing(*args, **kw)
            return table
        else:
            if mustexist:
                raise exc.InvalidRequestError(
                    "Table '%s' not defined" % (key))
            metadata.tables[key] = table = object.__new__(cls)
            try:
                table._init(name, metadata, *args, **kw)
                return table
            except:
                metadata.tables.pop(key)
                raise
                
    def __init__(self, *args, **kw):
        # __init__ is overridden to prevent __new__ from 
        # calling the superclass constructor.
        pass
        
    def _init(self, name, metadata, *args, **kwargs):
        super(Table, self).__init__(name)
        self.metadata = metadata
        self.schema = kwargs.pop('schema', None)
        self.indexes = set()
        self.constraints = set()
        self._columns = expression.ColumnCollection()
        self._set_primary_key(PrimaryKeyConstraint())
        self._foreign_keys = util.OrderedSet()
        self.ddl_listeners = util.defaultdict(list)
        self.kwargs = {}
        if self.schema is not None:
            self.fullname = "%s.%s" % (self.schema, self.name)
        else:
            self.fullname = self.name

        autoload = kwargs.pop('autoload', False)
        autoload_with = kwargs.pop('autoload_with', None)
        include_columns = kwargs.pop('include_columns', None)

        self.implicit_returning = kwargs.pop('implicit_returning', True)
        self.quote = kwargs.pop('quote', None)
        self.quote_schema = kwargs.pop('quote_schema', None)
        if 'info' in kwargs:
            self.info = kwargs.pop('info')

        self._prefixes = kwargs.pop('prefixes', [])

        self._extra_kwargs(**kwargs)

        # load column definitions from the database if 'autoload' is defined
        # we do it after the table is in the singleton dictionary to support
        # circular foreign keys
        if autoload:
            if autoload_with:
                autoload_with.reflecttable(self, include_columns=include_columns)
            else:
                _bind_or_error(metadata).reflecttable(self, include_columns=include_columns)

        # initialize all the column, etc. objects.  done after reflection to
        # allow user-overrides
        self._init_items(*args)

    def _init_existing(self, *args, **kwargs):
        autoload = kwargs.pop('autoload', False)
        autoload_with = kwargs.pop('autoload_with', None)
        schema = kwargs.pop('schema', None)
        if schema and schema != self.schema:
            raise exc.ArgumentError(
                "Can't change schema of existing table from '%s' to '%s'",
                (self.schema, schema))

        include_columns = kwargs.pop('include_columns', None)
        if include_columns:
            for c in self.c:
                if c.name not in include_columns:
                    self.c.remove(c)

        for key in ('quote', 'quote_schema'):
            if key in kwargs:
                setattr(self, key, kwargs.pop(key))

        if 'info' in kwargs:
            self.info = kwargs.pop('info')

        self._extra_kwargs(**kwargs)
        self._init_items(*args)

    def _extra_kwargs(self, **kwargs):
        # validate remaining kwargs that they all specify DB prefixes
        if len([k for k in kwargs
                if not re.match(r'^(?:%s)_' % '|'.join(dialects.__all__), k)]):
            raise TypeError(
                "Invalid argument(s) for Table: %r" % kwargs.keys())
        self.kwargs.update(kwargs)

    def _set_primary_key(self, pk):
        if getattr(self, '_primary_key', None) in self.constraints:
            self.constraints.remove(self._primary_key)
        self._primary_key = pk
        self.constraints.add(pk)

        for c in pk.columns:
            c.primary_key = True

    @util.memoized_property
    def _autoincrement_column(self):
        for col in self.primary_key:
            if col.autoincrement and \
                isinstance(col.type, types.Integer) and \
                not col.foreign_keys and \
                isinstance(col.default, (type(None), Sequence)):

                return col

    @property
    def key(self):
        return _get_table_key(self.name, self.schema)

    @property
    def primary_key(self):
        return self._primary_key

    def __repr__(self):
        return "Table(%s)" % ', '.join(
            [repr(self.name)] + [repr(self.metadata)] +
            [repr(x) for x in self.columns] +
            ["%s=%s" % (k, repr(getattr(self, k))) for k in ['schema']])

    def __str__(self):
        return _get_table_key(self.description, self.schema)

    @property
    def bind(self):
        """Return the connectable associated with this Table."""

        return self.metadata and self.metadata.bind or None

    def append_column(self, column):
        """Append a ``Column`` to this ``Table``."""

        column._set_parent(self)

    def append_constraint(self, constraint):
        """Append a ``Constraint`` to this ``Table``."""

        constraint._set_parent(self)

    def append_ddl_listener(self, event, listener):
        """Append a DDL event listener to this ``Table``.

        The ``listener`` callable will be triggered when this ``Table`` is
        created or dropped, either directly before or after the DDL is issued
        to the database.  The listener may modify the Table, but may not abort
        the event itself.

        Arguments are:

        event
          One of ``Table.ddl_events``; e.g. 'before-create', 'after-create',
          'before-drop' or 'after-drop'.

        listener
          A callable, invoked with three positional arguments:

          event
            The event currently being handled
          target
            The ``Table`` object being created or dropped
          bind
            The ``Connection`` bueing used for DDL execution.

        Listeners are added to the Table's ``ddl_listeners`` attribute.
        """

        if event not in self.ddl_events:
            raise LookupError(event)
        self.ddl_listeners[event].append(listener)

    def _set_parent(self, metadata):
        metadata.tables[_get_table_key(self.name, self.schema)] = self
        self.metadata = metadata

    def get_children(self, column_collections=True, schema_visitor=False, **kwargs):
        if not schema_visitor:
            return expression.TableClause.get_children(
                self, column_collections=column_collections, **kwargs)
        else:
            if column_collections:
                return list(self.columns)
            else:
                return []

    def exists(self, bind=None):
        """Return True if this table exists."""

        if bind is None:
            bind = _bind_or_error(self)

        def do(conn):
            return conn.dialect.has_table(conn, self.name, schema=self.schema)
        return bind.run_callable(do)

    def create(self, bind=None, checkfirst=False):
        """Issue a ``CREATE`` statement for this table.

        See also ``metadata.create_all()``.
        """
        self.metadata.create_all(bind=bind, checkfirst=checkfirst, tables=[self])

    def drop(self, bind=None, checkfirst=False):
        """Issue a ``DROP`` statement for this table.

        See also ``metadata.drop_all()``.
        """
        self.metadata.drop_all(bind=bind, checkfirst=checkfirst, tables=[self])

    def tometadata(self, metadata, schema=None):
        """Return a copy of this ``Table`` associated with a different ``MetaData``."""

        try:
            if not schema:
                schema = self.schema
            key = _get_table_key(self.name, schema)
            return metadata.tables[key]
        except KeyError:
            args = []
            for c in self.columns:
                args.append(c.copy(schema=schema))
            for c in self.constraints:
                args.append(c.copy(schema=schema))
            return Table(self.name, metadata, schema=schema, *args)

class Column(SchemaItem, expression.ColumnClause):
    """Represents a column in a database table."""

    __visit_name__ = 'column'
    
    def __init__(self, *args, **kwargs):
        """
        Construct a new ``Column`` object.
        
        :param name: The name of this column as represented in the database. 
          This argument may be the first positional argument, or specified
          via keyword.
          
          Names which contain no upper case characters
          will be treated as case insensitive names, and will not be quoted
          unless they are a reserved word.  Names with any number of upper
          case characters will be quoted and sent exactly.  Note that this
          behavior applies even for databases which standardize upper 
          case names as case insensitive such as Oracle.
          
          The name field may be omitted at construction time and applied
          later, at any time before the Column is associated with a 
          :class:`Table`.  This is to support convenient
          usage within the :mod:`~sqlalchemy.ext.declarative` extension.
          
        :param type\_: The column's type, indicated using an instance which 
          subclasses :class:`~sqlalchemy.types.AbstractType`.  If no arguments
          are required for the type, the class of the type can be sent
          as well, e.g.::
          
            # use a type with arguments
            Column('data', String(50))
            
            # use no arguments
            Column('level', Integer)
            
          The ``type`` argument may be the second positional argument
          or specified by keyword.

          If this column also contains a :class:`ForeignKey`,
          the type argument may be left as ``None`` in which case the
          type assigned will be that of the referenced column.

        :param \*args: Additional positional arguments include various 
          :class:`SchemaItem` derived constructs which will be applied 
          as options to the column.  These include instances of 
          :class:`Constraint`, :class:`ForeignKey`, :class:`ColumnDefault`, 
          and :class:`Sequence`.  In some cases an equivalent keyword 
          argument is available such as ``server_default``, ``default``
          and ``unique``.

        :param autoincrement: This flag may be set to ``False`` to 
          indicate an integer primary key column that should not be
          considered to be the "autoincrement" column, that is
          the integer primary key column which generates values 
          implicitly upon INSERT and whose value is usually returned
          via the DBAPI cursor.lastrowid attribute.   It defaults
          to ``True`` to satisfy the common use case of a table
          with a single integer primary key column.  If the table
          has a composite primary key consisting of more than one
          integer column, set this flag to True only on the 
          column that should be considered "autoincrement".
          
          The setting *only* has an effect for columns which are:
          
          * Integer derived (i.e. INT, SMALLINT, BIGINT)
          
          * Part of the primary key
          
          * Are not referenced by any foreign keys
          
          * have no server side or client side defaults (with the exception
            of Postgresql SERIAL).
            
          The setting has these two effects on columns that meet the
          above criteria:
          
          * DDL issued for the column will include database-specific
            keywords intended to signify this column as an
            "autoincrement" column, such as AUTO INCREMENT on MySQL,
            SERIAL on Postgresql, and IDENTITY on MS-SQL.  It does 
            *not* issue AUTOINCREMENT for SQLite since this is a
            special SQLite flag that is not required for autoincrementing
            behavior.
            
          * The column will be considered to be available as 
            cursor.lastrowid or equivalent, for those dialects which
            "post fetch" newly inserted identifiers after a row has
            been inserted (SQLite, MySQL, MS-SQL).  It does not have 
            any effect in this regard for databases that use sequences 
            to generate primary key identifiers (i.e. Firebird, Postgresql, 
            Oracle).

        :param default: A scalar, Python callable, or :class:`~sqlalchemy.sql.expression.ClauseElement`
          representing the *default value* for this column, which will be
          invoked upon insert if this column is otherwise not specified
          in the VALUES clause of the insert.  This is a shortcut
          to using :class:`ColumnDefault` as a positional argument.
          
          Contrast this argument to ``server_default`` which creates a 
          default generator on the database side.
        
        :param key: An optional string identifier which will identify this ``Column`` 
            object on the :class:`Table`.  When a key is provided, this is the
            only identifier referencing the ``Column`` within the application,
            including ORM attribute mapping; the ``name`` field is used only
            when rendering SQL.

        :param index: When ``True``, indicates that the column is indexed.
          This is a shortcut for using a :class:`Index` construct on the table.
          To specify indexes with explicit names or indexes that contain multiple 
          columns, use the :class:`Index` construct instead.

        :param info: A dictionary which defaults to ``{}``.  A space to store application 
          specific data. This must be a dictionary.

        :param nullable: If set to the default of ``True``, indicates the column
            will be rendered as allowing NULL, else it's rendered as NOT NULL.
            This parameter is only used when issuing CREATE TABLE statements.

        :param onupdate: A scalar, Python callable, or :class:`~sqlalchemy.sql.expression.ClauseElement`
            representing a default value to be applied to the column within UPDATE
            statements, which wil be invoked upon update if this column is not present
            in the SET clause of the update.  This is a shortcut to using 
            :class:`ColumnDefault` as a positional argument with ``for_update=True``.
            
        :param primary_key: If ``True``, marks this column as a primary key
            column.  Multiple columns can have this flag set to specify composite
            primary keys.  As an alternative, the primary key of a :class:`Table` can
            be specified via an explicit :class:`PrimaryKeyConstraint` object.

        :param server_default: A :class:`FetchedValue` instance, str, Unicode or
          :func:`~sqlalchemy.sql.expression.text` construct representing 
          the DDL DEFAULT value for the column.

          String types will be emitted as-is, surrounded by single quotes::

              Column('x', Text, server_default="val")

              x TEXT DEFAULT 'val'

          A :func:`~sqlalchemy.sql.expression.text` expression will be 
          rendered as-is, without quotes::

              Column('y', DateTime, server_default=text('NOW()'))0

              y DATETIME DEFAULT NOW()

          Strings and text() will be converted into a :class:`DefaultClause`
          object upon initialization.
          
          Use :class:`FetchedValue` to indicate that an already-existing column will generate
          a default value on the database side which will be available to SQLAlchemy 
          for post-fetch after inserts.  
          This construct does not specify any DDL and the implementation is 
          left to the database, such as via a trigger.

        :param server_onupdate:   A :class:`FetchedValue` instance representing 
            a database-side default generation function.  This indicates to 
            SQLAlchemy that a newly generated value will be available after updates.
            This construct does not specify any DDL and the implementation is 
            left to the database, such as via a trigger.

        :param quote: Force quoting of this column's name on or off, corresponding
           to ``True`` or ``False``.  When left at its default of ``None``,
           the column identifier will be quoted according to whether the name is
           case sensitive (identifiers with at least one upper case character are 
           treated as case sensitive), or if it's a reserved word.  This flag 
           is only needed to force quoting of a reserved word which is not known
           by the SQLAlchemy dialect.

        :param unique: When ``True``, indicates that this column contains a unique
            constraint, or if ``index`` is ``True`` as well, indicates that the
            :class:`Index` should be created with the unique flag.  To specify multiple
            columns in the constraint/index or to specify an explicit name,
            use the :class:`UniqueConstraint` or :class:`Index` constructs explicitly.

        """

        name = kwargs.pop('name', None)
        type_ = kwargs.pop('type_', None)
        if args:
            args = list(args)
            if isinstance(args[0], basestring):
                if name is not None:
                    raise exc.ArgumentError(
                        "May not pass name positionally and as a keyword.")
                name = args.pop(0)
        if args:
            coltype = args[0]
            
            if (isinstance(coltype, types.AbstractType) or
                (isinstance(coltype, type) and
                 issubclass(coltype, types.AbstractType))):
                if type_ is not None:
                    raise exc.ArgumentError(
                        "May not pass type_ positionally and as a keyword.")
                type_ = args.pop(0)

        super(Column, self).__init__(name, None, type_)
        self.key = kwargs.pop('key', name)
        self.primary_key = kwargs.pop('primary_key', False)
        self.nullable = kwargs.pop('nullable', not self.primary_key)
        self.default = kwargs.pop('default', None)
        self.server_default = kwargs.pop('server_default', None)
        self.server_onupdate = kwargs.pop('server_onupdate', None)
        self.index = kwargs.pop('index', None)
        self.unique = kwargs.pop('unique', None)
        self.quote = kwargs.pop('quote', None)
        self.onupdate = kwargs.pop('onupdate', None)
        self.autoincrement = kwargs.pop('autoincrement', True)
        self.constraints = set()
        self.foreign_keys = util.OrderedSet()
        self._table_events = set()
        
        if isinstance(self.type, types.SchemaType):
            self.type._set_parent(self)
            
        if self.default is not None:
            if isinstance(self.default, (ColumnDefault, Sequence)):
                args.append(self.default)
            else:
                args.append(ColumnDefault(self.default))
        if self.server_default is not None:
            if isinstance(self.server_default, FetchedValue):
                args.append(self.server_default)
            else:
                args.append(DefaultClause(self.server_default))
                
        if self.onupdate is not None:
            args.append(ColumnDefault(self.onupdate, for_update=True))
            
        if self.server_onupdate is not None:
            if isinstance(self.server_onupdate, FetchedValue):
                args.append(self.server_default)
            else:
                args.append(DefaultClause(self.server_onupdate,
                                            for_update=True))
        self._init_items(*args)

        util.set_creation_order(self)

        if 'info' in kwargs:
            self.info = kwargs.pop('info')
            
        if kwargs:
            raise exc.ArgumentError(
                "Unknown arguments passed to Column: " + repr(kwargs.keys()))

    def __str__(self):
        if self.name is None:
            return "(no name)"
        elif self.table is not None:
            if self.table.named_with_column:
                return (self.table.description + "." + self.description)
            else:
                return self.description
        else:
            return self.description

    def references(self, column):
        """Return True if this Column references the given column via foreign key."""
        for fk in self.foreign_keys:
            if fk.references(column.table):
                return True
        else:
            return False

    def append_foreign_key(self, fk):
        fk._set_parent(self)

    def __repr__(self):
        kwarg = []
        if self.key != self.name:
            kwarg.append('key')
        if self.primary_key:
            kwarg.append('primary_key')
        if not self.nullable:
            kwarg.append('nullable')
        if self.onupdate:
            kwarg.append('onupdate')
        if self.default:
            kwarg.append('default')
        if self.server_default:
            kwarg.append('server_default')
        return "Column(%s)" % ', '.join(
            [repr(self.name)] + [repr(self.type)] +
            [repr(x) for x in self.foreign_keys if x is not None] +
            [repr(x) for x in self.constraints] +
            [(self.table is not None and "table=<%s>" % self.table.description or "")] +
            ["%s=%s" % (k, repr(getattr(self, k))) for k in kwarg])

    def _set_parent(self, table):
        if self.name is None:
            raise exc.ArgumentError(
                "Column must be constructed with a name or assign .name "
                "before adding to a Table.")
        if self.key is None:
            self.key = self.name

        if getattr(self, 'table', None) is not None:
            raise exc.ArgumentError("this Column already has a table!")

        if self.key in table._columns:
            col = table._columns.get(self.key)
            for fk in col.foreign_keys:
                col.foreign_keys.remove(fk)
                table.foreign_keys.remove(fk)
                table.constraints.remove(fk.constraint)
            
        table._columns.replace(self)

        if self.primary_key:
            table.primary_key._replace(self)
        elif self.key in table.primary_key:
            raise exc.ArgumentError(
                "Trying to redefine primary-key column '%s' as a "
                "non-primary-key column on table '%s'" % (
                self.key, table.fullname))
        self.table = table

        if self.index:
            if isinstance(self.index, basestring):
                raise exc.ArgumentError(
                    "The 'index' keyword argument on Column is boolean only. "
                    "To create indexes with a specific name, create an "
                    "explicit Index object external to the Table.")
            Index('ix_%s' % self._label, self, unique=self.unique)
        elif self.unique:
            if isinstance(self.unique, basestring):
                raise exc.ArgumentError(
                    "The 'unique' keyword argument on Column is boolean only. "
                    "To create unique constraints or indexes with a specific "
                    "name, append an explicit UniqueConstraint to the Table's "
                    "list of elements, or create an explicit Index object "
                    "external to the Table.")
            table.append_constraint(UniqueConstraint(self.key))

        for fn in self._table_events:
            fn(table, self)
        del self._table_events
    
    def _on_table_attach(self, fn):
        if self.table is not None:
            fn(self.table, self)
        else:
            self._table_events.add(fn)
            
    def copy(self, **kw):
        """Create a copy of this ``Column``, unitialized.

        This is used in ``Table.tometadata``.

        """
        return Column(
                self.name, 
                self.type, 
                self.default, 
                key = self.key, 
                primary_key = self.primary_key, 
                nullable = self.nullable, 
                quote=self.quote, 
                index=self.index, 
                autoincrement=self.autoincrement, 
                default=self.default,
                server_default=self.server_default,
                onupdate=self.onupdate,
                server_onupdate=self.server_onupdate,
                *[c.copy(**kw) for c in self.constraints])

    def _make_proxy(self, selectable, name=None):
        """Create a *proxy* for this column.

        This is a copy of this ``Column`` referenced by a different parent
        (such as an alias or select statement).  The column should
        be used only in select scenarios, as its full DDL/default
        information is not transferred.
        
        """
        fk = [ForeignKey(f.column) for f in self.foreign_keys]
        c = Column(
            name or self.name, 
            self.type, 
            key = name or self.key, 
            primary_key = self.primary_key, 
            nullable = self.nullable, 
            quote=self.quote, *fk)
        c.table = selectable
        c.proxies = [self]
        selectable.columns.add(c)
        if self.primary_key:
            selectable.primary_key.add(c)
        for fn in c._table_events:
            fn(selectable, c)
        del c._table_events
        return c

    def get_children(self, schema_visitor=False, **kwargs):
        if schema_visitor:
            return [x for x in (self.default, self.onupdate) if x is not None] + \
                list(self.foreign_keys) + list(self.constraints)
        else:
            return expression.ColumnClause.get_children(self, **kwargs)


class ForeignKey(SchemaItem):
    """Defines a column-level FOREIGN KEY constraint between two columns.

    ``ForeignKey`` is specified as an argument to a :class:`Column` object,
    e.g.::
    
        t = Table("remote_table", metadata, 
            Column("remote_id", ForeignKey("main_table.id"))
        )

    For a composite (multiple column) FOREIGN KEY, use a
    :class:`ForeignKeyConstraint` object specified at the level of the
    :class:`Table`.
    
    Further examples of foreign key configuration are in
    :ref:`metadata_foreignkeys`.

    """

    __visit_name__ = 'foreign_key'

    def __init__(self, column, _constraint=None, use_alter=False, name=None,
                    onupdate=None, ondelete=None, deferrable=None,
                    initially=None, link_to_name=False):
        """
        Construct a column-level FOREIGN KEY.  
        
        The :class:`ForeignKey` object when constructed generates a
        :class:`ForeignKeyConstraint` which is associated with the parent
        :class:`Table` object's collection of constraints.

        :param column: A single target column for the key relationship. A
            :class:`Column` object or a column name as a string:
            ``tablename.columnkey`` or ``schema.tablename.columnkey``.
            ``columnkey`` is the ``key`` which has been assigned to the column
            (defaults to the column name itself), unless ``link_to_name`` is
            ``True`` in which case the rendered name of the column is used.

        :param name: Optional string. An in-database name for the key if
            `constraint` is not provided.

        :param onupdate: Optional string. If set, emit ON UPDATE <value> when
            issuing DDL for this constraint. Typical values include CASCADE,
            DELETE and RESTRICT.

        :param ondelete: Optional string. If set, emit ON DELETE <value> when
            issuing DDL for this constraint. Typical values include CASCADE,
            DELETE and RESTRICT.

        :param deferrable: Optional bool. If set, emit DEFERRABLE or NOT
            DEFERRABLE when issuing DDL for this constraint.

        :param initially: Optional string. If set, emit INITIALLY <value> when
            issuing DDL for this constraint.
        
        :param link_to_name: if True, the string name given in ``column`` is
            the rendered name of the referenced column, not its locally
            assigned ``key``.
          
        :param use_alter: passed to the underlying
            :class:`ForeignKeyConstraint` to indicate the constraint should be
            generated/dropped externally from the CREATE TABLE/ DROP TABLE
            statement. See that classes' constructor for details.
        
        """

        self._colspec = column
        self.constraint = _constraint
        self.use_alter = use_alter
        self.name = name
        self.onupdate = onupdate
        self.ondelete = ondelete
        self.deferrable = deferrable
        self.initially = initially
        self.link_to_name = link_to_name

    def __repr__(self):
        return "ForeignKey(%r)" % self._get_colspec()

    def copy(self, schema=None):
        """Produce a copy of this ForeignKey object."""

        return ForeignKey(
                self._get_colspec(schema=schema),
                use_alter=self.use_alter,
                name=self.name,
                onupdate=self.onupdate,
                ondelete=self.ondelete,
                deferrable=self.deferrable,
                initially=self.initially,
                link_to_name=self.link_to_name
                )

    def _get_colspec(self, schema=None):
        if schema:
            return schema + "." + self.column.table.name + "." + self.column.key
        elif isinstance(self._colspec, basestring):
            return self._colspec
        elif hasattr(self._colspec, '__clause_element__'):
            _column = self._colspec.__clause_element__()
        else:
            _column = self._colspec
            
        return "%s.%s" % (_column.table.fullname, _column.key)

    target_fullname = property(_get_colspec)

    def references(self, table):
        """Return True if the given table is referenced by this ForeignKey."""
        return table.corresponding_column(self.column) is not None

    def get_referent(self, table):
        """Return the column in the given table referenced by this ForeignKey.

        Returns None if this ``ForeignKey`` does not reference the given table.

        """

        return table.corresponding_column(self.column)

    @util.memoized_property
    def column(self):
        # ForeignKey inits its remote column as late as possible, so tables
        # can be defined without dependencies
        if isinstance(self._colspec, basestring):
            # locate the parent table this foreign key is attached to.  we
            # use the "original" column which our parent column represents
            # (its a list of columns/other ColumnElements if the parent
            # table is a UNION)
            for c in self.parent.base_columns:
                if isinstance(c, Column):
                    parenttable = c.table
                    break
            else:
                raise exc.ArgumentError(
                    "Parent column '%s' does not descend from a "
                    "table-attached Column" % str(self.parent))

            m = self._colspec.split('.')

            if m is None:
                raise exc.ArgumentError(
                    "Invalid foreign key column specification: %s" %
                    self._colspec)

            # A FK between column 'bar' and table 'foo' can be
            # specified as 'foo', 'foo.bar', 'dbo.foo.bar',
            # 'otherdb.dbo.foo.bar'. Once we have the column name and
            # the table name, treat everything else as the schema
            # name. Some databases (e.g. Sybase) support
            # inter-database foreign keys. See tickets#1341 and --
            # indirectly related -- Ticket #594. This assumes that '.'
            # will never appear *within* any component of the FK.

            (schema, tname, colname) = (None, None, None)
            if (len(m) == 1):
                tname   = m.pop()
            else:
                colname = m.pop()
                tname   = m.pop()

            if (len(m) > 0):
                schema = '.'.join(m)

            if _get_table_key(tname, schema) not in parenttable.metadata:
                raise exc.NoReferencedTableError(
                    "Could not find table '%s' with which to generate a "
                    "foreign key" % tname)
            table = Table(tname, parenttable.metadata,
                          mustexist=True, schema=schema)
                          
            _column = None
            if colname is None:
                # colname is None in the case that ForeignKey argument
                # was specified as table name only, in which case we
                # match the column name to the same column on the
                # parent.
                key = self.parent
                _column = table.c.get(self.parent.key, None)
            elif self.link_to_name:
                key = colname
                for c in table.c:
                    if c.name == colname:
                        _column = c
            else:
                key = colname
                _column = table.c.get(colname, None)

            if _column is None:
                raise exc.NoReferencedColumnError(
                    "Could not create ForeignKey '%s' on table '%s': "
                    "table '%s' has no column named '%s'" % (
                    self._colspec, parenttable.name, table.name, key))

        elif hasattr(self._colspec, '__clause_element__'):
            _column = self._colspec.__clause_element__()
        else:
            _column = self._colspec

        # propagate TypeEngine to parent if it didn't have one
        if isinstance(self.parent.type, types.NullType):
            self.parent.type = _column.type
        return _column

    def _set_parent(self, column):
        if hasattr(self, 'parent'):
            if self.parent is column:
                return
            raise exc.InvalidRequestError("This ForeignKey already has a parent !")
        self.parent = column

        self.parent.foreign_keys.add(self)
        self.parent._on_table_attach(self._set_table)
    
    def _set_table(self, table, column):
        if self.constraint is None and isinstance(table, Table):
            self.constraint = ForeignKeyConstraint(
                [], [], use_alter=self.use_alter, name=self.name,
                onupdate=self.onupdate, ondelete=self.ondelete,
                deferrable=self.deferrable, initially=self.initially,
                )
            self.constraint._elements[self.parent] = self
            self.constraint._set_parent(table)
        table.foreign_keys.add(self)
        
class DefaultGenerator(SchemaItem):
    """Base class for column *default* values."""

    __visit_name__ = 'default_generator'

    is_sequence = False
    
    def __init__(self, for_update=False):
        self.for_update = for_update

    def _set_parent(self, column):
        self.column = column
        if self.for_update:
            self.column.onupdate = self
        else:
            self.column.default = self

    def execute(self, bind=None, **kwargs):
        if bind is None:
            bind = _bind_or_error(self)
        return bind._execute_default(self, **kwargs)

    @property
    def bind(self):
        """Return the connectable associated with this default."""
        if getattr(self, 'column', None) is not None:
            return self.column.table.bind
        else:
            return None

    def __repr__(self):
        return "DefaultGenerator()"


class ColumnDefault(DefaultGenerator):
    """A plain default value on a column.

    This could correspond to a constant, a callable function, or a SQL clause.
    """

    def __init__(self, arg, **kwargs):
        super(ColumnDefault, self).__init__(**kwargs)
        if isinstance(arg, FetchedValue):
            raise exc.ArgumentError(
                "ColumnDefault may not be a server-side default type.")
        if util.callable(arg):
            arg = self._maybe_wrap_callable(arg)
        self.arg = arg
    
    @util.memoized_property
    def is_callable(self):
        return util.callable(self.arg)
        
    @util.memoized_property
    def is_clause_element(self):
        return isinstance(self.arg, expression.ClauseElement)
    
    @util.memoized_property
    def is_scalar(self):
        return not self.is_callable and not self.is_clause_element and not self.is_sequence
        
    def _maybe_wrap_callable(self, fn):
        """Backward compat: Wrap callables that don't accept a context."""

        if inspect.isfunction(fn):
            inspectable = fn
        elif inspect.isclass(fn):
            inspectable = fn.__init__
        elif hasattr(fn, '__call__'):
            inspectable = fn.__call__
        else:
            # probably not inspectable, try anyways.
            inspectable = fn
        try:
            argspec = inspect.getargspec(inspectable)
        except TypeError:
            return lambda ctx: fn()

        positionals = len(argspec[0])
        
        # Py3K compat - no unbound methods
        if inspect.ismethod(inspectable) or inspect.isclass(fn):
            positionals -= 1

        if positionals == 0:
            return lambda ctx: fn()

        defaulted = argspec[3] is not None and len(argspec[3]) or 0
        if positionals - defaulted > 1:
            raise exc.ArgumentError(
                "ColumnDefault Python function takes zero or one "
                "positional arguments")
        return fn

    def _visit_name(self):
        if self.for_update:
            return "column_onupdate"
        else:
            return "column_default"
    __visit_name__ = property(_visit_name)

    def __repr__(self):
        return "ColumnDefault(%r)" % self.arg

class Sequence(DefaultGenerator):
    """Represents a named database sequence."""

    __visit_name__ = 'sequence'

    is_sequence = True
    
    def __init__(self, name, start=None, increment=None, schema=None,
                 optional=False, quote=None, metadata=None, for_update=False):
        super(Sequence, self).__init__(for_update=for_update)
        self.name = name
        self.start = start
        self.increment = increment
        self.optional = optional
        self.quote = quote
        self.schema = schema
        self.metadata = metadata

    @util.memoized_property
    def is_callable(self):
        return False

    @util.memoized_property
    def is_clause_element(self):
        return False

    def __repr__(self):
        return "Sequence(%s)" % ', '.join(
            [repr(self.name)] +
            ["%s=%s" % (k, repr(getattr(self, k)))
             for k in ['start', 'increment', 'optional']])

    def _set_parent(self, column):
        super(Sequence, self)._set_parent(column)
        column._on_table_attach(self._set_table)
    
    def _set_table(self, table, column):
        self.metadata = table.metadata
        
    @property
    def bind(self):
        if self.metadata:
            return self.metadata.bind
        else:
            return None
        
    def create(self, bind=None, checkfirst=True):
        """Creates this sequence in the database."""

        if bind is None:
            bind = _bind_or_error(self)
        bind.create(self, checkfirst=checkfirst)

    def drop(self, bind=None, checkfirst=True):
        """Drops this sequence from the database."""

        if bind is None:
            bind = _bind_or_error(self)
        bind.drop(self, checkfirst=checkfirst)


class FetchedValue(object):
    """A default that takes effect on the database side."""

    def __init__(self, for_update=False):
        self.for_update = for_update

    def _set_parent(self, column):
        self.column = column
        if self.for_update:
            self.column.server_onupdate = self
        else:
            self.column.server_default = self

    def __repr__(self):
        return 'FetchedValue(for_update=%r)' % self.for_update


class DefaultClause(FetchedValue):
    """A DDL-specified DEFAULT column value."""

    def __init__(self, arg, for_update=False):
        util.assert_arg_type(arg, (basestring,
                                   expression.ClauseElement,
                                   expression._TextClause), 'arg')
        super(DefaultClause, self).__init__(for_update)
        self.arg = arg

    def __repr__(self):
        return "DefaultClause(%r, for_update=%r)" % (self.arg, self.for_update)

class PassiveDefault(DefaultClause):
    def __init__(self, *arg, **kw):
        util.warn_deprecated("PassiveDefault is deprecated.  Use DefaultClause.")
        DefaultClause.__init__(self, *arg, **kw)

class Constraint(SchemaItem):
    """A table-level SQL constraint."""

    __visit_name__ = 'constraint'

    def __init__(self, name=None, deferrable=None, initially=None, inline_ddl=True):
        """Create a SQL constraint.

        name
          Optional, the in-database name of this ``Constraint``.

        deferrable
          Optional bool.  If set, emit DEFERRABLE or NOT DEFERRABLE when
          issuing DDL for this constraint.

        initially
          Optional string.  If set, emit INITIALLY <value> when issuing DDL
          for this constraint.
          
        inline_ddl
          if True, DDL for this Constraint will be generated within the span of a
          CREATE TABLE or DROP TABLE statement, when the associated table's
          DDL is generated.  if False, no DDL is issued within that process.
          Instead, it is expected that an AddConstraint or DropConstraint 
          construct will be used to issue DDL for this Contraint.
          The AddConstraint/DropConstraint constructs set this flag automatically
          as well.
        """

        self.name = name
        self.deferrable = deferrable
        self.initially = initially
        self.inline_ddl = inline_ddl

    @property
    def table(self):
        try:
            if isinstance(self.parent, Table):
                return self.parent
        except AttributeError:
            pass
        raise exc.InvalidRequestError("This constraint is not bound to a table.  Did you mean to call table.add_constraint(constraint) ?")

    def _set_parent(self, parent):
        self.parent = parent
        parent.constraints.add(self)

    def copy(self, **kw):
        raise NotImplementedError()

class ColumnCollectionConstraint(Constraint):
    """A constraint that proxies a ColumnCollection."""
    
    def __init__(self, *columns, **kw):
        """
        \*columns
          A sequence of column names or Column objects.

        name
          Optional, the in-database name of this constraint.

        deferrable
          Optional bool.  If set, emit DEFERRABLE or NOT DEFERRABLE when
          issuing DDL for this constraint.

        initially
          Optional string.  If set, emit INITIALLY <value> when issuing DDL
          for this constraint.
        
        """
        super(ColumnCollectionConstraint, self).__init__(**kw)
        self.columns = expression.ColumnCollection()
        self._pending_colargs = [_to_schema_column_or_string(c) for c in columns]
        if self._pending_colargs and \
                isinstance(self._pending_colargs[0], Column) and \
                self._pending_colargs[0].table is not None:
            self._set_parent(self._pending_colargs[0].table)
        
    def _set_parent(self, table):
        super(ColumnCollectionConstraint, self)._set_parent(table)
        for col in self._pending_colargs:
            if isinstance(col, basestring):
                col = table.c[col]
            self.columns.add(col)

    def __contains__(self, x):
        return x in self.columns

    def copy(self, **kw):
        return self.__class__(name=self.name, deferrable=self.deferrable,
                              initially=self.initially, *self.columns.keys())

    def contains_column(self, col):
        return self.columns.contains_column(col)

    def __iter__(self):
        return iter(self.columns)

    def __len__(self):
        return len(self.columns)


class CheckConstraint(Constraint):
    """A table- or column-level CHECK constraint.

    Can be included in the definition of a Table or Column.
    """

    def __init__(self, sqltext, name=None, deferrable=None, initially=None, table=None):
        """Construct a CHECK constraint.

        sqltext
          A string containing the constraint definition.  Will be used
          verbatim.

        name
          Optional, the in-database name of the constraint.

        deferrable
          Optional bool.  If set, emit DEFERRABLE or NOT DEFERRABLE when
          issuing DDL for this constraint.

        initially
          Optional string.  If set, emit INITIALLY <value> when issuing DDL
          for this constraint.
          
        """

        super(CheckConstraint, self).__init__(name, deferrable, initially)
        if not isinstance(sqltext, basestring):
            raise exc.ArgumentError(
                "sqltext must be a string and will be used verbatim.")
        self.sqltext = sqltext
        if table is not None:
            self._set_parent(table)
            
    def __visit_name__(self):
        if isinstance(self.parent, Table):
            return "check_constraint"
        else:
            return "column_check_constraint"
    __visit_name__ = property(__visit_name__)

    def copy(self, **kw):
        return CheckConstraint(self.sqltext, name=self.name)

class ForeignKeyConstraint(Constraint):
    """A table-level FOREIGN KEY constraint.

    Defines a single column or composite FOREIGN KEY ... REFERENCES
    constraint. For a no-frills, single column foreign key, adding a
    :class:`ForeignKey` to the definition of a :class:`Column` is a shorthand
    equivalent for an unnamed, single column :class:`ForeignKeyConstraint`.
    
    Examples of foreign key configuration are in :ref:`metadata_foreignkeys`.
    
    """
    __visit_name__ = 'foreign_key_constraint'

    def __init__(self, columns, refcolumns, name=None, onupdate=None,
            ondelete=None, deferrable=None, initially=None, use_alter=False,
            link_to_name=False, table=None):
        """Construct a composite-capable FOREIGN KEY.

        :param columns: A sequence of local column names. The named columns
          must be defined and present in the parent Table. The names should
          match the ``key`` given to each column (defaults to the name) unless
          ``link_to_name`` is True.

        :param refcolumns: A sequence of foreign column names or Column
          objects. The columns must all be located within the same Table.

        :param name: Optional, the in-database name of the key.

        :param onupdate: Optional string. If set, emit ON UPDATE <value> when
          issuing DDL for this constraint. Typical values include CASCADE,
          DELETE and RESTRICT.

        :param ondelete: Optional string. If set, emit ON DELETE <value> when
          issuing DDL for this constraint. Typical values include CASCADE,
          DELETE and RESTRICT.

        :param deferrable: Optional bool. If set, emit DEFERRABLE or NOT
          DEFERRABLE when issuing DDL for this constraint.

        :param initially: Optional string. If set, emit INITIALLY <value> when
          issuing DDL for this constraint.

        :param link_to_name: if True, the string name given in ``column`` is
          the rendered name of the referenced column, not its locally assigned
          ``key``.

        :param use_alter: If True, do not emit the DDL for this constraint as
          part of the CREATE TABLE definition. Instead, generate it via an
          ALTER TABLE statement issued after the full collection of tables
          have been created, and drop it via an ALTER TABLE statement before
          the full collection of tables are dropped. This is shorthand for the
          usage of :class:`AddConstraint` and :class:`DropConstraint` applied
          as "after-create" and "before-drop" events on the MetaData object.
          This is normally used to generate/drop constraints on objects that
          are mutually dependent on each other.
          
        """
        super(ForeignKeyConstraint, self).__init__(name, deferrable, initially)

        self.onupdate = onupdate
        self.ondelete = ondelete
        self.link_to_name = link_to_name
        if self.name is None and use_alter:
            raise exc.ArgumentError("Alterable Constraint requires a name")
        self.use_alter = use_alter

        self._elements = util.OrderedDict()
        for col, refcol in zip(columns, refcolumns):
            self._elements[col] = ForeignKey(
                    refcol, 
                    _constraint=self, 
                    name=self.name, 
                    onupdate=self.onupdate, 
                    ondelete=self.ondelete, 
                    use_alter=self.use_alter, 
                    link_to_name=self.link_to_name
                )

        if table:
            self._set_parent(table)
    
    @property
    def columns(self):
        return self._elements.keys()
        
    @property
    def elements(self):
        return self._elements.values()
        
    def _set_parent(self, table):
        super(ForeignKeyConstraint, self)._set_parent(table)
        for col, fk in self._elements.iteritems():
            if isinstance(col, basestring):
                col = table.c[col]
            fk._set_parent(col)
            
        if self.use_alter:
            def supports_alter(ddl, event, schema_item, bind, **kw):
                return table in set(kw['tables']) and bind.dialect.supports_alter
            AddConstraint(self, on=supports_alter).execute_at('after-create', table.metadata)
            DropConstraint(self, on=supports_alter).execute_at('before-drop', table.metadata)
            
    def copy(self, **kw):
        return ForeignKeyConstraint(
                    [x.parent.name for x in self._elements.values()], 
                    [x._get_colspec(**kw) for x in self._elements.values()], 
                    name=self.name, 
                    onupdate=self.onupdate, 
                    ondelete=self.ondelete, 
                    use_alter=self.use_alter,
                    deferrable=self.deferrable,
                    initially=self.initially,
                    link_to_name=self.link_to_name
                )

class PrimaryKeyConstraint(ColumnCollectionConstraint):
    """A table-level PRIMARY KEY constraint.

    Defines a single column or composite PRIMARY KEY constraint. For a
    no-frills primary key, adding ``primary_key=True`` to one or more
    ``Column`` definitions is a shorthand equivalent for an unnamed single- or
    multiple-column PrimaryKeyConstraint.
    """

    __visit_name__ = 'primary_key_constraint'

    def _set_parent(self, table):
        super(PrimaryKeyConstraint, self)._set_parent(table)
        table._set_primary_key(self)

    def _replace(self, col):
        self.columns.replace(col)

class UniqueConstraint(ColumnCollectionConstraint):
    """A table-level UNIQUE constraint.

    Defines a single column or composite UNIQUE constraint. For a no-frills,
    single column constraint, adding ``unique=True`` to the ``Column``
    definition is a shorthand equivalent for an unnamed, single column
    UniqueConstraint.
    """

    __visit_name__ = 'unique_constraint'

class Index(SchemaItem):
    """A table-level INDEX.

    Defines a composite (one or more column) INDEX. For a no-frills, single
    column index, adding ``index=True`` to the ``Column`` definition is
    a shorthand equivalent for an unnamed, single column Index.
    """

    __visit_name__ = 'index'

    def __init__(self, name, *columns, **kwargs):
        """Construct an index object.

        Arguments are:

        name
          The name of the index

        \*columns
          Columns to include in the index. All columns must belong to the same
          table.

        \**kwargs
          Keyword arguments include:

          unique
            Defaults to False: create a unique index.

          postgresql_where
            Defaults to None: create a partial index when using PostgreSQL
        """

        self.name = name
        self.columns = expression.ColumnCollection()
        self.table = None
        self.unique = kwargs.pop('unique', False)
        self.kwargs = kwargs

        for column in columns:
            column = _to_schema_column(column)
            if self.table is None:
                self._set_parent(column.table)
            elif column.table != self.table:
                # all columns muse be from same table
                raise exc.ArgumentError(
                    "All index columns must be from same table. "
                    "%s is from %s not %s" % (column, column.table, self.table))
            self.columns.add(column)

    def _set_parent(self, table):
        self.table = table
        table.indexes.add(self)

    @property
    def bind(self):
        """Return the connectable associated with this Index."""
        
        return self.table.bind

    def create(self, bind=None):
        if bind is None:
            bind = _bind_or_error(self)
        bind.create(self)
        return self

    def drop(self, bind=None):
        if bind is None:
            bind = _bind_or_error(self)
        bind.drop(self)

    def __repr__(self):
        return 'Index("%s", %s%s)' % (self.name,
                                      ', '.join(repr(c) for c in self.columns),
                                      (self.unique and ', unique=True') or '')

class MetaData(SchemaItem):
    """A collection of Tables and their associated schema constructs.

    Holds a collection of Tables and an optional binding to an ``Engine`` or
    ``Connection``.  If bound, the :class:`~sqlalchemy.schema.Table` objects
    in the collection and their columns may participate in implicit SQL
    execution.

    The `Table` objects themselves are stored in the `metadata.tables`
    dictionary.

    The ``bind`` property may be assigned to dynamically.  A common pattern is
    to start unbound and then bind later when an engine is available::

      metadata = MetaData()
      # define tables
      Table('mytable', metadata, ...)
      # connect to an engine later, perhaps after loading a URL from a
      # configuration file
      metadata.bind = an_engine

    MetaData is a thread-safe object after tables have been explicitly defined
    or loaded via reflection.

    .. index::
      single: thread safety; MetaData

    """

    __visit_name__ = 'metadata'

    ddl_events = ('before-create', 'after-create', 'before-drop', 'after-drop')

    def __init__(self, bind=None, reflect=False):
        """Create a new MetaData object.

        bind
          An Engine or Connection to bind to.  May also be a string or URL
          instance, these are passed to create_engine() and this MetaData will
          be bound to the resulting engine.

        reflect
          Optional, automatically load all tables from the bound database.
          Defaults to False. ``bind`` is required when this option is set.
          For finer control over loaded tables, use the ``reflect`` method of
          ``MetaData``.

        """
        self.tables = {}
        self.bind = bind
        self.metadata = self
        self.ddl_listeners = util.defaultdict(list)
        if reflect:
            if not bind:
                raise exc.ArgumentError(
                    "A bind must be supplied in conjunction with reflect=True")
            self.reflect()

    def __repr__(self):
        return 'MetaData(%r)' % self.bind

    def __contains__(self, table_or_key):
        if not isinstance(table_or_key, basestring):
            table_or_key = table_or_key.key
        return table_or_key in self.tables

    def __getstate__(self):
        return {'tables': self.tables}

    def __setstate__(self, state):
        self.tables = state['tables']
        self._bind = None

    def is_bound(self):
        """True if this MetaData is bound to an Engine or Connection."""

        return self._bind is not None

    def bind(self):
        """An Engine or Connection to which this MetaData is bound.

        This property may be assigned an ``Engine`` or ``Connection``, or
        assigned a string or URL to automatically create a basic ``Engine``
        for this bind with ``create_engine()``.
        
        """
        return self._bind

    def _bind_to(self, bind):
        """Bind this MetaData to an Engine, Connection, string or URL."""

        global URL
        if URL is None:
            from sqlalchemy.engine.url import URL

        if isinstance(bind, (basestring, URL)):
            from sqlalchemy import create_engine
            self._bind = create_engine(bind)
        else:
            self._bind = bind
    bind = property(bind, _bind_to)

    def clear(self):
        """Clear all Table objects from this MetaData."""
        # TODO: why have clear()/remove() but not all
        # other accesors/mutators for the tables dict ?
        self.tables.clear()

    def remove(self, table):
        """Remove the given Table object from this MetaData."""
        
        # TODO: scan all other tables and remove FK _column
        del self.tables[table.key]

    @property
    def sorted_tables(self):
        """Returns a list of ``Table`` objects sorted in order of
        dependency.
        """
        from sqlalchemy.sql.util import sort_tables
        return sort_tables(self.tables.itervalues())
        
    def reflect(self, bind=None, schema=None, only=None):
        """Load all available table definitions from the database.

        Automatically creates ``Table`` entries in this ``MetaData`` for any
        table available in the database but not yet present in the
        ``MetaData``.  May be called multiple times to pick up tables recently
        added to the database, however no special action is taken if a table
        in this ``MetaData`` no longer exists in the database.

        bind
          A :class:`~sqlalchemy.engine.base.Connectable` used to access the database; if None, uses the
          existing bind on this ``MetaData``, if any.

        schema
          Optional, query and reflect tables from an alterate schema.

        only
          Optional.  Load only a sub-set of available named tables.  May be
          specified as a sequence of names or a callable.

          If a sequence of names is provided, only those tables will be
          reflected.  An error is raised if a table is requested but not
          available.  Named tables already present in this ``MetaData`` are
          ignored.

          If a callable is provided, it will be used as a boolean predicate to
          filter the list of potential table names.  The callable is called
          with a table name and this ``MetaData`` instance as positional
          arguments and should return a true value for any table to reflect.

        """
        reflect_opts = {'autoload': True}
        if bind is None:
            bind = _bind_or_error(self)
            conn = None
        else:
            reflect_opts['autoload_with'] = bind
            conn = bind.contextual_connect()

        if schema is not None:
            reflect_opts['schema'] = schema

        available = util.OrderedSet(bind.engine.table_names(schema,
                                                            connection=conn))
        current = set(self.tables.iterkeys())

        if only is None:
            load = [name for name in available if name not in current]
        elif util.callable(only):
            load = [name for name in available
                    if name not in current and only(name, self)]
        else:
            missing = [name for name in only if name not in available]
            if missing:
                s = schema and (" schema '%s'" % schema) or ''
                raise exc.InvalidRequestError(
                    'Could not reflect: requested table(s) not available '
                    'in %s%s: (%s)' % (bind.engine.url, s, ', '.join(missing)))
            load = [name for name in only if name not in current]

        for name in load:
            Table(name, self, **reflect_opts)

    def append_ddl_listener(self, event, listener):
        """Append a DDL event listener to this ``MetaData``.

        The ``listener`` callable will be triggered when this ``MetaData`` is
        involved in DDL creates or drops, and will be invoked either before
        all Table-related actions or after.

        Arguments are:

        event
          One of ``MetaData.ddl_events``; 'before-create', 'after-create',
          'before-drop' or 'after-drop'.
        listener
          A callable, invoked with three positional arguments:

          event
            The event currently being handled
          target
            The ``MetaData`` object being operated upon
          bind
            The ``Connection`` bueing used for DDL execution.

        Listeners are added to the MetaData's ``ddl_listeners`` attribute.

        Note: MetaData listeners are invoked even when ``Tables`` are created
        in isolation.  This may change in a future release. I.e.::

          # triggers all MetaData and Table listeners:
          metadata.create_all()

          # triggers MetaData listeners too:
          some.table.create()

        """
        if event not in self.ddl_events:
            raise LookupError(event)
        self.ddl_listeners[event].append(listener)

    def create_all(self, bind=None, tables=None, checkfirst=True):
        """Create all tables stored in this metadata.

        Conditional by default, will not attempt to recreate tables already
        present in the target database.

        bind
          A :class:`~sqlalchemy.engine.base.Connectable` used to access the database; if None, uses the
          existing bind on this ``MetaData``, if any.

        tables
          Optional list of ``Table`` objects, which is a subset of the total
          tables in the ``MetaData`` (others are ignored).

        checkfirst
          Defaults to True, don't issue CREATEs for tables already present
          in the target database.
          
        """
        if bind is None:
            bind = _bind_or_error(self)
        bind.create(self, checkfirst=checkfirst, tables=tables)

    def drop_all(self, bind=None, tables=None, checkfirst=True):
        """Drop all tables stored in this metadata.

        Conditional by default, will not attempt to drop tables not present in
        the target database.

        bind
          A :class:`~sqlalchemy.engine.base.Connectable` used to access the database; if None, uses
          the existing bind on this ``MetaData``, if any.

        tables
          Optional list of ``Table`` objects, which is a subset of the
          total tables in the ``MetaData`` (others are ignored).

        checkfirst
          Defaults to True, only issue DROPs for tables confirmed to be present
          in the target database.

        """
        if bind is None:
            bind = _bind_or_error(self)
        bind.drop(self, checkfirst=checkfirst, tables=tables)

class ThreadLocalMetaData(MetaData):
    """A MetaData variant that presents a different ``bind`` in every thread.

    Makes the ``bind`` property of the MetaData a thread-local value, allowing
    this collection of tables to be bound to different ``Engine``
    implementations or connections in each thread.

    The ThreadLocalMetaData starts off bound to None in each thread.  Binds
    must be made explicitly by assigning to the ``bind`` property or using
    ``connect()``.  You can also re-bind dynamically multiple times per
    thread, just like a regular ``MetaData``.

    """

    __visit_name__ = 'metadata'

    def __init__(self):
        """Construct a ThreadLocalMetaData."""

        self.context = util.threading.local()
        self.__engines = {}
        super(ThreadLocalMetaData, self).__init__()

    def bind(self):
        """The bound Engine or Connection for this thread.

        This property may be assigned an Engine or Connection, or assigned a
        string or URL to automatically create a basic Engine for this bind
        with ``create_engine()``."""

        return getattr(self.context, '_engine', None)

    def _bind_to(self, bind):
        """Bind to a Connectable in the caller's thread."""

        global URL
        if URL is None:
            from sqlalchemy.engine.url import URL

        if isinstance(bind, (basestring, URL)):
            try:
                self.context._engine = self.__engines[bind]
            except KeyError:
                from sqlalchemy import create_engine
                e = create_engine(bind)
                self.__engines[bind] = e
                self.context._engine = e
        else:
            # TODO: this is squirrely.  we shouldnt have to hold onto engines
            # in a case like this
            if bind not in self.__engines:
                self.__engines[bind] = bind
            self.context._engine = bind

    bind = property(bind, _bind_to)

    def is_bound(self):
        """True if there is a bind for this thread."""
        return (hasattr(self.context, '_engine') and
                self.context._engine is not None)

    def dispose(self):
        """Dispose all bound engines, in all thread contexts."""

        for e in self.__engines.itervalues():
            if hasattr(e, 'dispose'):
                e.dispose()

class SchemaVisitor(visitors.ClauseVisitor):
    """Define the visiting for ``SchemaItem`` objects."""

    __traverse_options__ = {'schema_visitor':True}


class DDLElement(expression.ClauseElement):
    """Base class for DDL expression constructs."""
    
    supports_execution = True
    _autocommit = True

    target = None
    on = None
    
    def execute(self, bind=None, target=None):
        """Execute this DDL immediately.

        Executes the DDL statement in isolation using the supplied
        :class:`~sqlalchemy.engine.base.Connectable` or :class:`~sqlalchemy.engine.base.Connectable` assigned to the ``.bind`` property,
        if not supplied.  If the DDL has a conditional ``on`` criteria, it
        will be invoked with None as the event.

        bind
          Optional, an ``Engine`` or ``Connection``.  If not supplied, a
          valid :class:`~sqlalchemy.engine.base.Connectable` must be present in the ``.bind`` property.

        target
          Optional, defaults to None.  The target SchemaItem for the 
          execute call.  Will be passed to the ``on`` callable if any, 
          and may also provide string expansion data for the
          statement. See ``execute_at`` for more information.
        """

        if bind is None:
            bind = _bind_or_error(self)

        if self._should_execute(None, target, bind):
            return bind.execute(self.against(target))
        else:
            bind.engine.logger.info("DDL execution skipped, criteria not met.")

    def execute_at(self, event, target):
        """Link execution of this DDL to the DDL lifecycle of a SchemaItem.

        Links this ``DDLElement`` to a ``Table`` or ``MetaData`` instance, executing
        it when that schema item is created or dropped.  The DDL statement
        will be executed using the same Connection and transactional context
        as the Table create/drop itself.  The ``.bind`` property of this
        statement is ignored.
        
        event
          One of the events defined in the schema item's ``.ddl_events``;
          e.g. 'before-create', 'after-create', 'before-drop' or 'after-drop'

        target
          The Table or MetaData instance for which this DDLElement will
          be associated with.

        A DDLElement instance can be linked to any number of schema items. 

        ``execute_at`` builds on the ``append_ddl_listener`` interface of
        MetaDta and Table objects.

        Caveat: Creating or dropping a Table in isolation will also trigger
        any DDL set to ``execute_at`` that Table's MetaData.  This may change
        in a future release.
        """

        if not hasattr(target, 'ddl_listeners'):
            raise exc.ArgumentError(
                "%s does not support DDL events" % type(target).__name__)
        if event not in target.ddl_events:
            raise exc.ArgumentError(
                "Unknown event, expected one of (%s), got '%r'" %
                (', '.join(target.ddl_events), event))
        target.ddl_listeners[event].append(self)
        return self

    @expression._generative
    def against(self, target):
        """Return a copy of this DDL against a specific schema item."""

        self.target = target

    def __call__(self, event, target, bind, **kw):
        """Execute the DDL as a ddl_listener."""

        if self._should_execute(event, target, bind, **kw):
            return bind.execute(self.against(target))

    def _check_ddl_on(self, on):
        if (on is not None and
            (not isinstance(on, (basestring, tuple, list, set)) and not util.callable(on))):
            raise exc.ArgumentError(
                "Expected the name of a database dialect, a tuple of names, or a callable for "
                "'on' criteria, got type '%s'." % type(on).__name__)

    def _should_execute(self, event, target, bind, **kw):
        if self.on is None:
            return True
        elif isinstance(self.on, basestring):
            return self.on == bind.engine.name
        elif isinstance(self.on, (tuple, list, set)):
            return bind.engine.name in self.on
        else:
            return self.on(self, event, target, bind, **kw)

    def bind(self):
        if self._bind:
            return self._bind
    def _set_bind(self, bind):
        self._bind = bind
    bind = property(bind, _set_bind)

    def _generate(self):
        s = self.__class__.__new__(self.__class__)
        s.__dict__ = self.__dict__.copy()
        return s
    
    def _compiler(self, dialect, **kw):
        """Return a compiler appropriate for this ClauseElement, given a Dialect."""
        
        return dialect.ddl_compiler(dialect, self, **kw)

class DDL(DDLElement):
    """A literal DDL statement.

    Specifies literal SQL DDL to be executed by the database.  DDL objects can
    be attached to ``Tables`` or ``MetaData`` instances, conditionally
    executing SQL as part of the DDL lifecycle of those schema items.  Basic
    templating support allows a single DDL instance to handle repetitive tasks
    for multiple tables.

    Examples::

      tbl = Table('users', metadata, Column('uid', Integer)) # ...
      DDL('DROP TRIGGER users_trigger').execute_at('before-create', tbl)

      spow = DDL('ALTER TABLE %(table)s SET secretpowers TRUE', on='somedb')
      spow.execute_at('after-create', tbl)

      drop_spow = DDL('ALTER TABLE users SET secretpowers FALSE')
      connection.execute(drop_spow)

    When operating on Table events, the following ``statement``
    string substitions are available::

      %(table)s  - the Table name, with any required quoting applied
      %(schema)s - the schema name, with any required quoting applied
      %(fullname)s - the Table name including schema, quoted if needed

    The DDL's ``context``, if any, will be combined with the standard
    substutions noted above.  Keys present in the context will override
    the standard substitutions.

    """

    __visit_name__ = "ddl"
    
    def __init__(self, statement, on=None, context=None, bind=None):
        """Create a DDL statement.

        statement
          A string or unicode string to be executed.  Statements will be
          processed with Python's string formatting operator.  See the
          ``context`` argument and the ``execute_at`` method.

          A literal '%' in a statement must be escaped as '%%'.

          SQL bind parameters are not available in DDL statements.

        on
          Optional filtering criteria.  May be a string, tuple or a callable
          predicate.  If a string, it will be compared to the name of the
          executing database dialect::

            DDL('something', on='postgresql')

          If a tuple, specifies multiple dialect names::

            DDL('something', on=('postgresql', 'mysql'))

          If a callable, it will be invoked with four positional arguments
          as well as optional keyword arguments:
            
            ddl
              This DDL element.
              
            event
              The name of the event that has triggered this DDL, such as
              'after-create' Will be None if the DDL is executed explicitly.

            target
              The ``Table`` or ``MetaData`` object which is the target of 
              this event. May be None if the DDL is executed explicitly.

            connection
              The ``Connection`` being used for DDL execution

            \**kw
              Keyword arguments which may be sent include:
                tables - a list of Table objects which are to be created/
                dropped within a MetaData.create_all() or drop_all() method
                call.
              
          If the callable returns a true value, the DDL statement will be
          executed.

        context
          Optional dictionary, defaults to None.  These values will be
          available for use in string substitutions on the DDL statement.

        bind
          Optional. A :class:`~sqlalchemy.engine.base.Connectable`, used by default when ``execute()``
          is invoked without a bind argument.
          
        """

        if not isinstance(statement, basestring):
            raise exc.ArgumentError(
                "Expected a string or unicode SQL statement, got '%r'" %
                statement)

        self.statement = statement
        self.context = context or {}

        self._check_ddl_on(on)
        self.on = on
        self._bind = bind


    def __repr__(self):
        return '<%s@%s; %s>' % (
            type(self).__name__, id(self),
            ', '.join([repr(self.statement)] +
                      ['%s=%r' % (key, getattr(self, key))
                       for key in ('on', 'context')
                       if getattr(self, key)]))

def _to_schema_column(element):
   if hasattr(element, '__clause_element__'):
       element = element.__clause_element__()
   if not isinstance(element, Column):
       raise exc.ArgumentError("schema.Column object expected")
   return element

def _to_schema_column_or_string(element):
  if hasattr(element, '__clause_element__'):
      element = element.__clause_element__()
  return element

class _CreateDropBase(DDLElement):
    """Base class for DDL constucts that represent CREATE and DROP or equivalents.

    The common theme of _CreateDropBase is a single
    ``element`` attribute which refers to the element
    to be created or dropped.
    
    """
    
    def __init__(self, element, on=None, bind=None):
        self.element = element
        self._check_ddl_on(on)
        self.on = on
        self.bind = bind
        element.inline_ddl = False

class CreateTable(_CreateDropBase):
    """Represent a CREATE TABLE statement."""
    
    __visit_name__ = "create_table"
    
class DropTable(_CreateDropBase):
    """Represent a DROP TABLE statement."""

    __visit_name__ = "drop_table"

    def __init__(self, element, cascade=False, **kw):
        self.cascade = cascade
        super(DropTable, self).__init__(element, **kw)

class CreateSequence(_CreateDropBase):
    """Represent a CREATE SEQUENCE statement."""
    
    __visit_name__ = "create_sequence"

class DropSequence(_CreateDropBase):
    """Represent a DROP SEQUENCE statement."""

    __visit_name__ = "drop_sequence"
    
class CreateIndex(_CreateDropBase):
    """Represent a CREATE INDEX statement."""
    
    __visit_name__ = "create_index"

class DropIndex(_CreateDropBase):
    """Represent a DROP INDEX statement."""

    __visit_name__ = "drop_index"

class AddConstraint(_CreateDropBase):
    """Represent an ALTER TABLE ADD CONSTRAINT statement."""
    
    __visit_name__ = "add_constraint"

class DropConstraint(_CreateDropBase):
    """Represent an ALTER TABLE DROP CONSTRAINT statement."""

    __visit_name__ = "drop_constraint"
    
    def __init__(self, element, cascade=False, **kw):
        self.cascade = cascade
        super(DropConstraint, self).__init__(element, **kw)

def _bind_or_error(schemaitem):
    bind = schemaitem.bind
    if not bind:
        name = schemaitem.__class__.__name__
        label = getattr(schemaitem, 'fullname',
                        getattr(schemaitem, 'name', None))
        if label:
            item = '%s %r' % (name, label)
        else:
            item = name
        if isinstance(schemaitem, (MetaData, DDL)):
            bindable = "the %s's .bind" % name
        else:
            bindable = "this %s's .metadata.bind" % name

        msg = ('The %s is not bound to an Engine or Connection.  '
               'Execution can not proceed without a database to execute '
               'against.  Either execute with an explicit connection or '
               'assign %s to enable implicit execution.') % (item, bindable)
        raise exc.UnboundExecutionError(msg)
    return bind